├── setup.py ├── .gitignore ├── requirements.txt ├── train ├── requirements.txt ├── __init__.py ├── optimization_test.py ├── .gitignore ├── sample_text.txt ├── tokenization_test.py ├── optimization.py ├── modeling_test.py ├── LICENSE ├── tokenization.py ├── extract_features.py ├── create_pretraining_data.py └── run_pretraining.py ├── reformers ├── __init__.py ├── utils.py ├── TFutils.py ├── TFattention.py ├── reformers.py ├── TFreformers.py ├── attention.py ├── efficient_attention.py ├── TFefficient_attention.py └── blocks.py ├── LICENSE ├── example.py └── README.md /setup.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | __pycache__/ -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | revtorch 2 | pytorch 3 | tensorflow -------------------------------------------------------------------------------- /train/requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow >= 2.0.0 # CPU Version of TensorFlow. 2 | # tensorflow-gpu >= 2.0.0 # GPU version of TensorFlow. 3 | -------------------------------------------------------------------------------- /reformers/__init__.py: -------------------------------------------------------------------------------- 1 | from .TFreformers import TFReformer, TFReformerLM 2 | from .TFefficient_attention import TFLSHAttention 3 | from .reformers import Reformer, ReformerLM -------------------------------------------------------------------------------- /train/__init__.py: -------------------------------------------------------------------------------- 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 | 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from reformers import ReformerLM, TFReformerLM, TFLSHAttention 2 | import torch 3 | import tensorflow as tf 4 | 5 | model = ReformerLM( 6 | num_tokens= 20000, 7 | emb = 512, 8 | depth = 12, 9 | max_seq_len = 32000, 10 | heads = 8, 11 | lsh_dropout = 0.1, 12 | causal = True, # auto-regressive or not 13 | bucket_size = 64, # average size of qk per bucket, 64 was recommended in paper 14 | n_hashes = 4, # 4 is permissible per author, 8 is the best but slower 15 | ff_chunks = 1600, # number of chunks for feedforward layer, make higher if there are memory issues 16 | weight_tie = False, # tie parameters of each layer for no memory per additional depth 17 | attn_chunks = 8, # process lsh attention in chunks, only way for memory to fit when scaling to 16k tokens 18 | use_full_attn = False # use full self attention, for comparison 19 | ) 20 | 21 | model_tf = TFReformerLM( 22 | num_tokens= 20000, 23 | emb = 512, 24 | depth = 1, 25 | max_seq_len = 32000, 26 | heads = 8, 27 | lsh_dropout = 0.1, 28 | causal = True, # auto-regressive or not 29 | bucket_size = 64, # average size of qk per bucket, 64 was recommended in paper 30 | n_hashes = 4, # 4 is permissible per author, 8 is the best but slower 31 | ff_chunks = 1600, # number of chunks for feedforward layer, make higher if there are memory issues 32 | weight_tie = False, # tie parameters of each layer for no memory per additional depth 33 | attn_chunks = 8, # process lsh attention in chunks, only way for memory to fit when scaling to 16k tokens 34 | use_full_attn = False # use full self attention, for comparison 35 | ) 36 | 37 | # x = tf.random.uniform((1, 32000)) 38 | model_tf.build(input_shape=(1,32000)) 39 | model_tf.summary() 40 | # y = model_tf(x) 41 | 42 | # x = torch.randint(0, 20000, (1, 32768)).long() 43 | # y = model(x) 44 | # y.sum().backward() -------------------------------------------------------------------------------- /train/optimization_test.py: -------------------------------------------------------------------------------- 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 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import optimization 20 | import tensorflow as tf 21 | 22 | 23 | class OptimizationTest(tf.test.TestCase): 24 | 25 | def test_adam(self): 26 | with self.test_session() as sess: 27 | w = tf.compat.v1.get_variable( 28 | "w", 29 | shape=[3], 30 | initializer=tf.compat.v1.constant_initializer([0.1, -0.2, -0.1])) 31 | x = tf.constant([0.4, 0.2, -0.5]) 32 | loss = tf.reduce_mean(input_tensor=tf.square(x - w)) 33 | tvars = tf.compat.v1.trainable_variables() 34 | grads = tf.gradients(ys=loss, xs=tvars) 35 | global_step = tf.compat.v1.train.get_or_create_global_step() 36 | optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2) 37 | train_op = optimizer.apply_gradients(zip(grads, tvars), global_step) 38 | init_op = tf.group(tf.compat.v1.global_variables_initializer(), 39 | tf.compat.v1.local_variables_initializer()) 40 | sess.run(init_op) 41 | for _ in range(100): 42 | sess.run(train_op) 43 | w_np = sess.run(w) 44 | self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2) 45 | 46 | 47 | if __name__ == "__main__": 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /train/.gitignore: -------------------------------------------------------------------------------- 1 | # Initially taken from Github's Python gitignore file 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # celery beat schedule file 86 | celerybeat-schedule 87 | 88 | # SageMath parsed files 89 | *.sage.py 90 | 91 | # Environments 92 | .env 93 | .venv 94 | env/ 95 | venv/ 96 | ENV/ 97 | env.bak/ 98 | venv.bak/ 99 | 100 | # Spyder project settings 101 | .spyderproject 102 | .spyproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | 107 | # mkdocs documentation 108 | /site 109 | 110 | # mypy 111 | .mypy_cache/ 112 | .dmypy.json 113 | dmypy.json 114 | 115 | # Pyre type checker 116 | .pyre/ 117 | -------------------------------------------------------------------------------- /reformers/utils.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Phillip Wang, 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import torch 24 | import torch.nn as nn 25 | import torch.nn.functional as F 26 | from torch.autograd import Function 27 | 28 | def make_unit_length(x, epsilon=1e-6): 29 | norm = x.norm(p=2, dim=-1, keepdim=True) 30 | return x.div(norm + epsilon) 31 | 32 | def sort_key_val(t1, t2, dim=-1): 33 | values, indices = t1.sort(dim=dim) 34 | t2 = t2.expand_as(t1) 35 | return values, t2.gather(dim, indices) 36 | 37 | def batched_index_select(values, indices): 38 | last_dim = values.shape[-1] 39 | return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim)) 40 | 41 | def process_inputs_chunk(fn, *args, chunks=1): 42 | chunked_inputs = list(map(lambda x: x.chunk(chunks, dim=0), args)) 43 | print(len(list(zip(*chunked_inputs))[0])) 44 | outputs = [fn(*input_pair) for input_pair in zip(*chunked_inputs)] 45 | return outputs 46 | 47 | def chunked_sum(tensor, chunks=1): 48 | *orig_size, last_dim = tensor.shape 49 | tensor = tensor.reshape(-1, last_dim) 50 | summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)] 51 | return torch.cat(summed_tensors, dim=0).reshape(orig_size) 52 | 53 | def cache_fn(f): 54 | cache = None 55 | def cached_fn(*args, **kwargs): 56 | nonlocal cache 57 | if cache is not None: 58 | return cache 59 | cache = f(*args, **kwargs) 60 | return cache 61 | return cached_fn 62 | 63 | 64 | class ScaleNorm(nn.Module): 65 | def __init__(self, emb, eps=1e-5): 66 | super().__init__() 67 | self.g = nn.Parameter(torch.ones(1, requires_grad=True)) 68 | self.eps = eps 69 | 70 | def forward(self, x): 71 | n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps) 72 | return x / n * self.g 73 | 74 | class WithNorm(nn.Module): 75 | def __init__(self, norm_class, emb, fn): 76 | super().__init__() 77 | self.emb = emb 78 | self.norm = norm_class(emb) 79 | self.fn = fn 80 | def forward(self, x): 81 | x = self.norm(x) 82 | return self.fn(x) 83 | 84 | class Chunk(nn.Module): 85 | def __init__(self, chunks, fn, along_dim = -1): 86 | super().__init__() 87 | self.dim = along_dim 88 | self.chunks = chunks 89 | self.fn = fn 90 | 91 | def forward(self, x): 92 | chunks = x.chunk(self.chunks, dim = self.dim) 93 | return torch.cat([self.fn(c) for c in chunks], dim = self.dim) 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reformers - Efficient Transformers 2 | 3 | This repository containes implementations of reformers as described in the following paper - [https://openreview.net/pdf?id=rkgNKkHtvB](https://openreview.net/pdf?id=rkgNKkHtvB). The following repository contains implementations of reformers in PyTorch as well as Tensorflow Keras. We will be performing more experiments on these over the course of time. 4 | 5 | ## Install 6 | 7 | clone the repository locally and install dependencies using pip install. The dependencies are present in the `requirements.txt` file. 8 | 9 | ## Usage 10 | 11 | ### PyTorch 12 | 13 | ```python 14 | import torch 15 | from reformers import ReformerLM 16 | 17 | model = ReformerLM( 18 | num_tokens= 20000, 19 | emb = 512, 20 | depth = 12, 21 | max_seq_len = 8192, 22 | heads = 8, 23 | lsh_dropout = 0.1, 24 | causal = True, # auto-regressive or not 25 | bucket_size = 64, # average size of qk per bucket, 64 was recommended in paper 26 | n_hashes = 4, # 4 is permissible per author, 8 is the best but slower 27 | ff_chunks = 200, # number of chunks for feedforward layer, make higher if there are memory issues 28 | weight_tie = False, # tie parameters of each layer for no memory per additional depth 29 | attn_chunks = 8, # process lsh attention in chunks, only way for memory to fit when scaling to 16k tokens 30 | use_full_attn = False # use full self attention, for comparison 31 | ).cuda() 32 | 33 | x = torch.randint(0, 20000, (1, 8192)).long().cuda() 34 | y = model(x) # (1, 8192, 20000) 35 | ``` 36 | 37 | ```python 38 | import torch 39 | from reformers import Reformer 40 | 41 | model = Reformer( 42 | emb = 512, 43 | depth = 12, 44 | max_seq_len = 8192, 45 | heads = 8, 46 | lsh_dropout = 0.1, 47 | causal = True 48 | ).cuda() 49 | 50 | x = torch.randn(1, 8192, 512).cuda() 51 | y = model(x) # (1, 8192, 512) 52 | ``` 53 | 54 | ### Tensorflow 55 | 56 | ```python 57 | model_tf = TFReformerLM( 58 | num_tokens= 20000, 59 | emb = 512, 60 | depth = 1, 61 | max_seq_len = 32000, 62 | heads = 8, 63 | lsh_dropout = 0.1, 64 | causal = True, # auto-regressive or not 65 | bucket_size = 64, # average size of qk per bucket, 64 was recommended in paper 66 | n_hashes = 4, # 4 is permissible per author, 8 is the best but slower 67 | ff_chunks = 1600, # number of chunks for feedforward layer, make higher if there are memory issues 68 | weight_tie = False, # tie parameters of each layer for no memory per additional depth 69 | attn_chunks = 8, # process lsh attention in chunks, only way for memory to fit when scaling to 16k tokens 70 | use_full_attn = False # use full self attention, for comparison 71 | ) 72 | 73 | model_tf.build(input_shape=(1,32000)) 74 | model_tf.summary() 75 | 76 | # Model: "tf_reformer_lm" 77 | # _________________________________________________________________ 78 | # Layer (type) Output Shape Param # 79 | # ================================================================= 80 | # embedding (Embedding) multiple 10240000 81 | # _________________________________________________________________ 82 | # embedding_1 (Embedding) multiple 16384000 83 | # _________________________________________________________________ 84 | # tf_reformer (TFReformer) multiple 2888704 85 | # _________________________________________________________________ 86 | # dense_5 (Dense) multiple 10260000 87 | # ================================================================= 88 | # Total params: 39,772,704 89 | # Trainable params: 39,772,704 90 | # Non-trainable params: 0 91 | ``` 92 | 93 | Source for PyTorch code - [https://github.com/lucidrains/reformer-pytorch](https://github.com/lucidrains/reformer-pytorch) -------------------------------------------------------------------------------- /reformers/TFutils.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import tensorflow as tf 24 | from tensorflow.keras import layers 25 | 26 | def make_unit_length(x, epsilon=1e-6): 27 | norm = tf.norm(x, ord=2, axis=-1, keepdims=True) 28 | return tf.math.truediv(x, norm + epsilon) 29 | 30 | def sort_key_val(t1, t2, dim=-1): 31 | values = tf.sort(t1, axis=dim) 32 | t2 = tf.broadcast_to(t2, t1.shape) 33 | return values, tf.gather(t2, tf.argsort(t1, axis=dim), axis=dim) 34 | 35 | def batched_index_select(values, indices): 36 | last_dim = values.shape[-1] 37 | return tf.squeeze(tf.gather(values, indices[:, :, None], axis=1)) 38 | 39 | def process_inputs_chunk(fn, *args, chunks=1): 40 | chunked_inputs = list(map(lambda x: tf.split(x, chunks, axis=0), args)) 41 | outputs = [fn(*input_pair) for input_pair in zip(*chunked_inputs)] 42 | return outputs 43 | 44 | def chunked_sum(tensor, chunks=1): 45 | *orig_size, last_dim = tensor.shape 46 | tensor = tf.reshape(tensor, [-1, last_dim]) 47 | summed_tensors = [c.sum(axis=-1) for c in tf.chunk(tensor, chunks, axis=0)] 48 | return tf.reshape(torch.concat(summed_tensors, axis=0), orig_size) 49 | 50 | def cache_fn(f): 51 | cache = None 52 | def cached_fn(*args, **kwargs): 53 | nonlocal cache 54 | if cache is not None: 55 | return cache 56 | cache = f(*args, **kwargs) 57 | return cache 58 | return cached_fn 59 | 60 | class ScaleNorm(layers.Layer): 61 | def __init__(self, emb, eps): 62 | super(ScaleNorm, self).__init__() 63 | self.g = tf.Variable(initial_value=w_init(shape=(1,), 64 | dtype='float32'), 65 | trainable=True) 66 | self.eps = eps 67 | 68 | def call(self, inputs): 69 | n = tf.norm(inputs, axis=-1, keepdims=True).clip_by_value(min=self.eps) 70 | return x / n * self.g 71 | 72 | class WithNorm(layers.Layer): 73 | def __init__(self, norm_class, emb, fn): 74 | super(WithNorm, self).__init__() 75 | self.emb = emb 76 | if isinstance(norm_class, ScaleNorm): 77 | self.norm = norm_class(emb) 78 | else: 79 | self.norm = norm_class() 80 | 81 | self.fn = fn 82 | 83 | def call(self, inputs): 84 | inputs = self.norm(inputs) 85 | return self.fn(inputs) 86 | 87 | class Chunk(layers.Layer): 88 | def __init__(self, chunks, fn, along_axis = -1): 89 | super(Chunk, self).__init__() 90 | self.axis = along_axis 91 | self.chunks = chunks 92 | self.fn = fn 93 | 94 | def call(self, inputs): 95 | chunks = tf.split(inputs, self.chunks, axis= self.axis) 96 | return tf.concat([self.fn(c) for c in chunks], axis = self.axis) -------------------------------------------------------------------------------- /train/sample_text.txt: -------------------------------------------------------------------------------- 1 | This text is included to make sure Unicode is handled properly: 力加勝北区ᴵᴺᵀᵃছজটডণত 2 | Text should be one-sentence-per-line, with empty lines between documents. 3 | This sample text is public domain and was randomly selected from Project Guttenberg. 4 | 5 | The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors. 6 | Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity. 7 | Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them. 8 | "Cass" Beard had risen early that morning, but not with a view to discovery. 9 | A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets. 10 | The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency. 11 | This was nearly opposite. 12 | Mr. Cassius crossed the highway, and stopped suddenly. 13 | Something glittered in the nearest red pool before him. 14 | Gold, surely! 15 | But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring. 16 | Looking at it more attentively, he saw that it bore the inscription, "May to Cass." 17 | Like most of his fellow gold-seekers, Cass was superstitious. 18 | 19 | The fountain of classic wisdom, Hypatia herself. 20 | As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge. 21 | From my youth I felt in me a soul above the matter-entangled herd. 22 | She revealed to me the glorious fact, that I am a spark of Divinity itself. 23 | A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's. 24 | There is a philosophic pleasure in opening one's treasures to the modest young. 25 | Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street. 26 | Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide; 27 | but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind. 28 | Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now. 29 | His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert; 30 | while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts. 31 | At last they reached the quay at the opposite end of the street; 32 | and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers. 33 | He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him. 34 | -------------------------------------------------------------------------------- /reformers/TFattention.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import math 24 | import tensorflow as tf 25 | from tensorflow.keras.layers import Dense 26 | 27 | def mask_fill_inf(matrix, mask): 28 | negmask = 1 - mask 29 | num = 3.4 * math.pow(10, 38) 30 | return (matrix * mask) + (-((negmask * num + num) - num)) 31 | 32 | class MultiHeadAttention(tf.keras.layers.Layer): 33 | 34 | def __init__(self, d_model, num_heads, name="multi_head_attention"): 35 | super(MultiHeadAttention, self).__init__(name=name) 36 | self.num_heads = num_heads 37 | self.d_model = d_model 38 | 39 | assert d_model % self.num_heads == 0 40 | self.depth = d_model // self.num_heads 41 | self.query_dense = Dense(units=d_model) 42 | self.key_dense = Dense(units=d_model) 43 | self.value_dense = Dense(units=d_model) 44 | self.dense = Dense(units=d_model) 45 | 46 | def split_heads(self, inputs, batch_size): 47 | inputs = tf.reshape( 48 | inputs, shape=(batch_size, -1, self.num_heads, self.depth)) 49 | return tf.transpose(inputs, perm=[0, 2, 1, 3]) 50 | 51 | def call(self, inputs): 52 | query, key, value, mask = inputs['query'], inputs['key'], inputs[ 53 | 'value'], inputs['mask'] 54 | batch_size = tf.shape(query)[0] 55 | 56 | # linear layers 57 | query = self.query_dense(query) 58 | key = self.key_dense(key) 59 | value = self.value_dense(value) 60 | 61 | # split heads 62 | query = self.split_heads(query, batch_size) 63 | key = self.split_heads(key, batch_size) 64 | value = self.split_heads(value, batch_size) 65 | 66 | scaled_attention = scaled_dot_product_attention(query, key, value, mask) 67 | scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) 68 | concat_attention = tf.reshape(scaled_attention, 69 | (batch_size, -1, self.d_model)) 70 | 71 | outputs = self.dense(concat_attention) 72 | return outputs 73 | 74 | 75 | class TFSelfAttention(tf.keras.Model): 76 | def __init__(self, emb, heads = 8, causal = False): 77 | super().__init__() 78 | assert emb % heads == 0, 'dimensions must be divisible by number of heads' 79 | self.attn = MultiheadAttention(emb, heads) 80 | self.to_out = Dense(emb, emb) 81 | self.causal = causal 82 | 83 | def call(self, inputs): 84 | b, t, e = inputs.shape 85 | inputs = tf.transpose(inputs, (0, 1)) 86 | 87 | attn_mask = tf.zeros(t, t) 88 | if self.causal: 89 | causal_mask = tf.triu(tf.ones(t, t) == 1, 1) 90 | mask_fill_inf(attn_mask, causal_mask) 91 | 92 | output = self.attn({'query' : x, 'key' : x, 'value' : x, 'mask' : attn_mask}) 93 | return self.to_out(tf.transpose(output, (0, 1))) 94 | 95 | 96 | class TFFeedForward(tf.keras.Model): 97 | def __init__(self, emb, mult = 4): 98 | super().__init__() 99 | self.emb = emb 100 | self.proj_in = Dense(emb * mult) 101 | self.proj_out = Dense(emb) 102 | 103 | def call(self, inputs): 104 | inputs = self.proj_in(inputs) 105 | inputs = tf.keras.activations.relu(inputs) 106 | inputs = self.proj_out(inputs) 107 | return inputs -------------------------------------------------------------------------------- /reformers/reformers.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Phillip Wang, 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import torch 24 | import torch.nn as nn 25 | import torch.nn.functional as F 26 | from torch.autograd import Function 27 | from revtorch import ReversibleBlock, ReversibleSequence 28 | from .attention import SelfAttention, FeedForward 29 | from .efficient_attention import LSHSelfAttention 30 | from .utils import WithNorm, Chunk 31 | 32 | class Reformer(nn.Module): 33 | def __init__(self, emb, depth, max_seq_len, heads = 8, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., lsh_attend_across_buckets = True, lsh_allow_duplicate_attention = True, random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_full_attn = False): 34 | super().__init__() 35 | self.emb = emb 36 | self.depth = depth 37 | 38 | get_full_attn = lambda: SelfAttention(emb, heads, causal = causal) 39 | get_lsh_attn = lambda: LSHSelfAttention(emb, heads, bucket_size, n_hashes, causal = causal, dropout = lsh_dropout, attn_chunks = attn_chunks, allow_duplicate_attention = lsh_allow_duplicate_attention, attend_across_buckets = lsh_attend_across_buckets, random_rotations_per_head = random_rotations_per_head) 40 | 41 | get_attn = get_full_attn if use_full_attn else get_lsh_attn 42 | get_ff = lambda: FeedForward(emb) 43 | 44 | if weight_tie: 45 | get_attn = cache_fn(get_attn) 46 | get_ff = cache_fn(get_ff) 47 | 48 | blocks = [] 49 | norm_type = ScaleNorm if use_scale_norm else nn.LayerNorm 50 | 51 | for _ in range(depth): 52 | attn = get_attn() 53 | parallel_net = get_attn() if twin_attention else get_ff() 54 | 55 | f = WithNorm(norm_type, emb, attn) 56 | g = WithNorm(norm_type, emb, parallel_net) 57 | 58 | if not twin_attention and ff_chunks > 1: 59 | g = Chunk(ff_chunks, g, along_dim = -2) 60 | 61 | blocks.append(ReversibleBlock(f, g, split_along_dim=-1)) 62 | 63 | self.layers = ReversibleSequence(nn.ModuleList(blocks)) 64 | 65 | def forward(self, x): 66 | x = torch.cat([x, x], dim = -1) 67 | x = self.layers(x) 68 | return torch.stack(x.chunk(2, dim=-1)).sum(dim=0) 69 | 70 | class ReformerLM(nn.Module): 71 | def __init__(self, num_tokens, emb, depth, max_seq_len, heads = 8, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_full_attn = False): 72 | super().__init__() 73 | self.token_emb = nn.Embedding(num_tokens, emb) 74 | self.pos_emb = nn.Embedding(max_seq_len, emb) 75 | self.reformer = Reformer(emb, depth, max_seq_len, heads = heads, bucket_size = bucket_size, n_hashes = n_hashes, ff_chunks = ff_chunks, attn_chunks = attn_chunks, causal = causal, weight_tie = weight_tie, lsh_dropout = lsh_dropout, random_rotations_per_head = random_rotations_per_head, twin_attention = twin_attention, use_scale_norm = use_scale_norm, use_full_attn = use_full_attn) 76 | self.to_logits = nn.Linear(emb, num_tokens) 77 | 78 | def forward(self, x): 79 | x = self.token_emb(x) + self.pos_emb(torch.arange(x.shape[1], device=x.device)) 80 | x = self.reformer(x) 81 | return self.to_logits(x) 82 | 83 | -------------------------------------------------------------------------------- /reformers/TFreformers.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import tensorflow as tf 24 | from tensorflow.keras.layers import Embedding, LayerNormalization, Dense 25 | from .TFefficient_attention import TFLSHAttention, TFLSHSelfAttention 26 | from .TFattention import TFSelfAttention, TFFeedForward 27 | from .TFutils import cache_fn, Chunk, WithNorm 28 | from .blocks import ReversibleBlock, ReversibleSequence 29 | 30 | class TFReformer(tf.keras.Model): 31 | def __init__(self, emb, depth, max_seq_len, heads = 8, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., lsh_attend_across_buckets = True, lsh_allow_duplicate_attention = True, random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_full_attn = False): 32 | super().__init__() 33 | self.emb = emb 34 | self.depth = depth 35 | 36 | get_full_attn = lambda: TFSelfAttention(emb, heads, causal = causal) 37 | get_lsh_attn = lambda: TFLSHSelfAttention(emb, heads, bucket_size, n_hashes, causal = causal, dropout = lsh_dropout, attn_chunks = attn_chunks, allow_duplicate_attention = lsh_allow_duplicate_attention, attend_across_buckets = lsh_attend_across_buckets, random_rotations_per_head = random_rotations_per_head) 38 | 39 | get_attn = get_full_attn if use_full_attn else get_lsh_attn 40 | get_ff = lambda: TFFeedForward(emb) 41 | 42 | if weight_tie: 43 | get_attn = cache_fn(get_attn) 44 | get_ff = cache_fn(get_ff) 45 | 46 | blocks = [] 47 | norm_type = ScaleNorm if use_scale_norm else LayerNormalization 48 | 49 | for _ in range(depth): 50 | attn = get_attn() 51 | parallel_net = get_attn() if twin_attention else get_ff() 52 | f = WithNorm(norm_type, emb, attn) 53 | g = WithNorm(norm_type, emb, parallel_net) 54 | 55 | if not twin_attention and ff_chunks > 1: 56 | g = Chunk(ff_chunks, g, along_axis = -2) 57 | 58 | blocks.append(ReversibleBlock(f, g, split_along_axis=-1)) 59 | 60 | self.model_layers = ReversibleSequence(blocks) 61 | 62 | def call(self, x): 63 | x = tf.concat([x, x], axis = -1) 64 | x = self.model_layers(x) 65 | return tf.stack(tf.reduce_sum(tf.split(x, 2, axis=-1), axis=0)) 66 | 67 | class TFReformerLM(tf.keras.Model): 68 | def __init__(self, num_tokens, emb, depth, max_seq_len, heads = 8, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., random_rotations_per_head = False, twin_attention = False, use_scale_norm = False, use_full_attn = False): 69 | super().__init__() 70 | self.token_emb = Embedding(num_tokens, emb) 71 | self.pos_emb = Embedding(max_seq_len, emb) 72 | self.reformer = TFReformer(emb, depth, max_seq_len, heads = heads, bucket_size = bucket_size, n_hashes = n_hashes, ff_chunks = ff_chunks, attn_chunks = attn_chunks, causal = causal, weight_tie = weight_tie, lsh_dropout = lsh_dropout, random_rotations_per_head = random_rotations_per_head, twin_attention = twin_attention, use_scale_norm = use_scale_norm, use_full_attn = use_full_attn) 73 | self.to_logits = Dense(num_tokens) 74 | 75 | def call(self, inputs): 76 | print(inputs.shape) 77 | inputs = self.token_emb(inputs) + self.pos_emb(tf.range(inputs.shape[1])) 78 | inputs = self.reformer(inputs) 79 | return self.to_logits(inputs) -------------------------------------------------------------------------------- /train/tokenization_test.py: -------------------------------------------------------------------------------- 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 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import os 20 | import tempfile 21 | import tokenization 22 | import six 23 | import tensorflow as tf 24 | 25 | 26 | class TokenizationTest(tf.test.TestCase): 27 | 28 | def test_full_tokenizer(self): 29 | vocab_tokens = [ 30 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 31 | "##ing", "," 32 | ] 33 | with tempfile.NamedTemporaryFile(delete=False) as vocab_writer: 34 | if six.PY2: 35 | vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) 36 | else: 37 | vocab_writer.write("".join( 38 | [x + "\n" for x in vocab_tokens]).encode("utf-8")) 39 | 40 | vocab_file = vocab_writer.name 41 | 42 | tokenizer = tokenization.FullTokenizer(vocab_file) 43 | os.unlink(vocab_file) 44 | 45 | tokens = tokenizer.tokenize(u"UNwant\u00E9d,running") 46 | self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) 47 | 48 | self.assertAllEqual( 49 | tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) 50 | 51 | def test_chinese(self): 52 | tokenizer = tokenization.BasicTokenizer() 53 | 54 | self.assertAllEqual( 55 | tokenizer.tokenize(u"ah\u535A\u63A8zz"), 56 | [u"ah", u"\u535A", u"\u63A8", u"zz"]) 57 | 58 | def test_basic_tokenizer_lower(self): 59 | tokenizer = tokenization.BasicTokenizer(do_lower_case=True) 60 | 61 | self.assertAllEqual( 62 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 63 | ["hello", "!", "how", "are", "you", "?"]) 64 | self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"]) 65 | 66 | def test_basic_tokenizer_no_lower(self): 67 | tokenizer = tokenization.BasicTokenizer(do_lower_case=False) 68 | 69 | self.assertAllEqual( 70 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 71 | ["HeLLo", "!", "how", "Are", "yoU", "?"]) 72 | 73 | def test_wordpiece_tokenizer(self): 74 | vocab_tokens = [ 75 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 76 | "##ing" 77 | ] 78 | 79 | vocab = {} 80 | for (i, token) in enumerate(vocab_tokens): 81 | vocab[token] = i 82 | tokenizer = tokenization.WordpieceTokenizer(vocab=vocab) 83 | 84 | self.assertAllEqual(tokenizer.tokenize(""), []) 85 | 86 | self.assertAllEqual( 87 | tokenizer.tokenize("unwanted running"), 88 | ["un", "##want", "##ed", "runn", "##ing"]) 89 | 90 | self.assertAllEqual( 91 | tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) 92 | 93 | def test_convert_tokens_to_ids(self): 94 | vocab_tokens = [ 95 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 96 | "##ing" 97 | ] 98 | 99 | vocab = {} 100 | for (i, token) in enumerate(vocab_tokens): 101 | vocab[token] = i 102 | 103 | self.assertAllEqual( 104 | tokenization.convert_tokens_to_ids( 105 | vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9]) 106 | 107 | def test_is_whitespace(self): 108 | self.assertTrue(tokenization._is_whitespace(u" ")) 109 | self.assertTrue(tokenization._is_whitespace(u"\t")) 110 | self.assertTrue(tokenization._is_whitespace(u"\r")) 111 | self.assertTrue(tokenization._is_whitespace(u"\n")) 112 | self.assertTrue(tokenization._is_whitespace(u"\u00A0")) 113 | 114 | self.assertFalse(tokenization._is_whitespace(u"A")) 115 | self.assertFalse(tokenization._is_whitespace(u"-")) 116 | 117 | def test_is_control(self): 118 | self.assertTrue(tokenization._is_control(u"\u0005")) 119 | 120 | self.assertFalse(tokenization._is_control(u"A")) 121 | self.assertFalse(tokenization._is_control(u" ")) 122 | self.assertFalse(tokenization._is_control(u"\t")) 123 | self.assertFalse(tokenization._is_control(u"\r")) 124 | self.assertFalse(tokenization._is_control(u"\U0001F4A9")) 125 | 126 | def test_is_punctuation(self): 127 | self.assertTrue(tokenization._is_punctuation(u"-")) 128 | self.assertTrue(tokenization._is_punctuation(u"$")) 129 | self.assertTrue(tokenization._is_punctuation(u"`")) 130 | self.assertTrue(tokenization._is_punctuation(u".")) 131 | 132 | self.assertFalse(tokenization._is_punctuation(u"A")) 133 | self.assertFalse(tokenization._is_punctuation(u" ")) 134 | 135 | 136 | if __name__ == "__main__": 137 | tf.test.main() 138 | -------------------------------------------------------------------------------- /reformers/attention.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | class Attention(nn.Module): 6 | """ Applies attention mechanism on the `context` using the `query`. 7 | 8 | **Thank you** to IBM for their initial implementation of :class:`Attention`. Here is 9 | their `License 10 | `__. 11 | 12 | Args: 13 | dimensions (int): Dimensionality of the query and context. 14 | attention_type (str, optional): How to compute the attention score: 15 | 16 | * dot: :math:`score(H_j,q) = H_j^T q` 17 | * general: :math:`score(H_j, q) = H_j^T W_a q` 18 | 19 | Example: 20 | 21 | >>> attention = Attention(256) 22 | >>> query = torch.randn(5, 1, 256) 23 | >>> context = torch.randn(5, 5, 256) 24 | >>> output, weights = attention(query, context) 25 | >>> output.size() 26 | torch.Size([5, 1, 256]) 27 | >>> weights.size() 28 | torch.Size([5, 1, 5]) 29 | """ 30 | 31 | def __init__(self, dimensions, attention_type='general'): 32 | super().__init__() 33 | 34 | if attention_type not in ['dot', 'general']: 35 | raise ValueError('Invalid attention type selected.') 36 | 37 | self.attention_type = attention_type 38 | if self.attention_type == 'general': 39 | self.linear_in = nn.Linear(dimensions, dimensions, bias=False) 40 | 41 | self.linear_out = nn.Linear(dimensions * 2, dimensions, bias=False) 42 | self.softmax = nn.Softmax(dim=-1) 43 | self.tanh = nn.Tanh() 44 | 45 | def forward(self, query, context): 46 | """ 47 | Args: 48 | query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of 49 | queries to query the context. 50 | context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data 51 | overwhich to apply the attention mechanism. 52 | 53 | Returns: 54 | :class:`tuple` with `output` and `weights`: 55 | * **output** (:class:`torch.LongTensor` [batch size, output length, dimensions]): 56 | Tensor containing the attended features. 57 | * **weights** (:class:`torch.FloatTensor` [batch size, output length, query length]): 58 | Tensor containing attention weights. 59 | """ 60 | batch_size, output_len, dimensions = query.size() 61 | query_len = context.size(1) 62 | 63 | if self.attention_type == "general": 64 | query = query.reshape(batch_size * output_len, dimensions) 65 | query = self.linear_in(query) 66 | query = query.reshape(batch_size, output_len, dimensions) 67 | 68 | # TODO: Include mask on PADDING_INDEX? 69 | 70 | # (batch_size, output_len, dimensions) * (batch_size, query_len, dimensions) -> 71 | # (batch_size, output_len, query_len) 72 | attention_scores = torch.bmm(query, context.transpose(1, 2).contiguous()) 73 | 74 | # Compute weights across every context sequence 75 | attention_scores = attention_scores.view(batch_size * output_len, query_len) 76 | attention_weights = self.softmax(attention_scores) 77 | attention_weights = attention_weights.view(batch_size, output_len, query_len) 78 | 79 | # (batch_size, output_len, query_len) * (batch_size, query_len, dimensions) -> 80 | # (batch_size, output_len, dimensions) 81 | mix = torch.bmm(attention_weights, context) 82 | 83 | # concat -> (batch_size * output_len, 2*dimensions) 84 | combined = torch.cat((mix, query), dim=2) 85 | combined = combined.view(batch_size * output_len, 2 * dimensions) 86 | 87 | # Apply linear_out on every 2nd dimension of concat 88 | # output -> (batch_size, output_len, dimensions) 89 | output = self.linear_out(combined).view(batch_size, output_len, dimensions) 90 | output = self.tanh(output) 91 | 92 | return output, attention_weights 93 | 94 | class SelfAttention(nn.Module): 95 | def __init__(self, emb, heads = 8, causal = False): 96 | super().__init__() 97 | assert emb % heads == 0, 'dimensions must be divisible by number of heads' 98 | self.attn = nn.MultiheadAttention(emb, heads) 99 | self.to_out = nn.Linear(emb, emb) 100 | self.causal = causal 101 | 102 | def forward(self, x): 103 | b, t, e = x.shape 104 | x = x.transpose(0, 1) 105 | 106 | attn_mask = torch.zeros(t, t, device=x.device) 107 | if self.causal: 108 | causal_mask = torch.triu(torch.ones(t, t, device=x.device) == 1, 1) 109 | attn_mask.masked_fill_(causal_mask == 1, float('-inf')) 110 | 111 | output, _ = self.attn(x, x, x, attn_mask = attn_mask) 112 | return self.to_out(output.transpose(0, 1)) 113 | 114 | 115 | class FeedForward(nn.Module): 116 | def __init__(self, emb, mult = 4): 117 | super().__init__() 118 | self.emb = emb 119 | self.proj_in = nn.Linear(emb, emb * mult) 120 | self.proj_out = nn.Linear(emb * mult, emb) 121 | 122 | def forward(self, x): 123 | x = self.proj_in(x) 124 | x = F.gelu(x) 125 | x = self.proj_out(x) 126 | return x 127 | -------------------------------------------------------------------------------- /train/optimization.py: -------------------------------------------------------------------------------- 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 | """Functions and classes related to optimization (weight updates).""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import re 22 | import tensorflow as tf 23 | 24 | 25 | def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu): 26 | """Creates an optimizer training op.""" 27 | global_step = tf.compat.v1.train.get_or_create_global_step() 28 | 29 | learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32) 30 | 31 | # Implements linear decay of the learning rate. 32 | learning_rate = tf.compat.v1.train.polynomial_decay( 33 | learning_rate, 34 | global_step, 35 | num_train_steps, 36 | end_learning_rate=0.0, 37 | power=1.0, 38 | cycle=False) 39 | 40 | # Implements linear warmup. I.e., if global_step < num_warmup_steps, the 41 | # learning rate will be `global_step/num_warmup_steps * init_lr`. 42 | if num_warmup_steps: 43 | global_steps_int = tf.cast(global_step, tf.int32) 44 | warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) 45 | 46 | global_steps_float = tf.cast(global_steps_int, tf.float32) 47 | warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) 48 | 49 | warmup_percent_done = global_steps_float / warmup_steps_float 50 | warmup_learning_rate = init_lr * warmup_percent_done 51 | 52 | is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) 53 | learning_rate = ( 54 | (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate) 55 | 56 | # It is recommended that you use this optimizer for fine tuning, since this 57 | # is how the model was trained (note that the Adam m/v variables are NOT 58 | # loaded from init_checkpoint.) 59 | optimizer = AdamWeightDecayOptimizer( 60 | learning_rate=learning_rate, 61 | weight_decay_rate=0.01, 62 | beta_1=0.9, 63 | beta_2=0.999, 64 | epsilon=1e-6, 65 | exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]) 66 | 67 | if use_tpu: 68 | optimizer = tf.compat.v1.tpu.CrossShardOptimizer(optimizer) 69 | 70 | tvars = tf.compat.v1.trainable_variables() 71 | grads = tf.gradients(ys=loss, xs=tvars) 72 | 73 | # This is how the model was pre-trained. 74 | (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) 75 | 76 | train_op = optimizer.apply_gradients( 77 | zip(grads, tvars), global_step=global_step) 78 | 79 | # Normally the global step update is done inside of `apply_gradients`. 80 | # However, `AdamWeightDecayOptimizer` doesn't do this. But if you use 81 | # a different optimizer, you should probably take this line out. 82 | new_global_step = global_step + 1 83 | train_op = tf.group(train_op, [global_step.assign(new_global_step)]) 84 | return train_op 85 | 86 | 87 | class AdamWeightDecayOptimizer(tf.compat.v1.train.Optimizer): 88 | """A basic Adam optimizer that includes "correct" L2 weight decay.""" 89 | 90 | def __init__(self, 91 | learning_rate, 92 | weight_decay_rate=0.0, 93 | beta_1=0.9, 94 | beta_2=0.999, 95 | epsilon=1e-6, 96 | exclude_from_weight_decay=None, 97 | name="AdamWeightDecayOptimizer"): 98 | """Constructs a AdamWeightDecayOptimizer.""" 99 | super(AdamWeightDecayOptimizer, self).__init__(False, name) 100 | 101 | self.learning_rate = learning_rate 102 | self.weight_decay_rate = weight_decay_rate 103 | self.beta_1 = beta_1 104 | self.beta_2 = beta_2 105 | self.epsilon = epsilon 106 | self.exclude_from_weight_decay = exclude_from_weight_decay 107 | 108 | def apply_gradients(self, grads_and_vars, global_step=None, name=None): 109 | """See base class.""" 110 | assignments = [] 111 | for (grad, param) in grads_and_vars: 112 | if grad is None or param is None: 113 | continue 114 | 115 | param_name = self._get_variable_name(param.name) 116 | 117 | m = tf.compat.v1.get_variable( 118 | name=param_name + "/adam_m", 119 | shape=param.shape.as_list(), 120 | dtype=tf.float32, 121 | trainable=False, 122 | initializer=tf.compat.v1.zeros_initializer()) 123 | v = tf.compat.v1.get_variable( 124 | name=param_name + "/adam_v", 125 | shape=param.shape.as_list(), 126 | dtype=tf.float32, 127 | trainable=False, 128 | initializer=tf.compat.v1.zeros_initializer()) 129 | 130 | # Standard Adam update. 131 | next_m = ( 132 | tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)) 133 | next_v = ( 134 | tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, 135 | tf.square(grad))) 136 | 137 | update = next_m / (tf.sqrt(next_v) + self.epsilon) 138 | 139 | # Just adding the square of the weights to the loss function is *not* 140 | # the correct way of using L2 regularization/weight decay with Adam, 141 | # since that will interact with the m and v parameters in strange ways. 142 | # 143 | # Instead we want ot decay the weights in a manner that doesn't interact 144 | # with the m/v parameters. This is equivalent to adding the square 145 | # of the weights to the loss with plain (non-momentum) SGD. 146 | if self._do_use_weight_decay(param_name): 147 | update += self.weight_decay_rate * param 148 | 149 | update_with_lr = self.learning_rate * update 150 | 151 | next_param = param - update_with_lr 152 | 153 | assignments.extend( 154 | [param.assign(next_param), 155 | m.assign(next_m), 156 | v.assign(next_v)]) 157 | return tf.group(*assignments, name=name) 158 | 159 | def _do_use_weight_decay(self, param_name): 160 | """Whether to use L2 weight decay for `param_name`.""" 161 | if not self.weight_decay_rate: 162 | return False 163 | if self.exclude_from_weight_decay: 164 | for r in self.exclude_from_weight_decay: 165 | if re.search(r, param_name) is not None: 166 | return False 167 | return True 168 | 169 | def _get_variable_name(self, param_name): 170 | """Get the variable name from the tensor name.""" 171 | m = re.match("^(.*):\\d+$", param_name) 172 | if m is not None: 173 | param_name = m.group(1) 174 | return param_name 175 | -------------------------------------------------------------------------------- /train/modeling_test.py: -------------------------------------------------------------------------------- 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 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import collections 20 | import json 21 | import random 22 | import re 23 | 24 | import modeling 25 | import six 26 | import tensorflow as tf 27 | 28 | 29 | class BertModelTest(tf.test.TestCase): 30 | 31 | class BertModelTester(object): 32 | 33 | def __init__(self, 34 | parent, 35 | batch_size=13, 36 | seq_length=7, 37 | is_training=True, 38 | use_input_mask=True, 39 | use_token_type_ids=True, 40 | vocab_size=99, 41 | hidden_size=32, 42 | num_hidden_layers=5, 43 | num_attention_heads=4, 44 | intermediate_size=37, 45 | hidden_act="gelu", 46 | hidden_dropout_prob=0.1, 47 | attention_probs_dropout_prob=0.1, 48 | max_position_embeddings=512, 49 | type_vocab_size=16, 50 | initializer_range=0.02, 51 | scope=None): 52 | self.parent = parent 53 | self.batch_size = batch_size 54 | self.seq_length = seq_length 55 | self.is_training = is_training 56 | self.use_input_mask = use_input_mask 57 | self.use_token_type_ids = use_token_type_ids 58 | self.vocab_size = vocab_size 59 | self.hidden_size = hidden_size 60 | self.num_hidden_layers = num_hidden_layers 61 | self.num_attention_heads = num_attention_heads 62 | self.intermediate_size = intermediate_size 63 | self.hidden_act = hidden_act 64 | self.hidden_dropout_prob = hidden_dropout_prob 65 | self.attention_probs_dropout_prob = attention_probs_dropout_prob 66 | self.max_position_embeddings = max_position_embeddings 67 | self.type_vocab_size = type_vocab_size 68 | self.initializer_range = initializer_range 69 | self.scope = scope 70 | 71 | def create_model(self): 72 | input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length], 73 | self.vocab_size) 74 | 75 | input_mask = None 76 | if self.use_input_mask: 77 | input_mask = BertModelTest.ids_tensor( 78 | [self.batch_size, self.seq_length], vocab_size=2) 79 | 80 | token_type_ids = None 81 | if self.use_token_type_ids: 82 | token_type_ids = BertModelTest.ids_tensor( 83 | [self.batch_size, self.seq_length], self.type_vocab_size) 84 | 85 | config = modeling.BertConfig( 86 | vocab_size=self.vocab_size, 87 | hidden_size=self.hidden_size, 88 | num_hidden_layers=self.num_hidden_layers, 89 | num_attention_heads=self.num_attention_heads, 90 | intermediate_size=self.intermediate_size, 91 | hidden_act=self.hidden_act, 92 | hidden_dropout_prob=self.hidden_dropout_prob, 93 | attention_probs_dropout_prob=self.attention_probs_dropout_prob, 94 | max_position_embeddings=self.max_position_embeddings, 95 | type_vocab_size=self.type_vocab_size, 96 | initializer_range=self.initializer_range) 97 | 98 | model = modeling.BertModel( 99 | config=config, 100 | is_training=self.is_training, 101 | input_ids=input_ids, 102 | input_mask=input_mask, 103 | token_type_ids=token_type_ids, 104 | scope=self.scope) 105 | 106 | outputs = { 107 | "embedding_output": model.get_embedding_output(), 108 | "sequence_output": model.get_sequence_output(), 109 | "pooled_output": model.get_pooled_output(), 110 | "all_encoder_layers": model.get_all_encoder_layers(), 111 | } 112 | return outputs 113 | 114 | def check_output(self, result): 115 | self.parent.assertAllEqual( 116 | result["embedding_output"].shape, 117 | [self.batch_size, self.seq_length, self.hidden_size]) 118 | 119 | self.parent.assertAllEqual( 120 | result["sequence_output"].shape, 121 | [self.batch_size, self.seq_length, self.hidden_size]) 122 | 123 | self.parent.assertAllEqual(result["pooled_output"].shape, 124 | [self.batch_size, self.hidden_size]) 125 | 126 | def test_default(self): 127 | self.run_tester(BertModelTest.BertModelTester(self)) 128 | 129 | def test_config_to_json_string(self): 130 | config = modeling.BertConfig(vocab_size=99, hidden_size=37) 131 | obj = json.loads(config.to_json_string()) 132 | self.assertEqual(obj["vocab_size"], 99) 133 | self.assertEqual(obj["hidden_size"], 37) 134 | 135 | def run_tester(self, tester): 136 | with self.test_session() as sess: 137 | ops = tester.create_model() 138 | init_op = tf.group(tf.compat.v1.global_variables_initializer(), 139 | tf.compat.v1.local_variables_initializer()) 140 | sess.run(init_op) 141 | output_result = sess.run(ops) 142 | tester.check_output(output_result) 143 | 144 | self.assert_all_tensors_reachable(sess, [init_op, ops]) 145 | 146 | @classmethod 147 | def ids_tensor(cls, shape, vocab_size, rng=None, name=None): 148 | """Creates a random int32 tensor of the shape within the vocab size.""" 149 | if rng is None: 150 | rng = random.Random() 151 | 152 | total_dims = 1 153 | for dim in shape: 154 | total_dims *= dim 155 | 156 | values = [] 157 | for _ in range(total_dims): 158 | values.append(rng.randint(0, vocab_size - 1)) 159 | 160 | return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name) 161 | 162 | def assert_all_tensors_reachable(self, sess, outputs): 163 | """Checks that all the tensors in the graph are reachable from outputs.""" 164 | graph = sess.graph 165 | 166 | ignore_strings = [ 167 | "^.*/assert_less_equal/.*$", 168 | "^.*/dilation_rate$", 169 | "^.*/Tensordot/concat$", 170 | "^.*/Tensordot/concat/axis$", 171 | "^testing/.*$", 172 | ] 173 | 174 | ignore_regexes = [re.compile(x) for x in ignore_strings] 175 | 176 | unreachable = self.get_unreachable_ops(graph, outputs) 177 | filtered_unreachable = [] 178 | for x in unreachable: 179 | do_ignore = False 180 | for r in ignore_regexes: 181 | m = r.match(x.name) 182 | if m is not None: 183 | do_ignore = True 184 | if do_ignore: 185 | continue 186 | filtered_unreachable.append(x) 187 | unreachable = filtered_unreachable 188 | 189 | self.assertEqual( 190 | len(unreachable), 0, "The following ops are unreachable: %s" % 191 | (" ".join([x.name for x in unreachable]))) 192 | 193 | @classmethod 194 | def get_unreachable_ops(cls, graph, outputs): 195 | """Finds all of the tensors in graph that are unreachable from outputs.""" 196 | outputs = cls.flatten_recursive(outputs) 197 | output_to_op = collections.defaultdict(list) 198 | op_to_all = collections.defaultdict(list) 199 | assign_out_to_in = collections.defaultdict(list) 200 | 201 | for op in graph.get_operations(): 202 | for x in op.inputs: 203 | op_to_all[op.name].append(x.name) 204 | for y in op.outputs: 205 | output_to_op[y.name].append(op.name) 206 | op_to_all[op.name].append(y.name) 207 | if str(op.type) == "Assign": 208 | for y in op.outputs: 209 | for x in op.inputs: 210 | assign_out_to_in[y.name].append(x.name) 211 | 212 | assign_groups = collections.defaultdict(list) 213 | for out_name in assign_out_to_in.keys(): 214 | name_group = assign_out_to_in[out_name] 215 | for n1 in name_group: 216 | assign_groups[n1].append(out_name) 217 | for n2 in name_group: 218 | if n1 != n2: 219 | assign_groups[n1].append(n2) 220 | 221 | seen_tensors = {} 222 | stack = [x.name for x in outputs] 223 | while stack: 224 | name = stack.pop() 225 | if name in seen_tensors: 226 | continue 227 | seen_tensors[name] = True 228 | 229 | if name in output_to_op: 230 | for op_name in output_to_op[name]: 231 | if op_name in op_to_all: 232 | for input_name in op_to_all[op_name]: 233 | if input_name not in stack: 234 | stack.append(input_name) 235 | 236 | expanded_names = [] 237 | if name in assign_groups: 238 | for assign_name in assign_groups[name]: 239 | expanded_names.append(assign_name) 240 | 241 | for expanded_name in expanded_names: 242 | if expanded_name not in stack: 243 | stack.append(expanded_name) 244 | 245 | unreachable_ops = [] 246 | for op in graph.get_operations(): 247 | is_unreachable = False 248 | all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs] 249 | for name in all_names: 250 | if name not in seen_tensors: 251 | is_unreachable = True 252 | if is_unreachable: 253 | unreachable_ops.append(op) 254 | return unreachable_ops 255 | 256 | @classmethod 257 | def flatten_recursive(cls, item): 258 | """Flattens (potentially nested) a tuple/dictionary/list to a list.""" 259 | output = [] 260 | if isinstance(item, list): 261 | output.extend(item) 262 | elif isinstance(item, tuple): 263 | output.extend(list(item)) 264 | elif isinstance(item, dict): 265 | for (_, v) in six.iteritems(item): 266 | output.append(v) 267 | else: 268 | return [item] 269 | 270 | flat_output = [] 271 | for x in output: 272 | flat_output.extend(cls.flatten_recursive(x)) 273 | return flat_output 274 | 275 | 276 | if __name__ == "__main__": 277 | tf.test.main() 278 | -------------------------------------------------------------------------------- /train/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /reformers/efficient_attention.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Phillip Wang, 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import torch 24 | import torch.nn as nn 25 | from torch.autograd import Function 26 | import torch.nn.functional as F 27 | from .utils import process_inputs_chunk, sort_key_val, batched_index_select, make_unit_length 28 | 29 | class LSHAttention(nn.Module): 30 | def __init__( self, 31 | dropout = 0., 32 | bucket_size = 64, 33 | n_hashes = 8, 34 | causal = False, 35 | allow_duplicate_attention = True, 36 | attend_across_buckets = True, 37 | rehash_each_round = True, 38 | drop_for_hash_rate = 0.0, 39 | random_rotations_per_head = False): 40 | super().__init__() 41 | if dropout >= 1.0: 42 | raise ValueError('Dropout rates must be lower than 1.') 43 | 44 | self.dropout = nn.Dropout(dropout) 45 | self.dropout_for_hash = nn.Dropout(drop_for_hash_rate) 46 | 47 | assert rehash_each_round or allow_duplicate_attention, ( 48 | 'The setting {allow_duplicate_attention=False, rehash_each_round=False}' 49 | ' is not implemented.') 50 | 51 | self.causal = causal 52 | self.n_hashes = n_hashes 53 | self.bucket_size = bucket_size 54 | 55 | self._allow_duplicate_attention = allow_duplicate_attention 56 | self._attend_across_buckets = attend_across_buckets 57 | self._rehash_each_round = rehash_each_round 58 | self._random_rotations_per_head = random_rotations_per_head 59 | 60 | def hash_vectors(self, n_buckets, vecs): 61 | batch_size = vecs.shape[0] 62 | device = vecs.device 63 | 64 | # See https://arxiv.org/pdf/1509.02897.pdf 65 | # We sample a different random rotation for each round of hashing to 66 | # decrease the probability of hash misses. 67 | assert n_buckets % 2 == 0 68 | 69 | rot_size = n_buckets 70 | 71 | rotations_shape = ( 72 | batch_size if self._random_rotations_per_head else 1, 73 | vecs.shape[-1], 74 | self.n_hashes if self._rehash_each_round else 1, 75 | rot_size // 2) 76 | 77 | random_rotations = torch.randn(rotations_shape, device=device).expand(batch_size, -1, -1, -1) 78 | 79 | dropped_vecs = self.dropout_for_hash(vecs) 80 | rotated_vecs = torch.einsum('btf,bfhi->bhti', dropped_vecs, random_rotations) 81 | 82 | if self._rehash_each_round: 83 | rotated_vecs = torch.cat([rotated_vecs, -rotated_vecs], dim=-1) 84 | buckets = torch.argmax(rotated_vecs, axis=-1) 85 | # buckets is now (self.n_hashes, seqlen). Next we add offsets so that 86 | # bucket numbers from different hashing rounds don't overlap. 87 | offsets = torch.arange(self.n_hashes, device=device) 88 | offsets = torch.reshape(offsets * n_buckets, (1, -1, 1)) 89 | buckets = torch.reshape(buckets + offsets, (batch_size, -1,)) 90 | else: 91 | rotated_vecs = torch.cat([rotated_vecs, -rotated_vecs], dim=-1) 92 | # In this configuration, we map each item to the top self.n_hashes buckets 93 | rotated_vecs = torch.squeeze(rotated_vecs, 0) 94 | bucket_range = torch.arange(rotated_vecs.shape[-1], device=device) 95 | bucket_range = torch.reshape(bucket_range, (1, -1)) 96 | bucket_range = bucket_range.expand_as(rotated_vecs.shape) 97 | 98 | _, buckets = sort_key_val(rotated_vecs, bucket_range, dim=-1) 99 | buckets = buckets[:, -self.n_hashes:] 100 | 101 | h, *_ = buckets.shape 102 | buckets = torch.reshape(buckets.permute((*_, h)), (-1,)) 103 | 104 | return buckets 105 | 106 | def forward(self, qk, v): 107 | batch_size, seqlen, _ = qk.shape 108 | device = qk.device 109 | 110 | n_buckets = seqlen // self.bucket_size 111 | n_bins = n_buckets 112 | 113 | buckets = self.hash_vectors(n_buckets, qk) 114 | # We use the same vector as both a query and a key. 115 | assert int(buckets.shape[1]) == self.n_hashes * seqlen 116 | 117 | ticker = torch.arange(self.n_hashes * seqlen, device=device).unsqueeze(0) 118 | buckets_and_t = seqlen * buckets + (ticker % seqlen) 119 | buckets_and_t = buckets_and_t.detach() 120 | 121 | # Hash-based sort ("s" at the start of variable names means "sorted") 122 | sbuckets_and_t, sticker = sort_key_val(buckets_and_t, ticker, dim=-1) 123 | _, undo_sort = sort_key_val(sticker, ticker, dim=-1) 124 | del ticker 125 | 126 | sbuckets_and_t = sbuckets_and_t.detach() 127 | sticker = sticker.detach() 128 | undo_sort = undo_sort.detach() 129 | 130 | st = (sticker % seqlen) 131 | sqk = batched_index_select(qk, st) 132 | sv = batched_index_select(v, st) 133 | 134 | # Split off a "bin" axis so that attention only occurs within chunks. 135 | bq_t = bkv_t = torch.reshape(st, (batch_size, self.n_hashes * n_bins, -1)) 136 | bqk = torch.reshape(sqk, (batch_size, self.n_hashes * n_bins, -1, sqk.shape[-1])) 137 | bv = torch.reshape(sv, (batch_size, self.n_hashes * n_bins, -1, sv.shape[-1])) 138 | bq_buckets = bkv_buckets = torch.reshape(sbuckets_and_t // seqlen, (batch_size, self.n_hashes * n_bins, -1)) 139 | 140 | # Hashing operates on unit-length vectors. Unnormalized query vectors are 141 | # fine because they effectively provide a learnable temperature for the 142 | # attention softmax, but normalizing keys is needed so that similarity for 143 | # the purposes of attention correctly corresponds to hash locality. 144 | bq = bqk 145 | bk = make_unit_length(bqk) 146 | 147 | # Allow each chunk to attend within itself, and also one chunk back. Chunk 148 | # boundaries might occur in the middle of a sequence of items from the 149 | # same bucket, so this increases the chances of attending to relevant items. 150 | def look_one_back(x): 151 | x_extra = torch.cat([x[:, -1:, ...], x[:, :-1, ...]], dim=1) 152 | return torch.cat([x, x_extra], dim=2) 153 | 154 | bk = look_one_back(bk) 155 | bv = look_one_back(bv) 156 | bkv_t = look_one_back(bkv_t) 157 | bkv_buckets = look_one_back(bkv_buckets) 158 | 159 | # Dot-product attention. 160 | dots = torch.einsum('bhie,bhje->bhij', bq, bk) * (bq.shape[-1] ** -0.5) 161 | 162 | # Causal masking 163 | if self.causal: 164 | mask = bq_t[:, :, :, None] < bkv_t[:, :, None, :] 165 | dots.masked_fill_(mask, float('-inf')) 166 | del mask 167 | 168 | # Mask out attention to self except when no other targets are available. 169 | self_mask = bq_t[:, :, :, None] == bkv_t[:, :, None, :] 170 | dots.masked_fill_(self_mask, - 1e5) 171 | del self_mask 172 | 173 | # Mask out attention to other hash buckets. 174 | if not self._attend_across_buckets: 175 | bucket_mask = bq_buckets[:, :, :, None] != bkv_buckets[:, :, None, :] 176 | dots.masked_fill_(bucket_mask, float('-inf')) 177 | del bucket_mask 178 | 179 | # Don't double-count query-key pairs across multiple rounds of hashing. 180 | # There are two possible strategies here. (1) The default is to count how 181 | # many times a query-key pair is repeated, and to lower its log-prob 182 | # correspondingly at each repetition. (2) When hard_k is set, the code 183 | # instead masks all but the first occurence of each query-key pair. 184 | if not self._allow_duplicate_attention: 185 | locs1 = undo_sort // bq_t.shape[-1] 186 | locs2 = (locs1 + 1) % (self.n_hashes * n_bins) 187 | if not self._attend_across_buckets: 188 | locs1 = buckets * (self.n_hashes * n_bins) + locs1 189 | locs2 = buckets * (self.n_hashes * n_bins) + locs2 190 | locs = torch.cat([ 191 | torch.reshape(locs1, (batch_size, self.n_hashes, seqlen)), 192 | torch.reshape(locs2, (batch_size, self.n_hashes, seqlen)), 193 | ], 1).permute((0, 2, 1)) 194 | 195 | slocs = batched_index_select(locs, st) 196 | b_locs = torch.reshape(slocs, (batch_size, self.n_hashes * n_bins, -1, 2 * self.n_hashes)) 197 | 198 | b_locs1 = b_locs[:, :, :, None, :self.n_hashes] 199 | 200 | bq_locs = b_locs1.expand(b_locs.shape[:3] + (2, self.n_hashes)) 201 | bq_locs = torch.reshape(bq_locs, b_locs.shape) 202 | bkv_locs = look_one_back(b_locs) 203 | 204 | dup_counts = (bq_locs[:, :, :, None, :] == bkv_locs[:, :, None, :, :]) 205 | # for memory considerations, chunk summation of last dimension for counting duplicates 206 | dup_counts = chunked_sum(dup_counts, chunks=(self.n_hashes * batch_size)) 207 | dup_counts = dup_counts.detach() 208 | assert dup_counts.shape == dots.shape 209 | dots = dots - torch.log(dup_counts + 1e-9) 210 | del dup_counts 211 | 212 | # Softmax. 213 | dots_logsumexp = torch.logsumexp(dots, dim=-1, keepdim=True) 214 | dots = torch.exp(dots - dots_logsumexp) 215 | dots = self.dropout(dots) 216 | 217 | bo = torch.einsum('buij,buje->buie', dots, bv) 218 | so = torch.reshape(bo, (batch_size, -1, bo.shape[-1])) 219 | slogits = torch.reshape(dots_logsumexp, (batch_size, -1,)) 220 | 221 | class UnsortLogits(Function): 222 | @staticmethod 223 | def forward(ctx, so, slogits): 224 | so = so.detach() 225 | slogits = slogits.detach() 226 | o = batched_index_select(so, undo_sort) 227 | _, logits = sort_key_val(sticker, slogits, dim=-1) 228 | return o, logits 229 | 230 | @staticmethod 231 | def backward(ctx, grad_x, grad_y): 232 | so_grad = batched_index_select(grad_x, sticker) 233 | _, slogits_grad = sort_key_val(buckets_and_t, grad_y, dim=-1) 234 | return so_grad, slogits_grad 235 | 236 | o, logits = UnsortLogits.apply(so, slogits) 237 | 238 | if self.n_hashes == 1: 239 | out = o 240 | else: 241 | o = torch.reshape(o, (batch_size, self.n_hashes, seqlen, o.shape[-1])) 242 | logits = torch.reshape(logits, (batch_size, self.n_hashes, seqlen, 1)) 243 | probs = torch.exp(logits - torch.logsumexp(logits, dim=1, keepdims=True)) 244 | out = torch.sum(o * probs, dim=1) 245 | 246 | assert out.shape == v.shape 247 | return out, buckets 248 | 249 | class LSHSelfAttention(nn.Module): 250 | def __init__(self, emb, heads = 8, bucket_size = 64, n_hashes = 8, causal = False, attn_chunks = None, random_rotations_per_head = False, attend_across_buckets = True, allow_duplicate_attention = True, **kwargs): 251 | super().__init__() 252 | assert emb % heads == 0, 'dimensions must be divisible by number of heads' 253 | 254 | self.emb = emb 255 | self.heads = heads 256 | self.attn_chunks = heads if attn_chunks is None else attn_chunks 257 | 258 | self.toqk = nn.Linear(emb, emb, bias = False) 259 | self.tov = nn.Linear(emb, emb, bias = False) 260 | self.to_out = nn.Linear(emb, emb) 261 | 262 | self.bucket_size = bucket_size 263 | self.lsh_attn = LSHAttention(bucket_size=bucket_size, causal=causal, random_rotations_per_head=random_rotations_per_head, attend_across_buckets = attend_across_buckets, allow_duplicate_attention = allow_duplicate_attention, **kwargs) 264 | 265 | def forward(self, x): 266 | b, t, e, h = *x.shape, self.heads 267 | assert t % self.bucket_size == 0, f'Sequence length needs to be divisible by target bucket size - {self.bucket_size}' 268 | 269 | qk = self.toqk(x) 270 | v = self.tov(x) 271 | 272 | def merge_heads(v): 273 | return v.view(b, t, h, -1).transpose(1, 2).reshape(b * h, t, -1) 274 | 275 | def split_heads(v): 276 | return v.view(b, h, t, -1).transpose(1, 2).contiguous() 277 | 278 | qk = merge_heads(qk) 279 | v = merge_heads(v) 280 | 281 | outputs = process_inputs_chunk(self.lsh_attn, qk, v, chunks=self.attn_chunks) 282 | attn_out = torch.cat([output for (output, _) in outputs], dim=0) 283 | 284 | out = split_heads(attn_out).view(b, t, e) 285 | 286 | return self.to_out(out) -------------------------------------------------------------------------------- /train/tokenization.py: -------------------------------------------------------------------------------- 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 | """Tokenization classes.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import collections 22 | import re 23 | import unicodedata 24 | import six 25 | import tensorflow as tf 26 | 27 | 28 | def validate_case_matches_checkpoint(do_lower_case, init_checkpoint): 29 | """Checks whether the casing config is consistent with the checkpoint name.""" 30 | 31 | # The casing has to be passed in by the user and there is no explicit check 32 | # as to whether it matches the checkpoint. The casing information probably 33 | # should have been stored in the bert_config.json file, but it's not, so 34 | # we have to heuristically detect it to validate. 35 | 36 | if not init_checkpoint: 37 | return 38 | 39 | m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint) 40 | if m is None: 41 | return 42 | 43 | model_name = m.group(1) 44 | 45 | lower_models = [ 46 | "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12", 47 | "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12" 48 | ] 49 | 50 | cased_models = [ 51 | "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16", 52 | "multi_cased_L-12_H-768_A-12" 53 | ] 54 | 55 | is_bad_config = False 56 | if model_name in lower_models and not do_lower_case: 57 | is_bad_config = True 58 | actual_flag = "False" 59 | case_name = "lowercased" 60 | opposite_flag = "True" 61 | 62 | if model_name in cased_models and do_lower_case: 63 | is_bad_config = True 64 | actual_flag = "True" 65 | case_name = "cased" 66 | opposite_flag = "False" 67 | 68 | if is_bad_config: 69 | raise ValueError( 70 | "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. " 71 | "However, `%s` seems to be a %s model, so you " 72 | "should pass in `--do_lower_case=%s` so that the fine-tuning matches " 73 | "how the model was pre-training. If this error is wrong, please " 74 | "just comment out this check." % (actual_flag, init_checkpoint, 75 | model_name, case_name, opposite_flag)) 76 | 77 | 78 | def convert_to_unicode(text): 79 | """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" 80 | if six.PY3: 81 | if isinstance(text, str): 82 | return text 83 | elif isinstance(text, bytes): 84 | return text.decode("utf-8", "ignore") 85 | else: 86 | raise ValueError("Unsupported string type: %s" % (type(text))) 87 | elif six.PY2: 88 | if isinstance(text, str): 89 | return text.decode("utf-8", "ignore") 90 | elif isinstance(text, unicode): 91 | return text 92 | else: 93 | raise ValueError("Unsupported string type: %s" % (type(text))) 94 | else: 95 | raise ValueError("Not running on Python2 or Python 3?") 96 | 97 | 98 | def printable_text(text): 99 | """Returns text encoded in a way suitable for print or `tf.logging`.""" 100 | 101 | # These functions want `str` for both Python2 and Python3, but in one case 102 | # it's a Unicode string and in the other it's a byte string. 103 | if six.PY3: 104 | if isinstance(text, str): 105 | return text 106 | elif isinstance(text, bytes): 107 | return text.decode("utf-8", "ignore") 108 | else: 109 | raise ValueError("Unsupported string type: %s" % (type(text))) 110 | elif six.PY2: 111 | if isinstance(text, str): 112 | return text 113 | elif isinstance(text, unicode): 114 | return text.encode("utf-8") 115 | else: 116 | raise ValueError("Unsupported string type: %s" % (type(text))) 117 | else: 118 | raise ValueError("Not running on Python2 or Python 3?") 119 | 120 | 121 | def load_vocab(vocab_file): 122 | """Loads a vocabulary file into a dictionary.""" 123 | vocab = collections.OrderedDict() 124 | index = 0 125 | with tf.io.gfile.GFile(vocab_file, "r") as reader: 126 | while True: 127 | token = convert_to_unicode(reader.readline()) 128 | if not token: 129 | break 130 | token = token.strip() 131 | vocab[token] = index 132 | index += 1 133 | return vocab 134 | 135 | 136 | def convert_by_vocab(vocab, items): 137 | """Converts a sequence of [tokens|ids] using the vocab.""" 138 | output = [] 139 | for item in items: 140 | output.append(vocab[item]) 141 | return output 142 | 143 | 144 | def convert_tokens_to_ids(vocab, tokens): 145 | return convert_by_vocab(vocab, tokens) 146 | 147 | 148 | def convert_ids_to_tokens(inv_vocab, ids): 149 | return convert_by_vocab(inv_vocab, ids) 150 | 151 | 152 | def whitespace_tokenize(text): 153 | """Runs basic whitespace cleaning and splitting on a piece of text.""" 154 | text = text.strip() 155 | if not text: 156 | return [] 157 | tokens = text.split() 158 | return tokens 159 | 160 | 161 | class FullTokenizer(object): 162 | """Runs end-to-end tokenziation.""" 163 | 164 | def __init__(self, vocab_file, do_lower_case=True): 165 | self.vocab = load_vocab(vocab_file) 166 | self.inv_vocab = {v: k for k, v in self.vocab.items()} 167 | self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) 168 | self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) 169 | 170 | def tokenize(self, text): 171 | split_tokens = [] 172 | for token in self.basic_tokenizer.tokenize(text): 173 | for sub_token in self.wordpiece_tokenizer.tokenize(token): 174 | split_tokens.append(sub_token) 175 | 176 | return split_tokens 177 | 178 | def convert_tokens_to_ids(self, tokens): 179 | return convert_by_vocab(self.vocab, tokens) 180 | 181 | def convert_ids_to_tokens(self, ids): 182 | return convert_by_vocab(self.inv_vocab, ids) 183 | 184 | 185 | class BasicTokenizer(object): 186 | """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" 187 | 188 | def __init__(self, do_lower_case=True): 189 | """Constructs a BasicTokenizer. 190 | 191 | Args: 192 | do_lower_case: Whether to lower case the input. 193 | """ 194 | self.do_lower_case = do_lower_case 195 | 196 | def tokenize(self, text): 197 | """Tokenizes a piece of text.""" 198 | text = convert_to_unicode(text) 199 | text = self._clean_text(text) 200 | 201 | # This was added on November 1st, 2018 for the multilingual and Chinese 202 | # models. This is also applied to the English models now, but it doesn't 203 | # matter since the English models were not trained on any Chinese data 204 | # and generally don't have any Chinese data in them (there are Chinese 205 | # characters in the vocabulary because Wikipedia does have some Chinese 206 | # words in the English Wikipedia.). 207 | text = self._tokenize_chinese_chars(text) 208 | 209 | orig_tokens = whitespace_tokenize(text) 210 | split_tokens = [] 211 | for token in orig_tokens: 212 | if self.do_lower_case: 213 | token = token.lower() 214 | token = self._run_strip_accents(token) 215 | split_tokens.extend(self._run_split_on_punc(token)) 216 | 217 | output_tokens = whitespace_tokenize(" ".join(split_tokens)) 218 | return output_tokens 219 | 220 | def _run_strip_accents(self, text): 221 | """Strips accents from a piece of text.""" 222 | text = unicodedata.normalize("NFD", text) 223 | output = [] 224 | for char in text: 225 | cat = unicodedata.category(char) 226 | if cat == "Mn": 227 | continue 228 | output.append(char) 229 | return "".join(output) 230 | 231 | def _run_split_on_punc(self, text): 232 | """Splits punctuation on a piece of text.""" 233 | chars = list(text) 234 | i = 0 235 | start_new_word = True 236 | output = [] 237 | while i < len(chars): 238 | char = chars[i] 239 | if _is_punctuation(char): 240 | output.append([char]) 241 | start_new_word = True 242 | else: 243 | if start_new_word: 244 | output.append([]) 245 | start_new_word = False 246 | output[-1].append(char) 247 | i += 1 248 | 249 | return ["".join(x) for x in output] 250 | 251 | def _tokenize_chinese_chars(self, text): 252 | """Adds whitespace around any CJK character.""" 253 | output = [] 254 | for char in text: 255 | cp = ord(char) 256 | if self._is_chinese_char(cp): 257 | output.append(" ") 258 | output.append(char) 259 | output.append(" ") 260 | else: 261 | output.append(char) 262 | return "".join(output) 263 | 264 | def _is_chinese_char(self, cp): 265 | """Checks whether CP is the codepoint of a CJK character.""" 266 | # This defines a "chinese character" as anything in the CJK Unicode block: 267 | # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) 268 | # 269 | # Note that the CJK Unicode block is NOT all Japanese and Korean characters, 270 | # despite its name. The modern Korean Hangul alphabet is a different block, 271 | # as is Japanese Hiragana and Katakana. Those alphabets are used to write 272 | # space-separated words, so they are not treated specially and handled 273 | # like the all of the other languages. 274 | if ((cp >= 0x4E00 and cp <= 0x9FFF) or # 275 | (cp >= 0x3400 and cp <= 0x4DBF) or # 276 | (cp >= 0x20000 and cp <= 0x2A6DF) or # 277 | (cp >= 0x2A700 and cp <= 0x2B73F) or # 278 | (cp >= 0x2B740 and cp <= 0x2B81F) or # 279 | (cp >= 0x2B820 and cp <= 0x2CEAF) or 280 | (cp >= 0xF900 and cp <= 0xFAFF) or # 281 | (cp >= 0x2F800 and cp <= 0x2FA1F)): # 282 | return True 283 | 284 | return False 285 | 286 | def _clean_text(self, text): 287 | """Performs invalid character removal and whitespace cleanup on text.""" 288 | output = [] 289 | for char in text: 290 | cp = ord(char) 291 | if cp == 0 or cp == 0xfffd or _is_control(char): 292 | continue 293 | if _is_whitespace(char): 294 | output.append(" ") 295 | else: 296 | output.append(char) 297 | return "".join(output) 298 | 299 | 300 | class WordpieceTokenizer(object): 301 | """Runs WordPiece tokenziation.""" 302 | 303 | def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200): 304 | self.vocab = vocab 305 | self.unk_token = unk_token 306 | self.max_input_chars_per_word = max_input_chars_per_word 307 | 308 | def tokenize(self, text): 309 | """Tokenizes a piece of text into its word pieces. 310 | 311 | This uses a greedy longest-match-first algorithm to perform tokenization 312 | using the given vocabulary. 313 | 314 | For example: 315 | input = "unaffable" 316 | output = ["un", "##aff", "##able"] 317 | 318 | Args: 319 | text: A single token or whitespace separated tokens. This should have 320 | already been passed through `BasicTokenizer. 321 | 322 | Returns: 323 | A list of wordpiece tokens. 324 | """ 325 | 326 | text = convert_to_unicode(text) 327 | 328 | output_tokens = [] 329 | for token in whitespace_tokenize(text): 330 | chars = list(token) 331 | if len(chars) > self.max_input_chars_per_word: 332 | output_tokens.append(self.unk_token) 333 | continue 334 | 335 | is_bad = False 336 | start = 0 337 | sub_tokens = [] 338 | while start < len(chars): 339 | end = len(chars) 340 | cur_substr = None 341 | while start < end: 342 | substr = "".join(chars[start:end]) 343 | if start > 0: 344 | substr = "##" + substr 345 | if substr in self.vocab: 346 | cur_substr = substr 347 | break 348 | end -= 1 349 | if cur_substr is None: 350 | is_bad = True 351 | break 352 | sub_tokens.append(cur_substr) 353 | start = end 354 | 355 | if is_bad: 356 | output_tokens.append(self.unk_token) 357 | else: 358 | output_tokens.extend(sub_tokens) 359 | return output_tokens 360 | 361 | 362 | def _is_whitespace(char): 363 | """Checks whether `chars` is a whitespace character.""" 364 | # \t, \n, and \r are technically contorl characters but we treat them 365 | # as whitespace since they are generally considered as such. 366 | if char == " " or char == "\t" or char == "\n" or char == "\r": 367 | return True 368 | cat = unicodedata.category(char) 369 | if cat == "Zs": 370 | return True 371 | return False 372 | 373 | 374 | def _is_control(char): 375 | """Checks whether `chars` is a control character.""" 376 | # These are technically control characters but we count them as whitespace 377 | # characters. 378 | if char == "\t" or char == "\n" or char == "\r": 379 | return False 380 | cat = unicodedata.category(char) 381 | if cat in ("Cc", "Cf"): 382 | return True 383 | return False 384 | 385 | 386 | def _is_punctuation(char): 387 | """Checks whether `chars` is a punctuation character.""" 388 | cp = ord(char) 389 | # We treat all non-letter/number ASCII as punctuation. 390 | # Characters such as "^", "$", and "`" are not in the Unicode 391 | # Punctuation class but we treat them as punctuation anyways, for 392 | # consistency. 393 | if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or 394 | (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): 395 | return True 396 | cat = unicodedata.category(char) 397 | if cat.startswith("P"): 398 | return True 399 | return False 400 | -------------------------------------------------------------------------------- /reformers/TFefficient_attention.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import tensorflow as tf 24 | from tensorflow.keras.layers import Dropout, Dense 25 | from .TFutils import sort_key_val, batched_index_select, make_unit_length, chunked_sum, process_inputs_chunk 26 | 27 | class TFLSHAttention(tf.keras.Model): 28 | def __init__( self, 29 | dropout = 0., 30 | bucket_size = 64, 31 | n_hashes = 8, 32 | causal = False, 33 | allow_duplicate_attention = True, 34 | attend_across_buckets = True, 35 | rehash_each_round = True, 36 | drop_for_hash_rate = 0.0, 37 | random_rotations_per_head = False): 38 | super(TFLSHAttention, self).__init__() 39 | if dropout >= 1.0: 40 | raise ValueError('Dropout rates must be lower than 1.') 41 | 42 | self.dropout = Dropout(dropout) 43 | self.dropout_for_hash = Dropout(dropout) 44 | 45 | assert rehash_each_round or allow_duplicate_attention, ( 46 | 'The setting {allow_duplicate_attention=False, rehash_each_round=False}' 47 | ' is not implemented.') 48 | 49 | self.causal = causal 50 | self.n_hashes = n_hashes 51 | self.bucket_size = bucket_size 52 | 53 | self._allow_duplicate_attention = allow_duplicate_attention 54 | self._attend_across_buckets = attend_across_buckets 55 | self._rehash_each_round = rehash_each_round 56 | self._random_rotations_per_head = random_rotations_per_head 57 | 58 | def hash_vectors(self, n_buckets, vecs): 59 | batch_size = vecs.shape[0] 60 | device = vecs.device 61 | 62 | # See https://arxiv.org/pdf/1509.02897.pdf 63 | # We sample a different random rotation for each round of hashing to 64 | # decrease the probability of hash misses. 65 | assert n_buckets % 2 == 0 66 | 67 | rot_size = n_buckets 68 | 69 | rotations_shape = ( 70 | batch_size if self._random_rotations_per_head else 1, 71 | vecs.shape[-1], 72 | self.n_hashes if self._rehash_each_round else 1, 73 | rot_size // 2) 74 | 75 | random_rotations = tf.broadcast_to(tf.random.normal(rotations_shape), (batch_size, vecs.shape[-1], self.n_hashes if self._rehash_each_round else 1, rot_size // 2)) 76 | 77 | dropped_vecs = self.dropout_for_hash(vecs) 78 | rotated_vecs = tf.einsum('btf,bfhi->bhti', dropped_vecs, random_rotations) 79 | 80 | if self._rehash_each_round: 81 | rotated_vecs = tf.concat([rotated_vecs, -rotated_vecs], axis=-1) 82 | buckets = tf.math.argmax(rotated_vecs, axis=-1) 83 | # buckets is now (self.n_hashes, seqlen). Next we add offsets so that 84 | # bucket numbers from different hashing rounds don't overlap. 85 | offsets = tf.range(self.n_hashes) 86 | offsets = tf.reshape(offsets * n_buckets, (1, -1, 1)) 87 | offsets = tf.cast(offsets, tf.int64) 88 | buckets = tf.reshape(buckets + offsets, (batch_size, -1,)) 89 | else: 90 | rotated_vecs = tf.concat([rotated_vecs, -rotated_vecs], axis=-1) 91 | # In this configuration, we map each item to the top self.n_hashes buckets 92 | rotated_vecs = tf.squeeze(rotated_vecs, axis=0) 93 | bucket_range = tf.range(rotated_vecs.shape[-1]) 94 | bucket_range = tf.reshape(bucket_range, (1, -1)) 95 | bucket_range = tf.broadcast_to(bucket_range, rotated_vecs.shape) 96 | 97 | _, buckets = sort_key_val(rotated_vecs, bucket_range, axis=-1) 98 | buckets = buckets[:, -self.n_hashes:] 99 | 100 | h, *_ = buckets.shape 101 | buckets = tf.reshape(buckets.permute((*_, h)), (-1,)) 102 | 103 | return buckets 104 | 105 | def call(self, qk, v): 106 | batch_size, seqlen, _ = qk.shape 107 | device = qk.device 108 | 109 | n_buckets = seqlen // self.bucket_size 110 | n_bins = n_buckets 111 | 112 | buckets = self.hash_vectors(n_buckets, qk) 113 | # We use the same vector as both a query and a key. 114 | assert int(buckets.shape[1]) == self.n_hashes * seqlen 115 | 116 | ticker = tf.expand_dims(tf.range(self.n_hashes * seqlen), axis=0) 117 | buckets_and_t = seqlen * buckets + tf.cast((ticker % seqlen), tf.int64) 118 | buckets_and_t = tf.stop_gradient(buckets_and_t) 119 | 120 | # Hash-based sort ("s" at the start of variable names means "sorted") 121 | sbuckets_and_t, sticker = sort_key_val(buckets_and_t, ticker, dim=-1) 122 | _, undo_sort = sort_key_val(sticker, ticker, dim=-1) 123 | del ticker 124 | 125 | sbuckets_and_t = tf.stop_gradient(sbuckets_and_t) 126 | sticker = tf.stop_gradient(sticker) 127 | undo_sort = tf.stop_gradient(undo_sort) 128 | 129 | st = (sticker % seqlen) 130 | sqk = batched_index_select(qk, st) 131 | sv = batched_index_select(v, st) 132 | 133 | # Split off a "bin" axis so that attention only occurs within chunks. 134 | bq_t = bkv_t = tf.reshape(st, (batch_size, self.n_hashes * n_bins, -1)) 135 | bqk = tf.reshape(sqk, (batch_size, self.n_hashes * n_bins, -1, sqk.shape[-1])) 136 | bv = tf.reshape(sv, (batch_size, self.n_hashes * n_bins, -1, sv.shape[-1])) 137 | bq_buckets = bkv_buckets = tf.reshape(sbuckets_and_t // seqlen, (batch_size, self.n_hashes * n_bins, -1)) 138 | 139 | # Hashing operates on unit-length vectors. Unnormalized query vectors are 140 | # fine because they effectively provide a learnable temperature for the 141 | # attention softmax, but normalizing keys is needed so that similarity for 142 | # the purposes of attention correctly corresponds to hash locality. 143 | bq = bqk 144 | bk = make_unit_length(bqk) 145 | 146 | # Allow each chunk to attend within itself, and also one chunk back. Chunk 147 | # boundaries might occur in the middle of a sequence of items from the 148 | # same bucket, so this increases the chances of attending to relevant items. 149 | def look_one_back(x): 150 | x_extra = tf.concat([x[:, -1:, ...], x[:, :-1, ...]], axis=1) 151 | return tf.concat([x, x_extra], axis=2) 152 | 153 | bk = look_one_back(bk) 154 | bv = look_one_back(bv) 155 | bkv_t = look_one_back(bkv_t) 156 | bkv_buckets = look_one_back(bkv_buckets) 157 | 158 | # Dot-product attention. 159 | dots = tf.einsum('bhie,bhje->bhij', bq, bk) * (bq.shape[-1] ** -0.5) 160 | 161 | # Causal masking 162 | if self.causal: 163 | mask = bq_t[:, :, :, None] < bkv_t[:, :, None, :] 164 | dots = tf.math.multiply(dots, tf.cast(mask, tf.float32)) + (1-tf.cast(mask, tf.float32)) * float('-inf') 165 | del mask 166 | 167 | # Mask out attention to self except when no other targets are available. 168 | self_mask = bq_t[:, :, :, None] == bkv_t[:, :, None, :] 169 | dots = tf.math.multiply(dots, tf.cast(self_mask, tf.float32)) + (1-tf.cast(self_mask, tf.float32)) * (- 1e5) 170 | del self_mask 171 | 172 | # Mask out attention to other hash buckets. 173 | if not self._attend_across_buckets: 174 | bucket_mask = bq_buckets[:, :, :, None] != bkv_buckets[:, :, None, :] 175 | dots = tf.math.multiply(dots, tf.cast(bucket_mask, tf.float32)) + (1-tf.cast(bucket_mask, tf.float32)) * float('-inf') 176 | del bucket_mask 177 | 178 | # Don't double-count query-key pairs across multiple rounds of hashing. 179 | # There are two possible strategies here. (1) The default is to count how 180 | # many times a query-key pair is repeated, and to lower its log-prob 181 | # correspondingly at each repetition. (2) When hard_k is set, the code 182 | # instead masks all but the first occurence of each query-key pair. 183 | if not self._allow_duplicate_attention: 184 | locs1 = undo_sort // bq_t.shape[-1] 185 | locs2 = (locs1 + 1) % (self.n_hashes * n_bins) 186 | if not self._attend_across_buckets: 187 | locs1 = buckets * (self.n_hashes * n_bins) + locs1 188 | locs2 = buckets * (self.n_hashes * n_bins) + locs2 189 | locs = tf.transpose( 190 | tf.concat([ 191 | tf.reshape(locs1, (batch_size, self.n_hashes, seqlen)), 192 | tf.reshape(locs2, (batch_size, self.n_hashes, seqlen)), 193 | ], 1), 194 | perm=[0, 2, 1]) 195 | 196 | slocs = batched_index_select(locs, st) 197 | b_locs = tf.reshape(slocs, (batch_size, self.n_hashes * n_bins, -1, 2 * self.n_hashes)) 198 | 199 | b_locs1 = b_locs[:, :, :, None, :self.n_hashes] 200 | 201 | bq_locs = b_locs1.expand(b_locs.shape[:3] + (2, self.n_hashes)) 202 | bq_locs = tf.reshape(bq_locs, b_locs.shape) 203 | bkv_locs = look_one_back(b_locs) 204 | 205 | dup_counts = (bq_locs[:, :, :, None, :] == bkv_locs[:, :, None, :, :]) 206 | # for memory considerations, chunk summation of last dimension for counting duplicates 207 | dup_counts = chunked_sum(dup_counts, chunks=(self.n_hashes * batch_size)) 208 | dup_counts = tf.stop_gradient(dup_counts) 209 | assert dup_counts.shape == dots.shape 210 | dots = dots - tf.log(dup_counts + 1e-9) 211 | del dup_counts 212 | 213 | # Softmax. 214 | dots_logsumexp = tf.math.reduce_logsumexp(dots, axis=-1, keepdims=True) 215 | dots = tf.exp(dots - dots_logsumexp) 216 | dots = self.dropout(dots) 217 | 218 | bo = tf.einsum('buij,buje->buie', dots, bv) 219 | so = tf.reshape(bo, (batch_size, -1, bo.shape[-1])) 220 | slogits = tf.reshape(dots_logsumexp, (batch_size, -1,)) 221 | 222 | class UnsortLogits(tf.keras.layers.Layer): 223 | def __init__(self): 224 | super(UnsortLogits, self).__init__() 225 | 226 | def call(self, so, slogits): 227 | so, slogits = tf.stop_gradient(so), tf.stop_gradient(slogits) 228 | o = batched_index_select(so, undo_sort) 229 | _, logits = sort_key_val(sticker, slogits, dim=-1) 230 | return o, logits 231 | 232 | 233 | unsortlogits = UnsortLogits() 234 | o, logits = unsortlogits(so, slogits) 235 | 236 | if self.n_hashes == 1: 237 | out = o 238 | else: 239 | o = tf.reshape(o, (batch_size, self.n_hashes, seqlen, o.shape[-1])) 240 | logits = tf.reshape(logits, (batch_size, self.n_hashes, seqlen, 1)) 241 | probs = tf.exp(logits - tf.math.reduce_logsumexp(logits, axis=1, keepdims=True)) 242 | out = tf.reduce_sum(o * probs, axis=1) 243 | 244 | assert out.shape == v.shape 245 | return out, buckets 246 | 247 | class TFLSHSelfAttention(tf.keras.Model): 248 | def __init__(self, emb, heads = 8, bucket_size = 64, n_hashes = 8, causal = False, attn_chunks = None, random_rotations_per_head = False, attend_across_buckets = True, allow_duplicate_attention = True, **kwargs): 249 | super(TFLSHSelfAttention, self).__init__() 250 | assert emb % heads == 0, 'dimensions must be divisible by number of heads' 251 | 252 | self.emb = emb 253 | self.heads = heads 254 | self.attn_chunks = heads if attn_chunks is None else attn_chunks 255 | 256 | self.toqk = Dense(emb, use_bias = False) 257 | self.tov = Dense(emb, use_bias = False) 258 | self.to_out = Dense(emb) 259 | 260 | self.bucket_size = bucket_size 261 | self.lsh_attn = TFLSHAttention(bucket_size=bucket_size, causal=causal, random_rotations_per_head=random_rotations_per_head, attend_across_buckets = attend_across_buckets, allow_duplicate_attention = allow_duplicate_attention, **kwargs) 262 | 263 | def call(self, inputs): 264 | b, t, e, h = *inputs.shape, self.heads 265 | assert t % self.bucket_size == 0, f'Sequence length needs to be divisible by target bucket size - {self.bucket_size}' 266 | 267 | qk = self.toqk(inputs) 268 | v = self.tov(inputs) 269 | 270 | def merge_heads(v): 271 | return tf.reshape(tf.transpose(tf.reshape(v, (b, t, h, -1)), perm=[0, 2, 1, 3]), (b * h, t, -1)) 272 | 273 | def split_heads(v): 274 | return tf.transpose(tf.reshape(v, (b, t, h, -1)), perm=[0, 2, 1, 3]) 275 | 276 | qk = merge_heads(qk) 277 | v = merge_heads(v) 278 | 279 | outputs = process_inputs_chunk(self.lsh_attn, qk, v, chunks=self.attn_chunks) 280 | attn_out = tf.concat([output for (output, _) in outputs], axis=0) 281 | 282 | out = tf.reshape(split_heads(attn_out), (b, t, e)) 283 | 284 | return self.to_out(out) -------------------------------------------------------------------------------- /train/extract_features.py: -------------------------------------------------------------------------------- 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 | """Extract pre-computed feature vectors from BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import codecs 22 | import collections 23 | import json 24 | import re 25 | 26 | import modeling 27 | import tokenization 28 | import tensorflow as tf 29 | 30 | flags = tf.compat.v1.flags 31 | 32 | FLAGS = flags.FLAGS 33 | 34 | flags.DEFINE_string("input_file", None, "") 35 | 36 | flags.DEFINE_string("output_file", None, "") 37 | 38 | flags.DEFINE_string("layers", "-1,-2,-3,-4", "") 39 | 40 | flags.DEFINE_string( 41 | "bert_config_file", None, 42 | "The config json file corresponding to the pre-trained BERT model. " 43 | "This specifies the model architecture.") 44 | 45 | flags.DEFINE_integer( 46 | "max_seq_length", 128, 47 | "The maximum total input sequence length after WordPiece tokenization. " 48 | "Sequences longer than this will be truncated, and sequences shorter " 49 | "than this will be padded.") 50 | 51 | flags.DEFINE_string( 52 | "init_checkpoint", None, 53 | "Initial checkpoint (usually from a pre-trained BERT model).") 54 | 55 | flags.DEFINE_string("vocab_file", None, 56 | "The vocabulary file that the BERT model was trained on.") 57 | 58 | flags.DEFINE_bool( 59 | "do_lower_case", True, 60 | "Whether to lower case the input text. Should be True for uncased " 61 | "models and False for cased models.") 62 | 63 | flags.DEFINE_integer("batch_size", 32, "Batch size for predictions.") 64 | 65 | flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") 66 | 67 | flags.DEFINE_string("master", None, 68 | "If using a TPU, the address of the master.") 69 | 70 | flags.DEFINE_integer( 71 | "num_tpu_cores", 8, 72 | "Only used if `use_tpu` is True. Total number of TPU cores to use.") 73 | 74 | flags.DEFINE_bool( 75 | "use_one_hot_embeddings", False, 76 | "If True, tf.one_hot will be used for embedding lookups, otherwise " 77 | "tf.nn.embedding_lookup will be used. On TPUs, this should be True " 78 | "since it is much faster.") 79 | 80 | 81 | class InputExample(object): 82 | 83 | def __init__(self, unique_id, text_a, text_b): 84 | self.unique_id = unique_id 85 | self.text_a = text_a 86 | self.text_b = text_b 87 | 88 | 89 | class InputFeatures(object): 90 | """A single set of features of data.""" 91 | 92 | def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): 93 | self.unique_id = unique_id 94 | self.tokens = tokens 95 | self.input_ids = input_ids 96 | self.input_mask = input_mask 97 | self.input_type_ids = input_type_ids 98 | 99 | 100 | def input_fn_builder(features, seq_length): 101 | """Creates an `input_fn` closure to be passed to TPUEstimator.""" 102 | 103 | all_unique_ids = [] 104 | all_input_ids = [] 105 | all_input_mask = [] 106 | all_input_type_ids = [] 107 | 108 | for feature in features: 109 | all_unique_ids.append(feature.unique_id) 110 | all_input_ids.append(feature.input_ids) 111 | all_input_mask.append(feature.input_mask) 112 | all_input_type_ids.append(feature.input_type_ids) 113 | 114 | def input_fn(params): 115 | """The actual input function.""" 116 | batch_size = params["batch_size"] 117 | 118 | num_examples = len(features) 119 | 120 | # This is for demo purposes and does NOT scale to large data sets. We do 121 | # not use Dataset.from_generator() because that uses tf.py_func which is 122 | # not TPU compatible. The right way to load data is with TFRecordReader. 123 | d = tf.data.Dataset.from_tensor_slices({ 124 | "unique_ids": 125 | tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32), 126 | "input_ids": 127 | tf.constant( 128 | all_input_ids, shape=[num_examples, seq_length], 129 | dtype=tf.int32), 130 | "input_mask": 131 | tf.constant( 132 | all_input_mask, 133 | shape=[num_examples, seq_length], 134 | dtype=tf.int32), 135 | "input_type_ids": 136 | tf.constant( 137 | all_input_type_ids, 138 | shape=[num_examples, seq_length], 139 | dtype=tf.int32), 140 | }) 141 | 142 | d = d.batch(batch_size=batch_size, drop_remainder=False) 143 | return d 144 | 145 | return input_fn 146 | 147 | 148 | def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu, 149 | use_one_hot_embeddings): 150 | """Returns `model_fn` closure for TPUEstimator.""" 151 | 152 | def model_fn(features, labels, mode, params): # pylint: disable=unused-argument 153 | """The `model_fn` for TPUEstimator.""" 154 | 155 | unique_ids = features["unique_ids"] 156 | input_ids = features["input_ids"] 157 | input_mask = features["input_mask"] 158 | input_type_ids = features["input_type_ids"] 159 | 160 | model = modeling.BertModel( 161 | config=bert_config, 162 | is_training=False, 163 | input_ids=input_ids, 164 | input_mask=input_mask, 165 | token_type_ids=input_type_ids, 166 | use_one_hot_embeddings=use_one_hot_embeddings) 167 | 168 | if mode != tf.estimator.ModeKeys.PREDICT: 169 | raise ValueError("Only PREDICT modes are supported: %s" % (mode)) 170 | 171 | tvars = tf.compat.v1.trainable_variables() 172 | scaffold_fn = None 173 | (assignment_map, 174 | initialized_variable_names) = modeling.get_assignment_map_from_checkpoint( 175 | tvars, init_checkpoint) 176 | if use_tpu: 177 | 178 | def tpu_scaffold(): 179 | tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map) 180 | return tf.compat.v1.train.Scaffold() 181 | 182 | scaffold_fn = tpu_scaffold 183 | else: 184 | tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map) 185 | 186 | tf.compat.v1.logging.info("**** Trainable Variables ****") 187 | for var in tvars: 188 | init_string = "" 189 | if var.name in initialized_variable_names: 190 | init_string = ", *INIT_FROM_CKPT*" 191 | tf.compat.v1.logging.info(" name = %s, shape = %s%s", var.name, var.shape, 192 | init_string) 193 | 194 | all_layers = model.get_all_encoder_layers() 195 | 196 | predictions = { 197 | "unique_id": unique_ids, 198 | } 199 | 200 | for (i, layer_index) in enumerate(layer_indexes): 201 | predictions["layer_output_%d" % i] = all_layers[layer_index] 202 | 203 | output_spec = tf.compat.v1.estimator.tpu.TPUEstimatorSpec( 204 | mode=mode, predictions=predictions, scaffold_fn=scaffold_fn) 205 | return output_spec 206 | 207 | return model_fn 208 | 209 | 210 | def convert_examples_to_features(examples, seq_length, tokenizer): 211 | """Loads a data file into a list of `InputBatch`s.""" 212 | 213 | features = [] 214 | for (ex_index, example) in enumerate(examples): 215 | tokens_a = tokenizer.tokenize(example.text_a) 216 | 217 | tokens_b = None 218 | if example.text_b: 219 | tokens_b = tokenizer.tokenize(example.text_b) 220 | 221 | if tokens_b: 222 | # Modifies `tokens_a` and `tokens_b` in place so that the total 223 | # length is less than the specified length. 224 | # Account for [CLS], [SEP], [SEP] with "- 3" 225 | _truncate_seq_pair(tokens_a, tokens_b, seq_length - 3) 226 | else: 227 | # Account for [CLS] and [SEP] with "- 2" 228 | if len(tokens_a) > seq_length - 2: 229 | tokens_a = tokens_a[0:(seq_length - 2)] 230 | 231 | # The convention in BERT is: 232 | # (a) For sequence pairs: 233 | # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] 234 | # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 235 | # (b) For single sequences: 236 | # tokens: [CLS] the dog is hairy . [SEP] 237 | # type_ids: 0 0 0 0 0 0 0 238 | # 239 | # Where "type_ids" are used to indicate whether this is the first 240 | # sequence or the second sequence. The embedding vectors for `type=0` and 241 | # `type=1` were learned during pre-training and are added to the wordpiece 242 | # embedding vector (and position vector). This is not *strictly* necessary 243 | # since the [SEP] token unambiguously separates the sequences, but it makes 244 | # it easier for the model to learn the concept of sequences. 245 | # 246 | # For classification tasks, the first vector (corresponding to [CLS]) is 247 | # used as as the "sentence vector". Note that this only makes sense because 248 | # the entire model is fine-tuned. 249 | tokens = [] 250 | input_type_ids = [] 251 | tokens.append("[CLS]") 252 | input_type_ids.append(0) 253 | for token in tokens_a: 254 | tokens.append(token) 255 | input_type_ids.append(0) 256 | tokens.append("[SEP]") 257 | input_type_ids.append(0) 258 | 259 | if tokens_b: 260 | for token in tokens_b: 261 | tokens.append(token) 262 | input_type_ids.append(1) 263 | tokens.append("[SEP]") 264 | input_type_ids.append(1) 265 | 266 | input_ids = tokenizer.convert_tokens_to_ids(tokens) 267 | 268 | # The mask has 1 for real tokens and 0 for padding tokens. Only real 269 | # tokens are attended to. 270 | input_mask = [1] * len(input_ids) 271 | 272 | # Zero-pad up to the sequence length. 273 | while len(input_ids) < seq_length: 274 | input_ids.append(0) 275 | input_mask.append(0) 276 | input_type_ids.append(0) 277 | 278 | assert len(input_ids) == seq_length 279 | assert len(input_mask) == seq_length 280 | assert len(input_type_ids) == seq_length 281 | 282 | if ex_index < 5: 283 | tf.compat.v1.logging.info("*** Example ***") 284 | tf.compat.v1.logging.info("unique_id: %s" % (example.unique_id)) 285 | tf.compat.v1.logging.info("tokens: %s" % " ".join( 286 | [tokenization.printable_text(x) for x in tokens])) 287 | tf.compat.v1.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) 288 | tf.compat.v1.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) 289 | tf.compat.v1.logging.info( 290 | "input_type_ids: %s" % " ".join([str(x) for x in input_type_ids])) 291 | 292 | features.append( 293 | InputFeatures( 294 | unique_id=example.unique_id, 295 | tokens=tokens, 296 | input_ids=input_ids, 297 | input_mask=input_mask, 298 | input_type_ids=input_type_ids)) 299 | return features 300 | 301 | 302 | def _truncate_seq_pair(tokens_a, tokens_b, max_length): 303 | """Truncates a sequence pair in place to the maximum length.""" 304 | 305 | # This is a simple heuristic which will always truncate the longer sequence 306 | # one token at a time. This makes more sense than truncating an equal percent 307 | # of tokens from each, since if one sequence is very short then each token 308 | # that's truncated likely contains more information than a longer sequence. 309 | while True: 310 | total_length = len(tokens_a) + len(tokens_b) 311 | if total_length <= max_length: 312 | break 313 | if len(tokens_a) > len(tokens_b): 314 | tokens_a.pop() 315 | else: 316 | tokens_b.pop() 317 | 318 | 319 | def read_examples(input_file): 320 | """Read a list of `InputExample`s from an input file.""" 321 | examples = [] 322 | unique_id = 0 323 | with tf.io.gfile.GFile(input_file, "r") as reader: 324 | while True: 325 | line = tokenization.convert_to_unicode(reader.readline()) 326 | if not line: 327 | break 328 | line = line.strip() 329 | text_a = None 330 | text_b = None 331 | m = re.match(r"^(.*) \|\|\| (.*)$", line) 332 | if m is None: 333 | text_a = line 334 | else: 335 | text_a = m.group(1) 336 | text_b = m.group(2) 337 | examples.append( 338 | InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b)) 339 | unique_id += 1 340 | return examples 341 | 342 | 343 | def main(_): 344 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) 345 | print(FLAGS) 346 | layer_indexes = [int(x) for x in FLAGS.layers.split(",")] 347 | 348 | bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) 349 | 350 | tokenizer = tokenization.FullTokenizer( 351 | vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) 352 | 353 | is_per_host = tf.compat.v1.estimator.tpu.InputPipelineConfig.PER_HOST_V2 354 | run_config = tf.compat.v1.estimator.tpu.RunConfig( 355 | master=FLAGS.master, 356 | tpu_config=tf.compat.v1.estimator.tpu.TPUConfig( 357 | num_shards=FLAGS.num_tpu_cores, 358 | per_host_input_for_training=is_per_host)) 359 | 360 | examples = read_examples(FLAGS.input_file) 361 | 362 | features = convert_examples_to_features( 363 | examples=examples, seq_length=FLAGS.max_seq_length, tokenizer=tokenizer) 364 | 365 | unique_id_to_feature = {} 366 | for feature in features: 367 | unique_id_to_feature[feature.unique_id] = feature 368 | 369 | model_fn = model_fn_builder( 370 | bert_config=bert_config, 371 | init_checkpoint=FLAGS.init_checkpoint, 372 | layer_indexes=layer_indexes, 373 | use_tpu=FLAGS.use_tpu, 374 | use_one_hot_embeddings=FLAGS.use_one_hot_embeddings) 375 | 376 | # If TPU is not available, this will fall back to normal Estimator on CPU 377 | # or GPU. 378 | estimator = tf.compat.v1.estimator.tpu.TPUEstimator( 379 | use_tpu=FLAGS.use_tpu, 380 | model_fn=model_fn, 381 | config=run_config, 382 | predict_batch_size=FLAGS.batch_size) 383 | 384 | input_fn = input_fn_builder( 385 | features=features, seq_length=FLAGS.max_seq_length) 386 | 387 | with codecs.getwriter("utf-8")(tf.io.gfile.GFile(FLAGS.output_file, 388 | "w")) as writer: 389 | for result in estimator.predict(input_fn, yield_single_examples=True): 390 | unique_id = int(result["unique_id"]) 391 | feature = unique_id_to_feature[unique_id] 392 | output_json = collections.OrderedDict() 393 | output_json["linex_index"] = unique_id 394 | all_features = [] 395 | for (i, token) in enumerate(feature.tokens): 396 | all_layers = [] 397 | for (j, layer_index) in enumerate(layer_indexes): 398 | layer_output = result["layer_output_%d" % j] 399 | layers = collections.OrderedDict() 400 | layers["index"] = layer_index 401 | layers["values"] = [ 402 | round(float(x), 6) for x in layer_output[i:(i + 1)].flat 403 | ] 404 | all_layers.append(layers) 405 | features = collections.OrderedDict() 406 | features["token"] = token 407 | features["layers"] = all_layers 408 | all_features.append(features) 409 | output_json["features"] = all_features 410 | writer.write(json.dumps(output_json) + "\n") 411 | 412 | 413 | if __name__ == "__main__": 414 | flags.mark_flag_as_required("input_file") 415 | flags.mark_flag_as_required("vocab_file") 416 | flags.mark_flag_as_required("bert_config_file") 417 | flags.mark_flag_as_required("init_checkpoint") 418 | flags.mark_flag_as_required("output_file") 419 | tf.compat.v1.app.run() 420 | -------------------------------------------------------------------------------- /train/create_pretraining_data.py: -------------------------------------------------------------------------------- 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 | """Create masked LM/next sentence masked_lm TF examples for BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import collections 22 | import random 23 | import tokenization 24 | import tensorflow as tf 25 | 26 | flags = tf.flags 27 | 28 | FLAGS = flags.FLAGS 29 | 30 | flags.DEFINE_string("input_file", None, 31 | "Input raw text file (or comma-separated list of files).") 32 | 33 | flags.DEFINE_string( 34 | "output_file", None, 35 | "Output TF example file (or comma-separated list of files).") 36 | 37 | flags.DEFINE_string("vocab_file", None, 38 | "The vocabulary file that the BERT model was trained on.") 39 | 40 | flags.DEFINE_bool( 41 | "do_lower_case", True, 42 | "Whether to lower case the input text. Should be True for uncased " 43 | "models and False for cased models.") 44 | 45 | flags.DEFINE_bool( 46 | "do_whole_word_mask", False, 47 | "Whether to use whole word masking rather than per-WordPiece masking.") 48 | 49 | flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.") 50 | 51 | flags.DEFINE_integer("max_predictions_per_seq", 20, 52 | "Maximum number of masked LM predictions per sequence.") 53 | 54 | flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.") 55 | 56 | flags.DEFINE_integer( 57 | "dupe_factor", 10, 58 | "Number of times to duplicate the input data (with different masks).") 59 | 60 | flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.") 61 | 62 | flags.DEFINE_float( 63 | "short_seq_prob", 0.1, 64 | "Probability of creating sequences which are shorter than the " 65 | "maximum length.") 66 | 67 | 68 | class TrainingInstance(object): 69 | """A single training instance (sentence pair).""" 70 | 71 | def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, 72 | is_random_next): 73 | self.tokens = tokens 74 | self.segment_ids = segment_ids 75 | self.is_random_next = is_random_next 76 | self.masked_lm_positions = masked_lm_positions 77 | self.masked_lm_labels = masked_lm_labels 78 | 79 | def __str__(self): 80 | s = "" 81 | s += "tokens: %s\n" % (" ".join( 82 | [tokenization.printable_text(x) for x in self.tokens])) 83 | s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) 84 | s += "is_random_next: %s\n" % self.is_random_next 85 | s += "masked_lm_positions: %s\n" % (" ".join( 86 | [str(x) for x in self.masked_lm_positions])) 87 | s += "masked_lm_labels: %s\n" % (" ".join( 88 | [tokenization.printable_text(x) for x in self.masked_lm_labels])) 89 | s += "\n" 90 | return s 91 | 92 | def __repr__(self): 93 | return self.__str__() 94 | 95 | 96 | def write_instance_to_example_files(instances, tokenizer, max_seq_length, 97 | max_predictions_per_seq, output_files): 98 | """Create TF example files from `TrainingInstance`s.""" 99 | writers = [] 100 | for output_file in output_files: 101 | writers.append(tf.io.TFRecordWriter(output_file)) 102 | 103 | writer_index = 0 104 | 105 | total_written = 0 106 | for (inst_index, instance) in enumerate(instances): 107 | input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) 108 | input_mask = [1] * len(input_ids) 109 | segment_ids = list(instance.segment_ids) 110 | assert len(input_ids) <= max_seq_length 111 | 112 | while len(input_ids) < max_seq_length: 113 | input_ids.append(0) 114 | input_mask.append(0) 115 | segment_ids.append(0) 116 | 117 | assert len(input_ids) == max_seq_length 118 | assert len(input_mask) == max_seq_length 119 | assert len(segment_ids) == max_seq_length 120 | 121 | masked_lm_positions = list(instance.masked_lm_positions) 122 | masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) 123 | masked_lm_weights = [1.0] * len(masked_lm_ids) 124 | 125 | while len(masked_lm_positions) < max_predictions_per_seq: 126 | masked_lm_positions.append(0) 127 | masked_lm_ids.append(0) 128 | masked_lm_weights.append(0.0) 129 | 130 | next_sentence_label = 1 if instance.is_random_next else 0 131 | 132 | features = collections.OrderedDict() 133 | features["input_ids"] = create_int_feature(input_ids) 134 | features["input_mask"] = create_int_feature(input_mask) 135 | features["segment_ids"] = create_int_feature(segment_ids) 136 | features["masked_lm_positions"] = create_int_feature(masked_lm_positions) 137 | features["masked_lm_ids"] = create_int_feature(masked_lm_ids) 138 | features["masked_lm_weights"] = create_float_feature(masked_lm_weights) 139 | features["next_sentence_labels"] = create_int_feature([next_sentence_label]) 140 | 141 | tf_example = tf.train.Example(features=tf.train.Features(feature=features)) 142 | 143 | writers[writer_index].write(tf_example.SerializeToString()) 144 | writer_index = (writer_index + 1) % len(writers) 145 | 146 | total_written += 1 147 | 148 | if inst_index < 20: 149 | tf.compat.v1.logging.info("*** Example ***") 150 | tf.compat.v1.logging.info("tokens: %s" % " ".join( 151 | [tokenization.printable_text(x) for x in instance.tokens])) 152 | 153 | for feature_name in features.keys(): 154 | feature = features[feature_name] 155 | values = [] 156 | if feature.int64_list.value: 157 | values = feature.int64_list.value 158 | elif feature.float_list.value: 159 | values = feature.float_list.value 160 | tf.compat.v1.logging.info( 161 | "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) 162 | 163 | for writer in writers: 164 | writer.close() 165 | 166 | tf.compat.v1.logging.info("Wrote %d total instances", total_written) 167 | 168 | 169 | def create_int_feature(values): 170 | feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) 171 | return feature 172 | 173 | 174 | def create_float_feature(values): 175 | feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) 176 | return feature 177 | 178 | 179 | def create_training_instances(input_files, tokenizer, max_seq_length, 180 | dupe_factor, short_seq_prob, masked_lm_prob, 181 | max_predictions_per_seq, rng): 182 | """Create `TrainingInstance`s from raw text.""" 183 | all_documents = [[]] 184 | 185 | # Input file format: 186 | # (1) One sentence per line. These should ideally be actual sentences, not 187 | # entire paragraphs or arbitrary spans of text. (Because we use the 188 | # sentence boundaries for the "next sentence prediction" task). 189 | # (2) Blank lines between documents. Document boundaries are needed so 190 | # that the "next sentence prediction" task doesn't span between documents. 191 | for input_file in input_files: 192 | with tf.io.gfile.GFile(input_file, "r") as reader: 193 | while True: 194 | line = tokenization.convert_to_unicode(reader.readline()) 195 | if not line: 196 | break 197 | line = line.strip() 198 | 199 | # Empty lines are used as document delimiters 200 | if not line: 201 | all_documents.append([]) 202 | tokens = tokenizer.tokenize(line) 203 | if tokens: 204 | all_documents[-1].append(tokens) 205 | 206 | # Remove empty documents 207 | all_documents = [x for x in all_documents if x] 208 | rng.shuffle(all_documents) 209 | 210 | vocab_words = list(tokenizer.vocab.keys()) 211 | instances = [] 212 | for _ in range(dupe_factor): 213 | for document_index in range(len(all_documents)): 214 | instances.extend( 215 | create_instances_from_document( 216 | all_documents, document_index, max_seq_length, short_seq_prob, 217 | masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) 218 | print('\r', _) 219 | rng.shuffle(instances) 220 | return instances 221 | 222 | 223 | def create_instances_from_document( 224 | all_documents, document_index, max_seq_length, short_seq_prob, 225 | masked_lm_prob, max_predictions_per_seq, vocab_words, rng): 226 | """Creates `TrainingInstance`s for a single document.""" 227 | document = all_documents[document_index] 228 | 229 | # Account for [CLS], [SEP], [SEP] 230 | max_num_tokens = max_seq_length - 3 231 | 232 | # We *usually* want to fill up the entire sequence since we are padding 233 | # to `max_seq_length` anyways, so short sequences are generally wasted 234 | # computation. However, we *sometimes* 235 | # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter 236 | # sequences to minimize the mismatch between pre-training and fine-tuning. 237 | # The `target_seq_length` is just a rough target however, whereas 238 | # `max_seq_length` is a hard limit. 239 | target_seq_length = max_num_tokens 240 | if rng.random() < short_seq_prob: 241 | target_seq_length = rng.randint(2, max_num_tokens) 242 | 243 | # We DON'T just concatenate all of the tokens from a document into a long 244 | # sequence and choose an arbitrary split point because this would make the 245 | # next sentence prediction task too easy. Instead, we split the input into 246 | # segments "A" and "B" based on the actual "sentences" provided by the user 247 | # input. 248 | instances = [] 249 | current_chunk = [] 250 | current_length = 0 251 | i = 0 252 | while i < len(document): 253 | segment = document[i] 254 | current_chunk.append(segment) 255 | current_length += len(segment) 256 | if i == len(document) - 1 or current_length >= target_seq_length: 257 | if current_chunk: 258 | # `a_end` is how many segments from `current_chunk` go into the `A` 259 | # (first) sentence. 260 | a_end = 1 261 | if len(current_chunk) >= 2: 262 | a_end = rng.randint(1, len(current_chunk) - 1) 263 | 264 | tokens_a = [] 265 | for j in range(a_end): 266 | tokens_a.extend(current_chunk[j]) 267 | 268 | tokens_b = [] 269 | # Random next 270 | is_random_next = False 271 | if len(current_chunk) == 1 or rng.random() < 0.5: 272 | is_random_next = True 273 | target_b_length = target_seq_length - len(tokens_a) 274 | 275 | # This should rarely go for more than one iteration for large 276 | # corpora. However, just to be careful, we try to make sure that 277 | # the random document is not the same as the document 278 | # we're processing. 279 | for _ in range(10): 280 | random_document_index = rng.randint(0, len(all_documents) - 1) 281 | if random_document_index != document_index: 282 | break 283 | 284 | random_document = all_documents[random_document_index] 285 | random_start = rng.randint(0, len(random_document) - 1) 286 | for j in range(random_start, len(random_document)): 287 | tokens_b.extend(random_document[j]) 288 | if len(tokens_b) >= target_b_length: 289 | break 290 | # We didn't actually use these segments so we "put them back" so 291 | # they don't go to waste. 292 | num_unused_segments = len(current_chunk) - a_end 293 | i -= num_unused_segments 294 | # Actual next 295 | else: 296 | is_random_next = False 297 | for j in range(a_end, len(current_chunk)): 298 | tokens_b.extend(current_chunk[j]) 299 | truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) 300 | 301 | assert len(tokens_a) >= 1 302 | assert len(tokens_b) >= 1 303 | 304 | tokens = [] 305 | segment_ids = [] 306 | tokens.append("[CLS]") 307 | segment_ids.append(0) 308 | for token in tokens_a: 309 | tokens.append(token) 310 | segment_ids.append(0) 311 | 312 | tokens.append("[SEP]") 313 | segment_ids.append(0) 314 | 315 | for token in tokens_b: 316 | tokens.append(token) 317 | segment_ids.append(1) 318 | tokens.append("[SEP]") 319 | segment_ids.append(1) 320 | 321 | (tokens, masked_lm_positions, 322 | masked_lm_labels) = create_masked_lm_predictions( 323 | tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) 324 | instance = TrainingInstance( 325 | tokens=tokens, 326 | segment_ids=segment_ids, 327 | is_random_next=is_random_next, 328 | masked_lm_positions=masked_lm_positions, 329 | masked_lm_labels=masked_lm_labels) 330 | instances.append(instance) 331 | current_chunk = [] 332 | current_length = 0 333 | i += 1 334 | 335 | return instances 336 | 337 | 338 | MaskedLmInstance = collections.namedtuple("MaskedLmInstance", 339 | ["index", "label"]) 340 | 341 | 342 | def create_masked_lm_predictions(tokens, masked_lm_prob, 343 | max_predictions_per_seq, vocab_words, rng): 344 | """Creates the predictions for the masked LM objective.""" 345 | 346 | cand_indexes = [] 347 | for (i, token) in enumerate(tokens): 348 | if token == "[CLS]" or token == "[SEP]": 349 | continue 350 | # Whole Word Masking means that if we mask all of the wordpieces 351 | # corresponding to an original word. When a word has been split into 352 | # WordPieces, the first token does not have any marker and any subsequence 353 | # tokens are prefixed with ##. So whenever we see the ## token, we 354 | # append it to the previous set of word indexes. 355 | # 356 | # Note that Whole Word Masking does *not* change the training code 357 | # at all -- we still predict each WordPiece independently, softmaxed 358 | # over the entire vocabulary. 359 | if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and 360 | token.startswith("##")): 361 | cand_indexes[-1].append(i) 362 | else: 363 | cand_indexes.append([i]) 364 | 365 | rng.shuffle(cand_indexes) 366 | 367 | output_tokens = list(tokens) 368 | 369 | num_to_predict = min(max_predictions_per_seq, 370 | max(1, int(round(len(tokens) * masked_lm_prob)))) 371 | 372 | masked_lms = [] 373 | covered_indexes = set() 374 | for index_set in cand_indexes: 375 | if len(masked_lms) >= num_to_predict: 376 | break 377 | # If adding a whole-word mask would exceed the maximum number of 378 | # predictions, then just skip this candidate. 379 | if len(masked_lms) + len(index_set) > num_to_predict: 380 | continue 381 | is_any_index_covered = False 382 | for index in index_set: 383 | if index in covered_indexes: 384 | is_any_index_covered = True 385 | break 386 | if is_any_index_covered: 387 | continue 388 | for index in index_set: 389 | covered_indexes.add(index) 390 | 391 | masked_token = None 392 | # 80% of the time, replace with [MASK] 393 | if rng.random() < 0.8: 394 | masked_token = "[MASK]" 395 | else: 396 | # 10% of the time, keep original 397 | if rng.random() < 0.5: 398 | masked_token = tokens[index] 399 | # 10% of the time, replace with random word 400 | else: 401 | masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] 402 | 403 | output_tokens[index] = masked_token 404 | 405 | masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) 406 | assert len(masked_lms) <= num_to_predict 407 | masked_lms = sorted(masked_lms, key=lambda x: x.index) 408 | 409 | masked_lm_positions = [] 410 | masked_lm_labels = [] 411 | for p in masked_lms: 412 | masked_lm_positions.append(p.index) 413 | masked_lm_labels.append(p.label) 414 | 415 | return (output_tokens, masked_lm_positions, masked_lm_labels) 416 | 417 | 418 | def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): 419 | """Truncates a pair of sequences to a maximum sequence length.""" 420 | while True: 421 | total_length = len(tokens_a) + len(tokens_b) 422 | if total_length <= max_num_tokens: 423 | break 424 | 425 | trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b 426 | assert len(trunc_tokens) >= 1 427 | 428 | # We want to sometimes truncate from the front and sometimes from the 429 | # back to add more randomness and avoid biases. 430 | if rng.random() < 0.5: 431 | del trunc_tokens[0] 432 | else: 433 | trunc_tokens.pop() 434 | 435 | 436 | def main(_): 437 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) 438 | 439 | tokenizer = tokenization.FullTokenizer( 440 | vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) 441 | 442 | input_files = [] 443 | for input_pattern in FLAGS.input_file.split(","): 444 | input_files.extend(tf.io.gfile.glob(input_pattern)) 445 | 446 | tf.compat.v1.logging.info("*** Reading from input files ***") 447 | for input_file in input_files: 448 | tf.compat.v1.logging.info(" %s", input_file) 449 | 450 | rng = random.Random(FLAGS.random_seed) 451 | instances = create_training_instances( 452 | input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor, 453 | FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq, 454 | rng) 455 | 456 | output_files = FLAGS.output_file.split(",") 457 | tf.compat.v1.logging.info("*** Writing to output files ***") 458 | for output_file in output_files: 459 | tf.compat.v1.logging.info(" %s", output_file) 460 | 461 | write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length, 462 | FLAGS.max_predictions_per_seq, output_files) 463 | 464 | 465 | if __name__ == "__main__": 466 | flags.mark_flag_as_required("input_file") 467 | flags.mark_flag_as_required("output_file") 468 | flags.mark_flag_as_required("vocab_file") 469 | tf.compat.v1.app.run() 470 | -------------------------------------------------------------------------------- /reformers/blocks.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2020 Streack, Jayakrishna Sahit 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import tensorflow as tf 24 | 25 | class RevBlock(tf.keras.Model): 26 | """Single reversible block containing several `_Residual` blocks. 27 | Each `_Residual` block in turn contains two _ResidualInner blocks, 28 | corresponding to the `F`/`G` functions in the paper. 29 | """ 30 | 31 | def __init__(self, 32 | n_res, 33 | filters, 34 | strides, 35 | input_shape, 36 | batch_norm_first=False, 37 | data_format="channels_first", 38 | bottleneck=False, 39 | fused=True, 40 | dtype=tf.float32): 41 | """Initialize RevBlock. 42 | Args: 43 | n_res: number of residual blocks 44 | filters: list/tuple of integers for output filter sizes of each residual 45 | strides: length 2 list/tuple of integers for height and width strides 46 | input_shape: length 3 list/tuple of integers 47 | batch_norm_first: whether to apply activation and batch norm before conv 48 | data_format: tensor data format, "NCHW"/"NHWC" 49 | bottleneck: use bottleneck residual if True 50 | fused: use fused batch normalization if True 51 | dtype: float16, float32, or float64 52 | """ 53 | super(RevBlock, self).__init__() 54 | self.blocks = tf.train.checkpoint.List() 55 | for i in range(n_res): 56 | curr_batch_norm_first = batch_norm_first and i == 0 57 | curr_strides = strides if i == 0 else (1, 1) 58 | block = _Residual( 59 | filters, 60 | curr_strides, 61 | input_shape, 62 | batch_norm_first=curr_batch_norm_first, 63 | data_format=data_format, 64 | bottleneck=bottleneck, 65 | fused=fused, 66 | dtype=dtype) 67 | self.blocks.append(block) 68 | 69 | if data_format == "channels_first": 70 | input_shape = (filters, input_shape[1] // curr_strides[0], 71 | input_shape[2] // curr_strides[1]) 72 | else: 73 | input_shape = (input_shape[0] // curr_strides[0], 74 | input_shape[1] // curr_strides[1], filters) 75 | 76 | def call(self, h, training=True): 77 | """Apply reversible block to inputs.""" 78 | 79 | for block in self.blocks: 80 | h = block(h, training=training) 81 | return h 82 | 83 | def backward_grads_and_vars(self, x, y, dy, training=True): 84 | """Apply reversible block backward to outputs.""" 85 | 86 | grads_all = [] 87 | vars_all = [] 88 | 89 | for i in reversed(range(len(self.blocks))): 90 | block = self.blocks[i] 91 | if i == 0: 92 | # First block usually contains downsampling that can't be reversed 93 | with tf.GradientTape() as tape: 94 | x = tf.identity(x) 95 | tape.watch(x) 96 | y = block(x, training=training) 97 | 98 | grads_combined = tape.gradient( 99 | y, [x] + block.trainable_variables, output_gradients=dy) 100 | dy = grads_combined[0] 101 | grads_all += grads_combined[1:] 102 | vars_all += block.trainable_variables 103 | else: 104 | y, dy, grads, vars_ = block.backward_grads_and_vars( 105 | y, dy, training=training) 106 | grads_all += grads 107 | vars_all += vars_ 108 | 109 | return dy, grads_all, vars_all 110 | 111 | class ReversibleSequence(tf.keras.Model): 112 | """Single reversible block containing several `_Residual` blocks. 113 | Each `_Residual` block in turn contains two _ResidualInner blocks, 114 | corresponding to the `F`/`G` functions in the paper. 115 | 116 | This is based on PyTorch's RevTorch - ReversibleSequence 117 | """ 118 | 119 | def __init__(self, 120 | blocks): 121 | """Initialize RevBlock. 122 | Args: 123 | n_res: number of residual blocks 124 | filters: list/tuple of integers for output filter sizes of each residual 125 | strides: length 2 list/tuple of integers for height and width strides 126 | input_shape: length 3 list/tuple of integers 127 | batch_norm_first: whether to apply activation and batch norm before conv 128 | data_format: tensor data format, "NCHW"/"NHWC" 129 | bottleneck: use bottleneck residual if True 130 | fused: use fused batch normalization if True 131 | dtype: float16, float32, or float64 132 | """ 133 | super(ReversibleSequence, self).__init__() 134 | self.blocks = blocks 135 | 136 | def call(self, h, training=True): 137 | """Apply reversible block to inputs.""" 138 | for block in self.blocks: 139 | h = block(h, training=training) 140 | return h 141 | 142 | def backward_grads_and_vars(self, x, y, dy, training=True): 143 | """Apply reversible block backward to outputs.""" 144 | 145 | grads_all = [] 146 | vars_all = [] 147 | 148 | for i in reversed(range(len(self.blocks))): 149 | block = self.blocks[i] 150 | if i == 0: 151 | # First block usually contains downsampling that can't be reversed 152 | with tf.GradientTape() as tape: 153 | x = tf.identity(x) 154 | tape.watch(x) 155 | y = block(x, training=training) 156 | 157 | grads_combined = tape.gradient( 158 | y, [x] + block.trainable_variables, output_gradients=dy) 159 | dy = grads_combined[0] 160 | grads_all += grads_combined[1:] 161 | vars_all += block.trainable_variables 162 | else: 163 | y, dy, grads, vars_ = block.backward_grads_and_vars( 164 | y, dy, training=training) 165 | grads_all += grads 166 | vars_all += vars_ 167 | 168 | return dy, grads_all, vars_all 169 | 170 | 171 | # class _Residual(tf.keras.Model): 172 | # """Single residual block contained in a _RevBlock. Each `_Residual` object has 173 | # two _ResidualInner objects, corresponding to the `F` and `G` functions in the 174 | # paper. 175 | # Args: 176 | # filters: output filter size 177 | # strides: length 2 list/tuple of integers for height and width strides 178 | # input_shape: length 3 list/tuple of integers 179 | # batch_norm_first: whether to apply activation and batch norm before conv 180 | # data_format: tensor data format, "NCHW"/"NHWC", 181 | # bottleneck: use bottleneck residual if True 182 | # fused: use fused batch normalization if True 183 | # dtype: float16, float32, or float64 184 | # """ 185 | # def __init__(self, 186 | # filters, 187 | # strides, 188 | # input_shape, 189 | # batch_norm_first=True, 190 | # data_format="channels_first", 191 | # bottleneck=False, 192 | # fused=True, 193 | # dtype=tf.float32): 194 | # super(_Residual, self).__init__() 195 | 196 | # self.filters = filters 197 | # self.strides = strides 198 | # self.axis = 1 if data_format == "channels_first" else 3 199 | # if data_format == "channels_first": 200 | # f_input_shape = (input_shape[0] // 2,) + input_shape[1:] 201 | # g_input_shape = (filters // 2, input_shape[1] // strides[0], 202 | # input_shape[2] // strides[1]) 203 | # else: 204 | # f_input_shape = input_shape[:2] + (input_shape[2] // 2,) 205 | # g_input_shape = (input_shape[0] // strides[0], 206 | # input_shape[1] // strides[1], filters // 2) 207 | 208 | # factory = _BottleneckResidualInner if bottleneck else _ResidualInner 209 | # self.f = factory( 210 | # filters=filters // 2, 211 | # strides=strides, 212 | # input_shape=f_input_shape, 213 | # batch_norm_first=batch_norm_first, 214 | # data_format=data_format, 215 | # fused=fused, 216 | # dtype=dtype) 217 | # self.g = factory( 218 | # filters=filters // 2, 219 | # strides=(1, 1), 220 | # input_shape=g_input_shape, 221 | # batch_norm_first=batch_norm_first, 222 | # data_format=data_format, 223 | # fused=fused, 224 | # dtype=dtype) 225 | 226 | # def call(self, x, training=True, concat=True): 227 | # """Apply residual block to inputs.""" 228 | 229 | # x1, x2 = tf.split(x, num_or_size_splits=2, axis=self.axis) 230 | # f_x2 = self.f(x2, training=training) 231 | # x1_down = ops.downsample( 232 | # x1, self.filters // 2, self.strides, axis=self.axis) 233 | # x2_down = ops.downsample( 234 | # x2, self.filters // 2, self.strides, axis=self.axis) 235 | # y1 = f_x2 + x1_down 236 | # g_y1 = self.g(y1, training=training) 237 | # y2 = g_y1 + x2_down 238 | # if not concat: # For correct backward grads 239 | # return y1, y2 240 | 241 | # return tf.concat([y1, y2], axis=self.axis) 242 | 243 | # def backward_grads_and_vars(self, y, dy, training=True): 244 | # """Manually compute backward gradients given input and output grads.""" 245 | # dy1, dy2 = tf.split(dy, num_or_size_splits=2, axis=self.axis) 246 | 247 | # with tf.GradientTape(persistent=True) as tape: 248 | # y = tf.identity(y) 249 | # tape.watch(y) 250 | # y1, y2 = tf.split(y, num_or_size_splits=2, axis=self.axis) 251 | # z1 = y1 252 | # gz1 = self.g(z1, training=training) 253 | # x2 = y2 - gz1 254 | # fx2 = self.f(x2, training=training) 255 | # x1 = z1 - fx2 256 | 257 | # grads_combined = tape.gradient( 258 | # gz1, [z1] + self.g.trainable_variables, output_gradients=dy2) 259 | # dz1 = dy1 + grads_combined[0] 260 | # dg = grads_combined[1:] 261 | # dx1 = dz1 262 | 263 | # grads_combined = tape.gradient( 264 | # fx2, [x2] + self.f.trainable_variables, output_gradients=dz1) 265 | # dx2 = dy2 + grads_combined[0] 266 | # df = grads_combined[1:] 267 | 268 | # del tape 269 | 270 | # grads = df + dg 271 | # vars_ = self.f.trainable_variables + self.g.trainable_variables 272 | 273 | # x = tf.concat([x1, x2], axis=self.axis) 274 | # dx = tf.concat([dx1, dx2], axis=self.axis) 275 | 276 | # return x, dx, grads, vars_ 277 | 278 | class ReversibleBlock(tf.keras.Model): 279 | """Single residual block contained in a _RevBlock. Each `_Residual` object has 280 | two _ResidualInner objects, corresponding to the `F` and `G` functions in the 281 | paper. This version takes in the F and G block directly, instead of constructing them. 282 | 283 | This implementation is based on PyTorch's RevTorch - ReversibleBlock 284 | Args: 285 | f_block: The first residual block 286 | g_block: the second residual block 287 | split_along_axis: axis for splitting, defaults to 1 288 | """ 289 | 290 | def __init__(self, 291 | f_block, 292 | g_block, 293 | split_along_axis=1): 294 | super(ReversibleBlock, self).__init__() 295 | 296 | self.axis = split_along_axis 297 | self.f = f_block 298 | self.g = g_block 299 | 300 | def call(self, x, training=True, concat=True): 301 | """Apply residual block to inputs.""" 302 | 303 | x1, x2 = tf.split(x, num_or_size_splits=2, axis=self.axis) 304 | f_x2 = self.f(x2, training=training) 305 | y1 = f_x2 + x1 306 | g_y1 = self.g(y1, training=training) 307 | y2 = g_y1 + x2 308 | if not concat: # For correct backward grads 309 | return y1, y2 310 | 311 | return tf.concat([y1, y2], axis=self.axis) 312 | 313 | def backward_grads_and_vars(self, y, dy, training=True): 314 | """Manually compute backward gradients given input and output grads.""" 315 | dy1, dy2 = tf.split(dy, num_or_size_splits=2, axis=self.axis) 316 | 317 | with tf.GradientTape(persistent=True) as tape: 318 | y = tf.identity(y) 319 | tape.watch(y) 320 | y1, y2 = tf.split(y, num_or_size_splits=2, axis=self.axis) 321 | z1 = y1 322 | gz1 = self.g(z1, training=training) 323 | x2 = y2 - gz1 324 | fx2 = self.f(x2, training=training) 325 | x1 = z1 - fx2 326 | 327 | grads_combined = tape.gradient( 328 | gz1, [z1] + self.g.trainable_variables, output_gradients=dy2) 329 | dz1 = dy1 + grads_combined[0] 330 | dg = grads_combined[1:] 331 | dx1 = dz1 332 | 333 | grads_combined = tape.gradient( 334 | fx2, [x2] + self.f.trainable_variables, output_gradients=dz1) 335 | dx2 = dy2 + grads_combined[0] 336 | df = grads_combined[1:] 337 | 338 | del tape 339 | 340 | grads = df + dg 341 | vars_ = self.f.trainable_variables + self.g.trainable_variables 342 | 343 | x = tf.concat([x1, x2], axis=self.axis) 344 | dx = tf.concat([dx1, dx2], axis=self.axis) 345 | 346 | return x, dx, grads, vars_ 347 | 348 | 349 | def _BottleneckResidualInner(filters, 350 | strides, 351 | input_shape, 352 | batch_norm_first=True, 353 | data_format="channels_first", 354 | fused=True, 355 | dtype=tf.float32): 356 | """Single bottleneck residual inner function contained in _Resdual. 357 | Corresponds to the `F`/`G` functions in the paper. 358 | Suitable for training on ImageNet dataset. 359 | Args: 360 | filters: output filter size 361 | strides: length 2 list/tuple of integers for height and width strides 362 | input_shape: length 3 list/tuple of integers 363 | batch_norm_first: whether to apply activation and batch norm before conv 364 | data_format: tensor data format, "NCHW"/"NHWC" 365 | fused: use fused batch normalization if True 366 | dtype: float16, float32, or float64 367 | Returns: 368 | A keras model 369 | """ 370 | 371 | axis = 1 if data_format == "channels_first" else 3 372 | model = tf.keras.Sequential() 373 | if batch_norm_first: 374 | model.add( 375 | tf.keras.layers.BatchNormalization( 376 | axis=axis, input_shape=input_shape, fused=fused, dtype=dtype)) 377 | model.add(tf.keras.layers.Activation("relu")) 378 | model.add( 379 | tf.keras.layers.Conv2D( 380 | filters=filters // 4, 381 | kernel_size=1, 382 | strides=strides, 383 | input_shape=input_shape, 384 | data_format=data_format, 385 | use_bias=False, 386 | padding="SAME", 387 | dtype=dtype)) 388 | 389 | model.add( 390 | tf.keras.layers.BatchNormalization(axis=axis, fused=fused, dtype=dtype)) 391 | model.add(tf.keras.layers.Activation("relu")) 392 | model.add( 393 | tf.keras.layers.Conv2D( 394 | filters=filters // 4, 395 | kernel_size=3, 396 | strides=(1, 1), 397 | data_format=data_format, 398 | use_bias=False, 399 | padding="SAME", 400 | dtype=dtype)) 401 | 402 | model.add( 403 | tf.keras.layers.BatchNormalization(axis=axis, fused=fused, dtype=dtype)) 404 | model.add(tf.keras.layers.Activation("relu")) 405 | model.add( 406 | tf.keras.layers.Conv2D( 407 | filters=filters, 408 | kernel_size=1, 409 | strides=(1, 1), 410 | data_format=data_format, 411 | use_bias=False, 412 | padding="SAME", 413 | dtype=dtype)) 414 | 415 | return model 416 | 417 | 418 | def _ResidualInner(filters, 419 | strides, 420 | input_shape, 421 | batch_norm_first=True, 422 | data_format="channels_first", 423 | fused=True, 424 | dtype=tf.float32): 425 | """Single residual inner function contained in _ResdualBlock. 426 | Corresponds to the `F`/`G` functions in the paper. 427 | Args: 428 | filters: output filter size 429 | strides: length 2 list/tuple of integers for height and width strides 430 | input_shape: length 3 list/tuple of integers 431 | batch_norm_first: whether to apply activation and batch norm before conv 432 | data_format: tensor data format, "NCHW"/"NHWC" 433 | fused: use fused batch normalization if True 434 | dtype: float16, float32, or float64 435 | Returns: 436 | A keras model 437 | """ 438 | 439 | axis = 1 if data_format == "channels_first" else 3 440 | model = tf.keras.Sequential() 441 | if batch_norm_first: 442 | model.add( 443 | tf.keras.layers.BatchNormalization( 444 | axis=axis, input_shape=input_shape, fused=fused, dtype=dtype)) 445 | model.add(tf.keras.layers.Activation("relu")) 446 | model.add( 447 | tf.keras.layers.Conv2D( 448 | filters=filters, 449 | kernel_size=3, 450 | strides=strides, 451 | input_shape=input_shape, 452 | data_format=data_format, 453 | use_bias=False, 454 | padding="SAME", 455 | dtype=dtype)) 456 | 457 | model.add( 458 | tf.keras.layers.BatchNormalization(axis=axis, fused=fused, dtype=dtype)) 459 | model.add(tf.keras.layers.Activation("relu")) 460 | model.add( 461 | tf.keras.layers.Conv2D( 462 | filters=filters, 463 | kernel_size=3, 464 | strides=(1, 1), 465 | data_format=data_format, 466 | use_bias=False, 467 | padding="SAME", 468 | dtype=dtype)) 469 | 470 | return model -------------------------------------------------------------------------------- /train/run_pretraining.py: -------------------------------------------------------------------------------- 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 | """Run masked LM/next sentence masked_lm pre-training for BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import os 22 | import modeling 23 | import optimization 24 | import tensorflow as tf 25 | 26 | flags = tf.compat.v1.flags 27 | 28 | FLAGS = flags.Flag 29 | 30 | ## Required parameters 31 | flags.DEFINE_string( 32 | "bert_config_file", None, 33 | "The config json file corresponding to the pre-trained BERT model. " 34 | "This specifies the model architecture.") 35 | 36 | flags.DEFINE_string( 37 | "input_file", None, 38 | "Input TF example files (can be a glob or comma separated).") 39 | 40 | flags.DEFINE_string( 41 | "output_dir", None, 42 | "The output directory where the model checkpoints will be written.") 43 | 44 | ## Other parameters 45 | flags.DEFINE_string( 46 | "init_checkpoint", None, 47 | "Initial checkpoint (usually from a pre-trained BERT model).") 48 | 49 | flags.DEFINE_integer( 50 | "max_seq_length", 128, 51 | "The maximum total input sequence length after WordPiece tokenization. " 52 | "Sequences longer than this will be truncated, and sequences shorter " 53 | "than this will be padded. Must match data generation.") 54 | 55 | flags.DEFINE_integer( 56 | "max_predictions_per_seq", 20, 57 | "Maximum number of masked LM predictions per sequence. " 58 | "Must match data generation.") 59 | 60 | flags.DEFINE_bool("do_train", False, "Whether to run training.") 61 | 62 | flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") 63 | 64 | flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") 65 | 66 | flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.") 67 | 68 | flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") 69 | 70 | flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.") 71 | 72 | flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.") 73 | 74 | flags.DEFINE_integer("save_checkpoints_steps", 1000, 75 | "How often to save the model checkpoint.") 76 | 77 | flags.DEFINE_integer("iterations_per_loop", 1000, 78 | "How many steps to make in each estimator call.") 79 | 80 | flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.") 81 | 82 | flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") 83 | 84 | flags.DEFINE_string( 85 | "tpu_name", None, 86 | "The Cloud TPU to use for training. This should be either the name " 87 | "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " 88 | "url.") 89 | 90 | flags.DEFINE_string( 91 | "tpu_zone", None, 92 | "[Optional] GCE zone where the Cloud TPU is located in. If not " 93 | "specified, we will attempt to automatically detect the GCE project from " 94 | "metadata.") 95 | 96 | flags.DEFINE_string( 97 | "gcp_project", None, 98 | "[Optional] Project name for the Cloud TPU-enabled project. If not " 99 | "specified, we will attempt to automatically detect the GCE project from " 100 | "metadata.") 101 | 102 | flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") 103 | 104 | flags.DEFINE_integer( 105 | "num_tpu_cores", 8, 106 | "Only used if `use_tpu` is True. Total number of TPU cores to use.") 107 | 108 | 109 | def model_fn_builder(bert_config, init_checkpoint, learning_rate, 110 | num_train_steps, num_warmup_steps, use_tpu, 111 | use_one_hot_embeddings): 112 | """Returns `model_fn` closure for TPUEstimator.""" 113 | 114 | def model_fn(features, labels, mode, params): # pylint: disable=unused-argument 115 | """The `model_fn` for TPUEstimator.""" 116 | 117 | tf.compat.v1.logging.info("*** Features ***") 118 | for name in sorted(features.keys()): 119 | tf.compat.v1.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) 120 | 121 | input_ids = features["input_ids"] 122 | input_mask = features["input_mask"] 123 | segment_ids = features["segment_ids"] 124 | masked_lm_positions = features["masked_lm_positions"] 125 | masked_lm_ids = features["masked_lm_ids"] 126 | masked_lm_weights = features["masked_lm_weights"] 127 | next_sentence_labels = features["next_sentence_labels"] 128 | 129 | is_training = (mode == tf.estimator.ModeKeys.TRAIN) 130 | 131 | model = modeling.BertModel( 132 | config=bert_config, 133 | is_training=is_training, 134 | input_ids=input_ids, 135 | input_mask=input_mask, 136 | token_type_ids=segment_ids, 137 | use_one_hot_embeddings=use_one_hot_embeddings) 138 | 139 | (masked_lm_loss, 140 | masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output( 141 | bert_config, model.get_sequence_output(), model.get_embedding_table(), 142 | masked_lm_positions, masked_lm_ids, masked_lm_weights) 143 | 144 | (next_sentence_loss, next_sentence_example_loss, 145 | next_sentence_log_probs) = get_next_sentence_output( 146 | bert_config, model.get_pooled_output(), next_sentence_labels) 147 | 148 | total_loss = masked_lm_loss + next_sentence_loss 149 | 150 | tvars = tf.compat.v1.trainable_variables() 151 | 152 | initialized_variable_names = {} 153 | scaffold_fn = None 154 | if init_checkpoint: 155 | (assignment_map, initialized_variable_names 156 | ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) 157 | if use_tpu: 158 | 159 | def tpu_scaffold(): 160 | tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map) 161 | return tf.compat.v1.train.Scaffold() 162 | 163 | scaffold_fn = tpu_scaffold 164 | else: 165 | tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map) 166 | 167 | tf.compat.v1.logging.info("**** Trainable Variables ****") 168 | for var in tvars: 169 | init_string = "" 170 | if var.name in initialized_variable_names: 171 | init_string = ", *INIT_FROM_CKPT*" 172 | tf.compat.v1.logging.info(" name = %s, shape = %s%s", var.name, var.shape, 173 | init_string) 174 | 175 | output_spec = None 176 | if mode == tf.estimator.ModeKeys.TRAIN: 177 | train_op = optimization.create_optimizer( 178 | total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) 179 | 180 | output_spec = tf.estimator.EstimatorSpec( 181 | mode=mode, 182 | loss=total_loss, 183 | train_op=train_op, 184 | scaffold=scaffold_fn) 185 | elif mode == tf.estimator.ModeKeys.EVAL: 186 | 187 | def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, 188 | masked_lm_weights, next_sentence_example_loss, 189 | next_sentence_log_probs, next_sentence_labels): 190 | """Computes the loss and accuracy of the model.""" 191 | masked_lm_log_probs = tf.reshape(masked_lm_log_probs, 192 | [-1, masked_lm_log_probs.shape[-1]]) 193 | masked_lm_predictions = tf.argmax( 194 | input=masked_lm_log_probs, axis=-1, output_type=tf.int32) 195 | masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1]) 196 | masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) 197 | masked_lm_weights = tf.reshape(masked_lm_weights, [-1]) 198 | masked_lm_accuracy = tf.compat.v1.metrics.accuracy( 199 | labels=masked_lm_ids, 200 | predictions=masked_lm_predictions, 201 | weights=masked_lm_weights) 202 | masked_lm_mean_loss = tf.compat.v1.metrics.mean( 203 | values=masked_lm_example_loss, weights=masked_lm_weights) 204 | 205 | next_sentence_log_probs = tf.reshape( 206 | next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]]) 207 | next_sentence_predictions = tf.argmax( 208 | input=next_sentence_log_probs, axis=-1, output_type=tf.int32) 209 | next_sentence_labels = tf.reshape(next_sentence_labels, [-1]) 210 | next_sentence_accuracy = tf.compat.v1.metrics.accuracy( 211 | labels=next_sentence_labels, predictions=next_sentence_predictions) 212 | next_sentence_mean_loss = tf.compat.v1.metrics.mean( 213 | values=next_sentence_example_loss) 214 | 215 | return { 216 | "masked_lm_accuracy": masked_lm_accuracy, 217 | "masked_lm_loss": masked_lm_mean_loss, 218 | "next_sentence_accuracy": next_sentence_accuracy, 219 | "next_sentence_loss": next_sentence_mean_loss, 220 | } 221 | 222 | eval_metrics = (metric_fn, [ 223 | masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, 224 | masked_lm_weights, next_sentence_example_loss, 225 | next_sentence_log_probs, next_sentence_labels 226 | ]) 227 | output_spec = tf.estimator.EstimatorSpec( 228 | mode=mode, 229 | loss=total_loss, 230 | eval_metrics_ops=eval_metrics, 231 | scaffold=scaffold_fn) 232 | else: 233 | raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode)) 234 | 235 | return output_spec 236 | 237 | return model_fn 238 | 239 | 240 | def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, 241 | label_ids, label_weights): 242 | """Get loss and log probs for the masked LM.""" 243 | input_tensor = gather_indexes(input_tensor, positions) 244 | 245 | with tf.compat.v1.variable_scope("cls/predictions"): 246 | # We apply one more non-linear transformation before the output layer. 247 | # This matrix is not used after pre-training. 248 | with tf.compat.v1.variable_scope("transform"): 249 | input_tensor = tf.compat.v1.layers.dense( 250 | input_tensor, 251 | units=bert_config.hidden_size, 252 | activation=modeling.get_activation(bert_config.hidden_act), 253 | kernel_initializer=modeling.create_initializer( 254 | bert_config.initializer_range)) 255 | layer_norm = modeling.get_layer_norm() 256 | layer_norm.build(input_tensor.shape) 257 | input_tensor = layer_norm.call(input_tensor) 258 | 259 | # The output weights are the same as the input embeddings, but there is 260 | # an output-only bias for each token. 261 | output_bias = tf.compat.v1.get_variable( 262 | "output_bias", 263 | shape=[bert_config.vocab_size], 264 | initializer=tf.compat.v1.zeros_initializer()) 265 | logits = tf.matmul(input_tensor, output_weights, transpose_b=True) 266 | logits = tf.nn.bias_add(logits, output_bias) 267 | log_probs = tf.nn.log_softmax(logits, axis=-1) 268 | 269 | label_ids = tf.reshape(label_ids, [-1]) 270 | label_weights = tf.reshape(label_weights, [-1]) 271 | 272 | one_hot_labels = tf.one_hot( 273 | label_ids, depth=bert_config.vocab_size, dtype=tf.float32) 274 | 275 | # The `positions` tensor might be zero-padded (if the sequence is too 276 | # short to have the maximum number of predictions). The `label_weights` 277 | # tensor has a value of 1.0 for every real prediction and 0.0 for the 278 | # padding predictions. 279 | per_example_loss = -tf.reduce_sum(input_tensor=log_probs * one_hot_labels, axis=[-1]) 280 | numerator = tf.reduce_sum(input_tensor=label_weights * per_example_loss) 281 | denominator = tf.reduce_sum(input_tensor=label_weights) + 1e-5 282 | loss = numerator / denominator 283 | 284 | return (loss, per_example_loss, log_probs) 285 | 286 | 287 | def get_next_sentence_output(bert_config, input_tensor, labels): 288 | """Get loss and log probs for the next sentence prediction.""" 289 | 290 | # Simple binary classification. Note that 0 is "next sentence" and 1 is 291 | # "random sentence". This weight matrix is not used after pre-training. 292 | with tf.compat.v1.variable_scope("cls/seq_relationship"): 293 | output_weights = tf.compat.v1.get_variable( 294 | "output_weights", 295 | shape=[2, bert_config.hidden_size], 296 | initializer=modeling.create_initializer(bert_config.initializer_range)) 297 | output_bias = tf.compat.v1.get_variable( 298 | "output_bias", shape=[2], initializer=tf.compat.v1.zeros_initializer()) 299 | 300 | logits = tf.matmul(input_tensor, output_weights, transpose_b=True) 301 | logits = tf.nn.bias_add(logits, output_bias) 302 | log_probs = tf.nn.log_softmax(logits, axis=-1) 303 | labels = tf.reshape(labels, [-1]) 304 | one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) 305 | per_example_loss = -tf.reduce_sum(input_tensor=one_hot_labels * log_probs, axis=-1) 306 | loss = tf.reduce_mean(input_tensor=per_example_loss) 307 | return (loss, per_example_loss, log_probs) 308 | 309 | 310 | def gather_indexes(sequence_tensor, positions): 311 | """Gathers the vectors at the specific positions over a minibatch.""" 312 | sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) 313 | batch_size = sequence_shape[0] 314 | seq_length = sequence_shape[1] 315 | width = sequence_shape[2] 316 | 317 | flat_offsets = tf.reshape( 318 | tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]) 319 | flat_positions = tf.reshape(positions + flat_offsets, [-1]) 320 | flat_sequence_tensor = tf.reshape(sequence_tensor, 321 | [batch_size * seq_length, width]) 322 | output_tensor = tf.gather(flat_sequence_tensor, flat_positions) 323 | return output_tensor 324 | 325 | 326 | def input_fn_builder(input_files, 327 | max_seq_length, 328 | max_predictions_per_seq, 329 | is_training, 330 | num_cpu_threads=4): 331 | """Creates an `input_fn` closure to be passed to TPUEstimator.""" 332 | 333 | def input_fn(params): 334 | """The actual input function.""" 335 | try: 336 | batch_size = params["batch_size"] 337 | except: 338 | batch_size = 16 339 | 340 | name_to_features = { 341 | "input_ids": 342 | tf.io.FixedLenFeature([max_seq_length], tf.int64), 343 | "input_mask": 344 | tf.io.FixedLenFeature([max_seq_length], tf.int64), 345 | "segment_ids": 346 | tf.io.FixedLenFeature([max_seq_length], tf.int64), 347 | "masked_lm_positions": 348 | tf.io.FixedLenFeature([max_predictions_per_seq], tf.int64), 349 | "masked_lm_ids": 350 | tf.io.FixedLenFeature([max_predictions_per_seq], tf.int64), 351 | "masked_lm_weights": 352 | tf.io.FixedLenFeature([max_predictions_per_seq], tf.float32), 353 | "next_sentence_labels": 354 | tf.io.FixedLenFeature([1], tf.int64), 355 | } 356 | 357 | # For training, we want a lot of parallel reading and shuffling. 358 | # For eval, we want no shuffling and parallel reading doesn't matter. 359 | if is_training: 360 | d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files)) 361 | d = d.repeat() 362 | d = d.shuffle(buffer_size=len(input_files)) 363 | 364 | # `cycle_length` is the number of parallel files that get read. 365 | cycle_length = min(num_cpu_threads, len(input_files)) 366 | 367 | # `sloppy` mode means that the interleaving is not exact. This adds 368 | # even more randomness to the training pipeline. 369 | d = d.apply( 370 | tf.data.experimental.parallel_interleave( 371 | tf.data.TFRecordDataset, 372 | sloppy=is_training, 373 | cycle_length=cycle_length)) 374 | d = d.shuffle(buffer_size=100) 375 | else: 376 | d = tf.data.TFRecordDataset(input_files) 377 | # Since we evaluate for a fixed number of steps we don't want to encounter 378 | # out-of-range exceptions. 379 | d = d.repeat() 380 | 381 | # We must `drop_remainder` on training because the TPU requires fixed 382 | # size dimensions. For eval, we assume we are evaluating on the CPU or GPU 383 | # and we *don't* want to drop the remainder, otherwise we wont cover 384 | # every sample. 385 | d = d.apply( 386 | tf.data.experimental.map_and_batch( 387 | lambda record: _decode_record(record, name_to_features), 388 | batch_size=batch_size, 389 | num_parallel_batches=num_cpu_threads, 390 | drop_remainder=True)) 391 | return d 392 | 393 | return input_fn 394 | 395 | 396 | def _decode_record(record, name_to_features): 397 | """Decodes a record to a TensorFlow example.""" 398 | example = tf.io.parse_single_example(serialized=record, features=name_to_features) 399 | 400 | # tf.Example only supports tf.int64, but the TPU only supports tf.int32. 401 | # So cast all int64 to int32. 402 | for name in list(example.keys()): 403 | t = example[name] 404 | if t.dtype == tf.int64: 405 | t = tf.cast(t, dtype=tf.int32) 406 | example[name] = t 407 | 408 | return example 409 | 410 | 411 | def main(_): 412 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) 413 | 414 | if not FLAGS.do_train and not FLAGS.do_eval: 415 | raise ValueError("At least one of `do_train` or `do_eval` must be True.") 416 | 417 | bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) 418 | 419 | tf.io.gfile.makedirs(FLAGS.output_dir) 420 | 421 | input_files = [] 422 | for input_pattern in FLAGS.input_file.split(","): 423 | input_files.extend(tf.io.gfile.glob(input_pattern)) 424 | 425 | tf.compat.v1.logging.info("*** Input Files ***") 426 | for input_file in input_files: 427 | tf.compat.v1.logging.info(" %s" % input_file) 428 | 429 | tpu_cluster_resolver = None 430 | if FLAGS.use_tpu and FLAGS.tpu_name: 431 | tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( 432 | FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) 433 | 434 | is_per_host = tf.compat.v1.estimator.tpu.InputPipelineConfig.PER_HOST_V2 435 | run_config = tf.compat.v1.estimator.tpu.RunConfig( 436 | cluster=tpu_cluster_resolver, 437 | master=FLAGS.master, 438 | model_dir=FLAGS.output_dir, 439 | save_checkpoints_steps=FLAGS.save_checkpoints_steps, 440 | tpu_config=tf.compat.v1.estimator.tpu.TPUConfig( 441 | iterations_per_loop=FLAGS.iterations_per_loop, 442 | num_shards=FLAGS.num_tpu_cores, 443 | per_host_input_for_training=is_per_host)) 444 | 445 | model_fn = model_fn_builder( 446 | bert_config=bert_config, 447 | init_checkpoint=FLAGS.init_checkpoint, 448 | learning_rate=FLAGS.learning_rate, 449 | num_train_steps=FLAGS.num_train_steps, 450 | num_warmup_steps=FLAGS.num_warmup_steps, 451 | use_tpu=FLAGS.use_tpu, 452 | use_one_hot_embeddings=FLAGS.use_tpu) 453 | 454 | # If TPU is not available, this will fall back to normal Estimator on CPU 455 | # or GPU. 456 | estimator = tf.compat.v1.estimator.tpu.TPUEstimator( 457 | use_tpu=FLAGS.use_tpu, 458 | model_fn=model_fn, 459 | config=run_config, 460 | train_batch_size=FLAGS.train_batch_size, 461 | eval_batch_size=FLAGS.eval_batch_size) 462 | 463 | if FLAGS.do_train: 464 | tf.compat.v1.logging.info("***** Running training *****") 465 | tf.compat.v1.logging.info(" Batch size = %d", FLAGS.train_batch_size) 466 | train_input_fn = input_fn_builder( 467 | input_files=input_files, 468 | max_seq_length=FLAGS.max_seq_length, 469 | max_predictions_per_seq=FLAGS.max_predictions_per_seq, 470 | is_training=True) 471 | estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps) 472 | 473 | if FLAGS.do_eval: 474 | tf.compat.v1.logging.info("***** Running evaluation *****") 475 | tf.compat.v1.logging.info(" Batch size = %d", FLAGS.eval_batch_size) 476 | 477 | eval_input_fn = input_fn_builder( 478 | input_files=input_files, 479 | max_seq_length=FLAGS.max_seq_length, 480 | max_predictions_per_seq=FLAGS.max_predictions_per_seq, 481 | is_training=False) 482 | 483 | result = estimator.evaluate( 484 | input_fn=eval_input_fn, steps=FLAGS.max_eval_steps) 485 | 486 | output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") 487 | with tf.io.gfile.GFile(output_eval_file, "w") as writer: 488 | tf.compat.v1.logging.info("***** Eval results *****") 489 | for key in sorted(result.keys()): 490 | tf.compat.v1.logging.info(" %s = %s", key, str(result[key])) 491 | writer.write("%s = %s\n" % (key, str(result[key]))) 492 | 493 | 494 | if __name__ == "__main__": 495 | flags.mark_flag_as_required("input_file") 496 | flags.mark_flag_as_required("bert_config_file") 497 | flags.mark_flag_as_required("output_dir") 498 | tf.compat.v1.app.run() 499 | --------------------------------------------------------------------------------