├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── README_files └── span.png ├── adagrad_with_grad_clip.py ├── adaptive_io.py ├── adaptive_span.py ├── config.py ├── data.py ├── experiments ├── enwik8.sh ├── enwik8_large.sh ├── enwik8_pers.sh ├── enwik8_pers_small.sh ├── enwik8_small.sh ├── text8.sh ├── text8_large.sh └── wiki103_pers.sh ├── get_data.sh ├── get_pretrained.sh ├── main.py ├── models.py ├── persistent_memory.py ├── trainer.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | checkpoints 2 | data 3 | 4 | # Created by https://www.gitignore.io/api/linux,macos,python 5 | # Edit at https://www.gitignore.io/?templates=linux,macos,python 6 | 7 | ### Linux ### 8 | *~ 9 | 10 | # temporary files which can be created if a process still has a handle open of a deleted file 11 | .fuse_hidden* 12 | 13 | # KDE directory preferences 14 | .directory 15 | 16 | # Linux trash folder which might appear on any partition or disk 17 | .Trash-* 18 | 19 | # .nfs files are created when an open file is removed but is still being accessed 20 | .nfs* 21 | 22 | ### macOS ### 23 | # General 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must end with two \r 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | .com.apple.timemachine.donotpresent 42 | 43 | # Directories potentially created on remote AFP share 44 | .AppleDB 45 | .AppleDesktop 46 | Network Trash Folder 47 | Temporary Items 48 | .apdisk 49 | 50 | ### Python ### 51 | # Byte-compiled / optimized / DLL files 52 | __pycache__/ 53 | *.py[cod] 54 | *$py.class 55 | 56 | # C extensions 57 | *.so 58 | 59 | # Distribution / packaging 60 | .Python 61 | build/ 62 | develop-eggs/ 63 | dist/ 64 | downloads/ 65 | eggs/ 66 | .eggs/ 67 | lib/ 68 | lib64/ 69 | parts/ 70 | sdist/ 71 | var/ 72 | wheels/ 73 | pip-wheel-metadata/ 74 | share/python-wheels/ 75 | *.egg-info/ 76 | .installed.cfg 77 | *.egg 78 | MANIFEST 79 | 80 | # PyInstaller 81 | # Usually these files are written by a python script from a template 82 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 83 | *.manifest 84 | *.spec 85 | 86 | # Installer logs 87 | pip-log.txt 88 | pip-delete-this-directory.txt 89 | 90 | # Unit test / coverage reports 91 | htmlcov/ 92 | .tox/ 93 | .nox/ 94 | .coverage 95 | .coverage.* 96 | .cache 97 | nosetests.xml 98 | coverage.xml 99 | *.cover 100 | .hypothesis/ 101 | .pytest_cache/ 102 | 103 | # Translations 104 | *.mo 105 | *.pot 106 | 107 | # Django stuff: 108 | *.log 109 | local_settings.py 110 | db.sqlite3 111 | 112 | # Flask stuff: 113 | instance/ 114 | .webassets-cache 115 | 116 | # Scrapy stuff: 117 | .scrapy 118 | 119 | # Sphinx documentation 120 | docs/_build/ 121 | 122 | # PyBuilder 123 | target/ 124 | 125 | # Jupyter Notebook 126 | .ipynb_checkpoints 127 | 128 | # IPython 129 | profile_default/ 130 | ipython_config.py 131 | 132 | # pyenv 133 | .python-version 134 | 135 | # pipenv 136 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 137 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 138 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 139 | # install all needed dependencies. 140 | #Pipfile.lock 141 | 142 | # celery beat schedule file 143 | celerybeat-schedule 144 | 145 | # SageMath parsed files 146 | *.sage.py 147 | 148 | # Environments 149 | .env 150 | .venv 151 | env/ 152 | venv/ 153 | ENV/ 154 | env.bak/ 155 | venv.bak/ 156 | 157 | # Spyder project settings 158 | .spyderproject 159 | .spyproject 160 | 161 | # Rope project settings 162 | .ropeproject 163 | 164 | # mkdocs documentation 165 | /site 166 | 167 | # mypy 168 | .mypy_cache/ 169 | .dmypy.json 170 | dmypy.json 171 | 172 | # Pyre type checker 173 | .pyre/ 174 | 175 | # End of https://www.gitignore.io/api/linux,macos,python 176 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to adaptive-span 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## License 30 | By contributing to adaptive-span, you agree that your contributions will be licensed 31 | under the LICENSE file in the root directory of this source tree. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sequential Transformer 2 | This is a code for training Transformers on sequential tasks such as language modeling. Unlike the original Transformer architecture, it uses caching of previous representations and relative position embeddings to better adapt to sequential tasks. In addition, the code also implements the following projects as described below and in this blog [post](https://ai.facebook.com/blog/making-transformer-networks-simpler-and-more-efficient/): 3 | - [Adaptive Attention Span](#adaptive-attention-span) 4 | - [All-attention Network](#all-attention-network) 5 | 6 | ## Requirements 7 | You need PyTorch 0.4.1 or above and a cuda-enabled GPU to run the code. If there are multiple GPUs available, the code uses `nn.DataParallel` to utilize them. For better efficiency, enable distributed training by `--distributed` argument, which can run on multiple nodes. 8 | 9 | 10 | 11 | ## Adaptive Attention Span 12 | This code can be used for running experiments in [Adaptive Attention Span for Transformers](https://arxiv.org/abs/1905.07799) paper. The adaptive span allows a model to learn an optimal context size for each self-attention head from training data. As shown in the below figure, only few heads require long attention span, thus making it possible to increase the context size to 8k tokens without increasing computation time and memory footprint significantly. 13 | 14 |
15 | 16 |
17 | 18 | An argument `--adapt-span` enables adaptive span. Otherwise a model will have a fixed attention span. The adaptive-span is implemented as a `nn.Module` to make it easier to plug it into other models. 19 | 20 | ### Running experiments in the paper 21 | Scripts for running experiments in the paper are located in `./experiments/` directory. For example, a smaller 8-layer version of our model can be trained on a single GPU by running: 22 | ```bash 23 | bash experiments/enwik8_small.sh 24 | ``` 25 | It should reach about 1.3bpc on dev after 150k steps. 26 | 27 | For training larger models, multiple GPUs are recommended. In the script files, you can configure the number of available GPUs. Increase the `--batch-split` argument if you run out of GPU memory (it splits batches into smaller pieces without changing the final result). 28 | 29 | We obtained the following results in our experiments: 30 | 31 | | Experiment | #params | dev | test | 32 | | ---------- | ---:| ---:| ----:| 33 | | enwik8 | 38M | 1.04 bpb | 1.02 bpb | 34 | | enwik8_large | 209M | 1.00 bpb | 0.98 bpb | 35 | | text8 | 39M | 1.05 bpc | 1.11 bpc | 36 | | text8_large | 209M | 1.01 bpc | 1.07 bpc | 37 | 38 | A large model training takes about 1.2sec/batch near the end (initially it's faster because the attention spans are smaller) on 8 V100 GPUs. So, for example, the whole `enwik8_large` training of 170k steps should take less than 2.4 days. 39 | 40 | ### Pre-trained models 41 | You can download pre-trained models by running the `get_pretrained.sh` script. Then the same scripts in `./experiments/` can be used to evaluate those models. Since the download script puts models in `./checkpoints/`, make sure there is no file with the same name. Note that these pre-trained models are obtained by rerunning the training scripts after the code cleanup, so there are small differences from the above results due to the randomness of the training. 42 | 43 | 44 | ## All-attention Network 45 | The code also can be used for training All-attention Networks introduced in [Augmenting Self-attention with Persistent Memory](https://arxiv.org/abs/1907.01470). If `--pers-mem-size` argument is set to `N`, all FF sublayers will be removed from the model and `N` persistent memory vectors will be added to every self-attention sublayer. The following experiments can be found in `./experiments/` directory. 46 | 47 | | Experiment | #params | dev | test | 48 | | ---------- | ---:| ---:| ----:| 49 | | enwik8_pers_small.sh | 39M | 1.03 bpb | 1.01 bpb | 50 | | enwik8_pers.sh | 114M | 1.00 bpb | 0.98 bpb | 51 | | wiki103_pers.sh | 133M | 18.8 ppl *| 19.7 ppl *| 52 | 53 | (\*This number is slightly better than the paper because it includes end-of-line as a token.) 54 | 55 | ## License 56 | The code is licensed under CC-BY-NC license. See the LICENSE file for more details. 57 | 58 | ## Acknowledgement 59 | We thank Xavier Martinet for helping with cleaning the code. The data preprocessing scripts are downloaded from [awd-lstm](https://github.com/salesforce/awd-lstm-lm/) and [transformer-XL](https://github.com/kimiyoung/transformer-xl) repos. The `adagrad_with_grad_clip.py` is mostly adapted from PyTorch. 60 | -------------------------------------------------------------------------------- /README_files/span.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/adaptive-span/27b815fee821acce2c2d4104cc0720cb1dc74c37/README_files/span.png -------------------------------------------------------------------------------- /adagrad_with_grad_clip.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | from torch.optim import Adagrad 11 | 12 | 13 | def _clip_grad(clr, grad, group_grad_clip): 14 | if group_grad_clip > 0: 15 | norm = grad.norm(2).item() 16 | if norm > group_grad_clip: 17 | clr *= group_grad_clip / (norm + 1e-10) 18 | return clr 19 | 20 | 21 | class AdagradWithGradClip(Adagrad): 22 | """Adagrad algoritm with custom gradient clipping""" 23 | def __init__(self, 24 | params, 25 | lr=1e-2, 26 | lr_decay=0, 27 | weight_decay=0, 28 | initial_accumulator_value=0, 29 | grad_clip=0): 30 | Adagrad.__init__(self, 31 | params, 32 | lr=lr, 33 | lr_decay=lr_decay, 34 | weight_decay=weight_decay, 35 | initial_accumulator_value=initial_accumulator_value) 36 | self.defaults['grad_clip'] = grad_clip 37 | self.param_groups[0].setdefault('grad_clip', grad_clip) 38 | 39 | def step(self, closure=None): 40 | loss = None 41 | if closure is not None: 42 | loss = closure() 43 | 44 | for group in self.param_groups: 45 | for p in group['params']: 46 | if p.grad is None: 47 | continue 48 | 49 | grad = p.grad.data 50 | state = self.state[p] 51 | 52 | state['step'] += 1 53 | 54 | if group['weight_decay'] != 0: 55 | if p.grad.data.is_sparse: 56 | raise RuntimeError("weight_decay option is " 57 | "not compatible with sparse " 58 | "gradients") 59 | grad = grad.add(group['weight_decay'], p.data) 60 | 61 | clr = (group['lr'] / 62 | (1 + (state['step'] - 1) * group['lr_decay'])) 63 | 64 | # clip 65 | clr = _clip_grad(clr=clr, 66 | grad=grad, 67 | group_grad_clip=group['grad_clip']) 68 | 69 | if grad.is_sparse: 70 | # the update is non-linear so indices must be unique 71 | grad = grad.coalesce() 72 | grad_indices = grad._indices() 73 | grad_values = grad._values() 74 | size = grad.size() 75 | 76 | def make_sparse(values): 77 | constructor = grad.new 78 | if grad_indices.dim() == 0 or values.dim() == 0: 79 | return constructor().resize_as_(grad) 80 | return constructor(grad_indices, values, size) 81 | state['sum'].add_(make_sparse(grad_values.pow(2))) 82 | std = state['sum']._sparse_mask(grad) 83 | std_values = std._values().sqrt_().add_(1e-10) 84 | p.data.add_(-clr, make_sparse(grad_values / std_values)) 85 | else: 86 | state['sum'].addcmul_(1, grad, grad) 87 | std = state['sum'].sqrt().add_(1e-10) 88 | p.data.addcdiv_(-clr, grad, std) 89 | 90 | return loss 91 | -------------------------------------------------------------------------------- /adaptive_io.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import torch 11 | from torch import nn 12 | from torch.nn import functional as F 13 | 14 | 15 | class AdaptiveEmbedding(nn.Module): 16 | """ An adaptive embedding module from "Adaptive Input Representations for 17 | Neural Language Modeling" (https://arxiv.org/abs/1809.10853) """ 18 | def __init__(self, n_tokens, d_embed, d_proj, cutoffs, div_val=4): 19 | super(AdaptiveEmbedding, self).__init__() 20 | 21 | self.n_tokens = n_tokens 22 | self.d_embed = d_embed 23 | self.d_proj = d_proj 24 | 25 | assert 0 < min(cutoffs) <= max(cutoffs) < n_tokens 26 | self.cutoffs = cutoffs + [n_tokens] 27 | self.cutoff_ends = [0] + self.cutoffs 28 | self.div_val = div_val 29 | assert self.div_val > 1 30 | assert len(self.cutoffs) > 1 31 | 32 | self.emb_scale = d_proj ** 0.5 33 | 34 | self.emb_layers = nn.ModuleList() 35 | self.emb_projs = nn.ParameterList() 36 | 37 | # embedding layers / projections 38 | for i in range(len(self.cutoffs)): 39 | l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] 40 | d_emb_i = d_embed // (div_val ** i) 41 | self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i)) 42 | self.emb_projs.append(nn.Linear(d_emb_i, d_proj).weight) 43 | 44 | def forward(self, indices): 45 | param = self.emb_layers[0].weight.data 46 | idx_flat = indices.contiguous().view(-1) 47 | emb_flat = torch.zeros([idx_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device) 48 | 49 | # for each cluster 50 | for i in range(len(self.cutoffs)): 51 | # find elements in that cluster 52 | l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] 53 | mask_i = (idx_flat >= l_idx) & (idx_flat < r_idx) 54 | 55 | # if there are no elements, continue 56 | indices_i = mask_i.nonzero().squeeze() 57 | if indices_i.numel() == 0: 58 | continue 59 | 60 | # add embeddings from this cluster 61 | idx_i = idx_flat.index_select(0, indices_i) - l_idx 62 | emb_i = self.emb_layers[i](idx_i) 63 | emb_i = F.linear(emb_i, self.emb_projs[i]) 64 | emb_flat = emb_flat.type_as(emb_i) if emb_flat.dtype != emb_i.dtype else emb_flat # small hack for AMP-O1 65 | emb_flat.index_copy_(0, indices_i, emb_i) 66 | 67 | # reshape embeddings 68 | embed = emb_flat.view(*indices.size(), self.d_proj) 69 | 70 | # rescale embeddings 71 | embed.mul_(self.emb_scale) 72 | 73 | return embed 74 | 75 | 76 | class ProjectedAdaptiveLogSoftmax(nn.Module): 77 | """ An efficient softmax implementation from "Efficient softmax 78 | approximation for GPUs" (http://arxiv.org/abs/1609.04309). """ 79 | def __init__(self, n_tokens, d_embed, d_proj, cutoffs, div_val=4): 80 | super(ProjectedAdaptiveLogSoftmax, self).__init__() 81 | 82 | self.n_tokens = n_tokens 83 | self.d_embed = d_embed 84 | self.d_proj = d_proj 85 | 86 | assert 0 < min(cutoffs) <= max(cutoffs) < n_tokens 87 | self.cutoffs = cutoffs + [n_tokens] 88 | self.cutoff_ends = [0] + self.cutoffs 89 | self.div_val = div_val 90 | assert self.div_val > 1 91 | assert len(self.cutoffs) > 1 92 | 93 | self.shortlist_size = self.cutoffs[0] 94 | self.n_clusters = len(self.cutoffs) - 1 95 | self.head_size = self.shortlist_size + self.n_clusters 96 | 97 | # clusters parameters 98 | self.cluster_proj = nn.Linear(self.d_embed, self.n_clusters) 99 | 100 | self.out_layers = nn.ModuleList() 101 | self.out_projs = nn.ParameterList() 102 | 103 | # output layers / projections 104 | for i in range(len(self.cutoffs)): 105 | l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1] 106 | d_emb_i = d_embed // (div_val ** i) 107 | self.out_projs.append(nn.Linear(d_emb_i, d_proj).weight) 108 | self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx)) 109 | 110 | def _compute_logit(self, hidden, weight, bias, proj): 111 | proj_hid = F.linear(hidden, proj.t().contiguous()) # TODO: .contiguous() not necessary? 112 | logit = F.linear(proj_hid, weight, bias=bias) 113 | return logit 114 | 115 | def forward(self, hidden, target): 116 | """ 117 | Input: 118 | - `hidden` FloatTensor(shape + (d_proj,)) 119 | - `target` LongTensor(shape) 120 | Output: 121 | - `nll` FloatTensor(shape) 122 | """ 123 | assert hidden.shape[-1] == self.d_proj 124 | assert hidden.shape[:-1] == target.shape 125 | shape = target.shape 126 | hidden = hidden.view(-1, self.d_proj) 127 | target = target.view(-1) 128 | 129 | # construct weights and biases 130 | weights, biases = [], [] 131 | for i in range(len(self.cutoffs)): 132 | weight_i = self.out_layers[i].weight 133 | bias_i = self.out_layers[i].bias 134 | if i == 0: 135 | weight_i = torch.cat([weight_i, self.cluster_proj.weight], dim=0) 136 | bias_i = torch.cat([bias_i, self.cluster_proj.bias], dim=0) 137 | weights.append(weight_i) 138 | biases.append(bias_i) 139 | 140 | # head / cluster assignments 141 | head_logit = self._compute_logit(hidden, weights[0], biases[0], self.out_projs[0]) 142 | head_logprob = F.log_softmax(head_logit.float(), dim=1) 143 | 144 | # final log-probabilities 145 | nll = torch.zeros_like(target, dtype=torch.float32, device=hidden.device) 146 | 147 | offset = 0 148 | cutoff_values = [0] + self.cutoffs 149 | 150 | # for each cluster 151 | for i in range(len(cutoff_values) - 1): 152 | 153 | # select the target tokens in that cluster 154 | l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1] 155 | mask_i = (target >= l_idx) & (target < r_idx) 156 | indices_i = mask_i.nonzero().squeeze() 157 | 158 | # if there are not any, there is nothing to do 159 | if indices_i.numel() == 0: 160 | continue 161 | 162 | # index in current cluster 163 | target_i = target.index_select(0, indices_i) - l_idx 164 | head_logprob_i = head_logprob.index_select(0, indices_i) 165 | 166 | if i == 0: 167 | # for targets in the head cluster, there is just the head score 168 | logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1) 169 | else: 170 | # otherwise, we sum the cluster assignment (head) and target scores 171 | hidden_i = hidden.index_select(0, indices_i) 172 | tail_logit_i = self._compute_logit(hidden_i, weights[i], biases[i], self.out_projs[i]) 173 | tail_logprob_i = F.log_softmax(tail_logit_i.float(), dim=1) 174 | logprob_i = head_logprob_i[:, -i] + tail_logprob_i.gather(1, target_i[:, None]).squeeze(1) 175 | 176 | # populate output 177 | nll.index_copy_(0, indices_i, -logprob_i) 178 | 179 | offset += logprob_i.size(0) 180 | 181 | return nll.view(shape) 182 | 183 | 184 | def compute_dummy_loss(in_emb, out_emb): 185 | # hack to fix adaptive ou/in with distributed code 186 | dummy_loss = 0 * ( 187 | sum(x.weight[0, 0] for x in in_emb.emb_layers) + 188 | sum(x[0, 0] for x in in_emb.emb_projs) + 189 | sum(x[0, 0] for x in out_emb.out_projs) + 190 | sum(x.weight[0, 0] for x in out_emb.out_layers) + 191 | sum(x.bias[0] for x in out_emb.out_layers) 192 | ) 193 | return dummy_loss 194 | 195 | 196 | def build_adaptive_io(vocab_size, hidden_size, adapt_io_cutoffs, 197 | adapt_io_divval, adapt_io_tied, **kargs): 198 | in_emb = AdaptiveEmbedding( 199 | vocab_size, hidden_size, hidden_size, 200 | cutoffs=adapt_io_cutoffs, 201 | div_val=adapt_io_divval) 202 | out_emb = ProjectedAdaptiveLogSoftmax( 203 | vocab_size, hidden_size, hidden_size, 204 | cutoffs=adapt_io_cutoffs, 205 | div_val=adapt_io_divval) 206 | if adapt_io_tied: 207 | for i in range(len(adapt_io_cutoffs) + 1): 208 | out_emb.out_layers[i].weight = in_emb.emb_layers[i].weight 209 | out_emb.out_projs[i] = in_emb.emb_projs[i] 210 | return in_emb, out_emb 211 | -------------------------------------------------------------------------------- /adaptive_span.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import math 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | 16 | 17 | class AdaptiveMask(nn.Module): 18 | """Soft masking function for adaptive size. 19 | It masks out the last K values of an input. The masking value 20 | goes from 1 to 0 gradually, so K can be learned with 21 | back-propagation. 22 | 23 | Args: 24 | max_size: maximum size (i.e. input dimension) 25 | ramp_size: size of the ramp going from 0 to 1 26 | init_val: initial size proportion not to be masked out 27 | shape: learn multiple sizes independent of each other 28 | """ 29 | 30 | def __init__(self, max_size, ramp_size, init_val=0, shape=(1,)): 31 | nn.Module.__init__(self) 32 | self._max_size = max_size 33 | self._ramp_size = ramp_size 34 | self.current_val = nn.Parameter(torch.zeros(*shape) + init_val) 35 | mask_template = torch.linspace(1 - max_size, 0, steps=max_size) 36 | self.register_buffer('mask_template', mask_template) 37 | 38 | def forward(self, x): 39 | mask = self.mask_template + self.current_val * self._max_size 40 | mask = mask / self._ramp_size + 1 41 | mask = mask.clamp(0, 1) 42 | if x.size(-1) < self._max_size: 43 | # the input could have been trimmed beforehand to save computation 44 | mask = mask[:, :, -x.size(-1):] 45 | x = x * mask 46 | return x 47 | 48 | def get_current_max_size(self, include_ramp=True): 49 | current_size = math.ceil(self.current_val.max().item() * self._max_size) 50 | if include_ramp: 51 | current_size += self._ramp_size 52 | current_size = max(0, min(self._max_size, current_size)) 53 | return current_size 54 | 55 | def get_current_avg_size(self, include_ramp=True): 56 | current_size = math.ceil(self.current_val.mean().item() * self._max_size) 57 | if include_ramp: 58 | current_size += self._ramp_size 59 | current_size = max(0, min(self._max_size, current_size)) 60 | return current_size 61 | 62 | def clamp_param(self): 63 | """this need to be called after each update""" 64 | self.current_val.data.clamp_(0, 1) 65 | 66 | 67 | class AdaptiveSpan(nn.Module): 68 | """Adaptive attention span for Transformerself. 69 | This module learns an attention span length from data for each 70 | self-attention head. 71 | 72 | Args: 73 | attn_span: maximum attention span 74 | adapt_span_loss: loss coefficient for the span length 75 | adapt_span_ramp: length of the masking ramp 76 | adapt_span_init: initial size ratio 77 | adapt_span_cache: adapt cache size to reduce memory usage 78 | """ 79 | def __init__(self, attn_span, adapt_span_loss, adapt_span_ramp, 80 | adapt_span_init, adapt_span_cache, nb_heads, **kargs): 81 | nn.Module.__init__(self) 82 | self._adapt_cache = adapt_span_cache 83 | self._max_span = attn_span 84 | self._loss_coeff = adapt_span_loss 85 | self._nb_heads = nb_heads 86 | self._mask = AdaptiveMask(max_size=self._max_span, 87 | ramp_size=adapt_span_ramp, 88 | init_val=adapt_span_init, 89 | shape=(nb_heads, 1, 1)) 90 | 91 | def forward(self, attn, normalize=True): 92 | """mask attention with the right span""" 93 | # batch and head dimensions are merged together, so separate them first 94 | B = attn.size(0) # batch size 95 | M = attn.size(1) # block size 96 | attn = attn.reshape(B // self._nb_heads, self._nb_heads, M, -1) 97 | 98 | attn = self._mask(attn) 99 | if normalize: 100 | attn = attn / (attn.sum(-1, keepdim=True) + 1e-8) # normalize so sum is 1 101 | 102 | attn = attn.view(B, M, -1) 103 | return attn 104 | 105 | def get_trim_len(self): 106 | """how much of memory can be trimmed to reduce computation""" 107 | L = self._max_span 108 | trim_len = min(L - 1, L - self._mask.get_current_max_size()) 109 | # too fine granularity might be bad for the memory management 110 | trim_len = math.floor(trim_len / 64) * 64 111 | return trim_len 112 | 113 | def trim_memory(self, query, key, value, key_pe): 114 | """trim out unnecessary memory beforehand to reduce computation""" 115 | trim_len = self.get_trim_len() 116 | cache_size = key.size(1) - query.size(1) 117 | trim_len_cache = trim_len - (self._max_span - cache_size) 118 | if trim_len_cache > 0: 119 | key = key[:, trim_len_cache:, :] 120 | value = value[:, trim_len_cache:, :] 121 | elif trim_len_cache < 0: 122 | # cache is too short! this happens when validation resumes 123 | # after a lot of updates. 124 | key = F.pad(key, [0, 0, -trim_len_cache, 0]) 125 | value = F.pad(value, [0, 0, -trim_len_cache, 0]) 126 | if trim_len > 0: 127 | if key_pe is not None: 128 | key_pe = key_pe[:, :, trim_len:] 129 | return key, value, key_pe 130 | 131 | def get_cache_size(self): 132 | """determine how long the cache should be""" 133 | if self._adapt_cache: 134 | trim_len = self.get_trim_len() 135 | # give a buffer of 64 steps since a span might increase 136 | # in future updates 137 | return min(self._max_span, self._max_span - trim_len + 64) 138 | else: 139 | return self._max_span 140 | 141 | def get_loss(self): 142 | """a loss term for regularizing the span length""" 143 | return self._loss_coeff * self._max_span * self._mask.current_val.mean() 144 | 145 | def get_current_max_span(self): 146 | return self._mask.get_current_max_size() 147 | 148 | def get_current_avg_span(self): 149 | return self._mask.get_current_avg_size() 150 | 151 | def clamp_param(self): 152 | self._mask.clamp_param() 153 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | # command-line arguments with their default values 11 | 12 | PARAMS_CONFIG = { 13 | # env-specific 14 | 'env_params': { 15 | '--distributed': { 16 | 'action': 'store_true', 17 | 'default': False, 18 | 'help': 'enable distributed training.' 19 | '(otherwise will use all available GPUs with dataparallel)', 20 | 'dest': 'distributed' 21 | }, 22 | '--local_rank': { 23 | 'type': int, 24 | 'default': 0, 25 | 'help': 'used in distributed training', 26 | 'dest': 'local_rank' 27 | }, 28 | }, 29 | # data-specific 30 | 'data_params': { 31 | '--data': { 32 | 'type': str, 33 | 'default': 'data/text8', 34 | 'help': 'data location ' 35 | '(must contain train.txt, valid.txt and test.txt)', 36 | 'dest': 'data_path' 37 | }, 38 | '--data-unit': { 39 | 'type': str, 40 | 'default': 'bpc', 41 | 'choices': ['bpc', 'ppl'], 42 | 'help': 'loss unit to log', 43 | 'dest': 'data_unit' 44 | }, 45 | }, 46 | # model-specific 47 | 'model_params': { 48 | '--hid-sz': { 49 | 'type': int, 50 | 'default': 256, 51 | 'help': 'hidden size (i.e. model size)', 52 | 'dest': 'hidden_size' 53 | }, 54 | '--inner-hid-sz': { 55 | 'type': int, 56 | 'default': 1024, 57 | 'help': 'inner hidden size of FF layer', 58 | 'dest': 'inner_hidden_size' 59 | }, 60 | '--nlayers': { 61 | 'type': int, 62 | 'default': 8, 63 | 'help': 'number of layers', 64 | 'dest': 'nb_layers' 65 | }, 66 | '--block-sz': { 67 | 'type': int, 68 | 'default': 64, 69 | 'help': 'block size ' 70 | '(the length of sequence to process in parallel)', 71 | 'dest': 'block_size' 72 | }, 73 | '--nheads': { 74 | 'type': int, 75 | 'default': 2, 76 | 'help': 'number of self-attention heads', 77 | 'dest': 'nb_heads' 78 | }, 79 | '--attn-span': { 80 | 'type': int, 81 | 'default': 32, 82 | 'help': 'length of the attention span', 83 | 'dest': 'attn_span' 84 | }, 85 | '--dropout': { 86 | 'type': float, 87 | 'default': 0.2, 88 | 'help': 'dropout rate of ReLU and attention', 89 | 'dest': 'dropout' 90 | }, 91 | '--emb-dropout': { 92 | 'type': float, 93 | 'default': 0., 94 | 'help': 'the dropout rate applied on I/O embeddings', 95 | 'dest': 'emb_dropout' 96 | }, 97 | }, 98 | # optimization-specific 99 | 'optim_params': { 100 | '--lr': { 101 | 'type': float, 102 | 'default': 0.03, 103 | 'help': 'learning rate', 104 | 'dest': 'lr' 105 | }, 106 | '--momentum': { 107 | 'type': float, 108 | 'default': 0.9, 109 | 'help': 'SGD momentum', 110 | 'dest': 'momentum' 111 | }, 112 | '--optim': { 113 | 'type': str, 114 | 'default': 'sgd', 115 | 'help': 'optimization method: sgd | adagrad', 116 | 'dest': 'optim' 117 | }, 118 | '--lr-warmup': { 119 | 'type': int, 120 | 'default': 0, 121 | 'help': 'linearly increase LR from 0 ' 122 | 'during first lr_warmup updates', 123 | 'dest': 'lr_warmup' 124 | }, 125 | '--grad-clip': { 126 | 'type': float, 127 | 'default': 0, 128 | 'help': '[only works with adagrad!] ' 129 | 'clip gradient of each module parameters by a given ' 130 | 'value', 131 | 'dest': 'grad_clip' 132 | }, 133 | }, 134 | # trainer-specific 135 | 'trainer_params': { 136 | '--batch-sz': { 137 | 'type': int, 138 | 'default': 64, 139 | 'help': 'batch size', 140 | 'dest': 'batch_size' 141 | }, 142 | '--batch-split': { 143 | 'type': int, 144 | 'default': 1, 145 | 'help': 'split a batch into smaller parts to fit in GPU memory', 146 | 'dest': 'batch_split' 147 | }, 148 | '--nbatches': { 149 | 'type': int, 150 | 'default': 1000, 151 | 'help': 'number of batches in each iteration', 152 | 'dest': 'nb_batches_per_iter' 153 | }, 154 | '--niter': { 155 | 'type': int, 156 | 'default': 1000, 157 | 'help': 'number of iterations to train', 158 | 'dest': 'nb_iter' 159 | }, 160 | '--checkpoint': { 161 | 'type': str, 162 | 'default': '', 163 | 'help': 'path to save/load model', 164 | 'dest': 'checkpoint_path' 165 | }, 166 | '--full-eval-mode': { 167 | 'action': 'store_true', 168 | 'default': False, 169 | 'help': 'do evaluation on the whole validation and the test data', 170 | 'dest': 'full_eval_mode' 171 | }, 172 | }, 173 | # adaptive I/O specific params 174 | 'adapt_io_params': { 175 | '--adapt-io': { 176 | 'action': 'store_true', 177 | 'default': False, 178 | 'help': 'enable adaptive input and output representations', 179 | 'dest': 'adapt_io_enabled' 180 | }, 181 | '--adapt-io-tied': { 182 | 'action': 'store_true', 183 | 'default': False, 184 | 'help': 'tie the input parameters with the output parameters', 185 | 'dest': 'adapt_io_tied' 186 | }, 187 | '--adapt-io-divval': { 188 | 'type': int, 189 | 'default': 4, 190 | 'help': 'dimension division value', 191 | 'dest': 'adapt_io_divval' 192 | }, 193 | '--adapt-io-cutoffs': { 194 | 'type': int, 195 | 'default': [20000, 40000, 200000], 196 | 'help': 'cutoffs values', 197 | 'dest': 'adapt_io_cutoffs' 198 | }, 199 | }, 200 | # adaptive attention span specific params 201 | 'adapt_span_params': { 202 | '--adapt-span': { 203 | 'action': 'store_true', 204 | 'default': False, 205 | 'help': 'enable adaptive attention span', 206 | 'dest': 'adapt_span_enabled' 207 | }, 208 | '--adapt-span-loss': { 209 | 'type': float, 210 | 'default': 0, 211 | 'help': 'the loss coefficient for span lengths', 212 | 'dest': 'adapt_span_loss' 213 | }, 214 | '--adapt-span-ramp': { 215 | 'type': int, 216 | 'default': 32, 217 | 'help': 'ramp length of the soft masking function', 218 | 'dest': 'adapt_span_ramp' 219 | }, 220 | '--adapt-span-init': { 221 | 'type': float, 222 | 'default': 0, 223 | 'help': 'initial attention span ratio', 224 | 'dest': 'adapt_span_init' 225 | }, 226 | '--adapt-span-cache': { 227 | 'action': 'store_true', 228 | 'default': False, 229 | 'help': 'adapt cache size as well to reduce memory usage', 230 | 'dest': 'adapt_span_cache' 231 | }, 232 | }, 233 | # persistent memory specific params 234 | 'pers_mem_params': { 235 | '--pers-mem-size': { 236 | 'type': int, 237 | 'default': 0, 238 | 'help': 'the number of persistent memory vectors', 239 | 'dest': 'pers_mem_size' 240 | }, 241 | }, 242 | } 243 | -------------------------------------------------------------------------------- /data.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import os 11 | import torch 12 | 13 | 14 | class Dictionary(object): 15 | def __init__(self, path, sort_dict=False): 16 | self.word2idx = {} 17 | self.word2count = {} 18 | self.idx2word = [] 19 | 20 | assert os.path.exists(path) 21 | # Add words to the dictionary 22 | with open(path, 'r', encoding="utf8") as f: 23 | for line in f: 24 | words = line.split() + [''] 25 | for word in words: 26 | if sort_dict: 27 | self.word2count[word] = self.word2count.get(word, 0) + 1 28 | elif word not in self.word2idx: 29 | self.word2idx[word] = len(self.idx2word) 30 | self.idx2word.append(word) 31 | if sort_dict: 32 | # Sort dictionary by count and build indices accordingly: 33 | sorted_dict = sorted(self.word2count.items(), key=lambda kv: kv[1])[::-1] 34 | for i in range(len(sorted_dict)): 35 | word = sorted_dict[i][0] 36 | self.word2idx[word] = i 37 | self.idx2word.append(word) 38 | 39 | def __len__(self): 40 | return len(self.idx2word) 41 | 42 | 43 | def _tokenize(text_path, dictionary): 44 | """Tokenizes a text file.""" 45 | print('Tokenizing {}'.format(text_path)) 46 | assert os.path.exists(text_path) 47 | 48 | # Assign to each token its identifier 49 | ids = [] 50 | with open(text_path, 'r', encoding="utf8") as f: 51 | for line in f: 52 | tokens = line.split() + [''] 53 | for token in tokens: 54 | ids.append(dictionary[token]) 55 | ids = torch.LongTensor(ids) 56 | 57 | return ids 58 | 59 | 60 | class Corpus: 61 | def __init__(self, data_path, sort_dict): 62 | print('Building dictionary') 63 | self._dictionary = Dictionary(os.path.join(data_path, 'train.txt'), sort_dict) 64 | 65 | self.train = _tokenize( 66 | text_path=os.path.join(data_path, 'train.txt'), 67 | dictionary=self._dictionary.word2idx) 68 | self.valid = _tokenize( 69 | text_path=os.path.join(data_path, 'valid.txt'), 70 | dictionary=self._dictionary.word2idx) 71 | self.test = _tokenize( 72 | text_path=os.path.join(data_path, 'test.txt'), 73 | dictionary=self._dictionary.word2idx) 74 | 75 | @property 76 | def vocab_size(self): 77 | return len(self._dictionary) 78 | 79 | 80 | def _batchify(data_tensor, batch_size): 81 | nb_batches = data_tensor.size(0) // batch_size 82 | # trim away some tokens to make whole batches 83 | data_tensor = data_tensor.narrow(0, 0, nb_batches * batch_size) 84 | data_tensor = data_tensor.view(batch_size, -1).contiguous() 85 | return data_tensor 86 | 87 | 88 | def _build_corpus(data_path, env_params, sort_dict): 89 | # save the corpus to a file so that it's faster next time 90 | if sort_dict: 91 | corpus_path = os.path.join(data_path, 'corpus_sorted.pt') 92 | else: 93 | corpus_path = os.path.join(data_path, 'corpus.pt') 94 | if os.path.exists(corpus_path): 95 | print('Loading an existing corpus file from {}'.format(corpus_path)) 96 | corpus = torch.load(corpus_path) 97 | else: 98 | print('Creating a corpus file at {}'.format(corpus_path)) 99 | if env_params['distributed']: 100 | # only one process need to create a corpus file 101 | if env_params['rank'] == 0: 102 | corpus = Corpus(data_path, sort_dict) 103 | torch.save(corpus, corpus_path) 104 | # sync with other processes 105 | torch.distributed.broadcast(torch.zeros(1).cuda(), src=0) 106 | else: 107 | print('Waiting rank0 to create a corpus file.') 108 | # sync with rank0 109 | torch.distributed.broadcast(torch.zeros(1).cuda(), src=0) 110 | corpus = torch.load(corpus_path) 111 | else: 112 | corpus = Corpus(data_path, sort_dict) 113 | torch.save(corpus, corpus_path) 114 | return corpus 115 | 116 | 117 | def _get_train_val_test_data(corpus, batch_size): 118 | return [ 119 | _batchify(corpus.train, batch_size), 120 | _batchify(corpus.valid, batch_size), 121 | _batchify(corpus.test, batch_size) 122 | ] 123 | 124 | 125 | def get_train_val_test_data(data_params, env_params, batch_size, device, sort_dict): 126 | corpus = _build_corpus(data_params['data_path'], env_params, sort_dict) 127 | data_params['vocab_size'] = corpus.vocab_size 128 | train_data, val_data, test_data = _get_train_val_test_data( 129 | corpus=corpus, batch_size=batch_size) 130 | 131 | if env_params['distributed']: 132 | # split the data into equal parts 133 | assert batch_size % env_params['world_size'] == 0 134 | device_batch_size = batch_size // env_params['world_size'] 135 | slice_data = slice( 136 | device_batch_size * env_params['rank'], 137 | device_batch_size * (env_params['rank'] + 1)) 138 | train_data = train_data[slice_data] 139 | val_data = val_data[slice_data] 140 | test_data = test_data[slice_data] 141 | 142 | train_data = train_data.to(device) 143 | val_data = val_data.to(device) 144 | test_data = test_data.to(device) 145 | return train_data, val_data, test_data 146 | -------------------------------------------------------------------------------- /experiments/enwik8.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/enwik8 \ 13 | --nlayers 12 \ 14 | --hid-sz 512 \ 15 | --inner-hid-sz 2048 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.3 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 600 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000005 \ 30 | --adapt-span-cache \ 31 | --distributed \ 32 | --checkpoint checkpoints/enwik8.pt 33 | " 34 | 35 | 36 | echo "Training ..." 37 | # using the pytorch distributed launching 38 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 39 | 40 | 41 | echo "Evaluation ..." 42 | # use a smaller batch size to reduce tokens without context and omitted tokens. 43 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 44 | --full-eval-mode --batch-sz 8 45 | -------------------------------------------------------------------------------- /experiments/enwik8_large.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/enwik8 \ 13 | --nlayers 24 \ 14 | --hid-sz 768 \ 15 | --inner-hid-sz 4096 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.4 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 150 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000005 \ 30 | --adapt-span-cache \ 31 | --batch-split 2 \ 32 | --distributed \ 33 | --checkpoint checkpoints/enwik8_large.pt 34 | " 35 | 36 | 37 | echo "Training ..." 38 | # using the pytorch distributed launching 39 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 40 | 41 | 42 | echo "Fine-tuning ..." 43 | # train another 20k steps with a 10x smaller learning rate 44 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 45 | --lr 0.007 --niter 170 46 | 47 | 48 | echo "Evaluation ..." 49 | # use a smaller batch size to reduce tokens without context and omitted tokens. 50 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 51 | --full-eval-mode --batch-sz 8 52 | -------------------------------------------------------------------------------- /experiments/enwik8_pers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/enwik8 \ 13 | --nlayers 36 \ 14 | --hid-sz 512 \ 15 | --inner-hid-sz 1 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.4 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 200 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000001 \ 30 | --adapt-span-cache \ 31 | --pers-mem-size 2048 \ 32 | --batch-split 2 \ 33 | --distributed \ 34 | --checkpoint checkpoints/enwik8_pers.pt 35 | " 36 | 37 | 38 | echo "Training ..." 39 | # using the pytorch distributed launching 40 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 41 | 42 | 43 | echo "Fine-tuning ..." 44 | # train another 20k steps with a 10x smaller learning rate 45 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 46 | --lr 0.007 --niter 210 47 | 48 | 49 | echo "Evaluation ..." 50 | # use a smaller batch size to reduce tokens without context and omitted tokens. 51 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 52 | --full-eval-mode --batch-sz 8 53 | -------------------------------------------------------------------------------- /experiments/enwik8_pers_small.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/enwik8 \ 13 | --nlayers 18 \ 14 | --hid-sz 512 \ 15 | --inner-hid-sz 1 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.3 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 450 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000001 \ 30 | --adapt-span-cache \ 31 | --pers-mem-size 1024 \ 32 | --batch-split 2 \ 33 | --distributed \ 34 | --checkpoint checkpoints/enwik8_pers_small.pt 35 | " 36 | 37 | 38 | echo "Training ..." 39 | # using the pytorch distributed launching 40 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 41 | 42 | 43 | echo "Fine-tuning ..." 44 | # train another 20k steps with a 10x smaller learning rate 45 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 46 | --lr 0.007 --niter 480 47 | 48 | 49 | echo "Evaluation ..." 50 | # use a smaller batch size to reduce tokens without context and omitted tokens. 51 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 52 | --full-eval-mode --batch-sz 8 53 | -------------------------------------------------------------------------------- /experiments/enwik8_small.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # get the data 4 | bash get_data.sh 5 | mkdir -p checkpoints 6 | 7 | args=" 8 | --data data/enwik8 \ 9 | --nlayers 8 \ 10 | --hid-sz 256 \ 11 | --inner-hid-sz 1024 \ 12 | --nheads 4 \ 13 | --attn-span 1024 \ 14 | --block-sz 256 \ 15 | --batch-sz 64 \ 16 | --lr 0.07 \ 17 | --momentum 0 \ 18 | --dropout 0 \ 19 | --optim adagrad \ 20 | --lr-warmup 8000 \ 21 | --grad-clip 0.03 \ 22 | --niter 150 \ 23 | --nbatches 1000 \ 24 | --adapt-span \ 25 | --adapt-span-loss 0.000002 \ 26 | --adapt-span-cache 27 | --checkpoint checkpoints/enwik8_small.pt 28 | " 29 | 30 | 31 | echo "Training ..." 32 | # using the pytorch distributed launching 33 | python3 main.py $args 34 | 35 | 36 | echo "Evaluation ..." 37 | # use a smaller batch size to reduce tokens without context and omitted tokens. 38 | python3 main.py $args --full-eval-mode --batch-sz 8 39 | -------------------------------------------------------------------------------- /experiments/text8.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # get the data 4 | bash get_data.sh 5 | mkdir -p checkpoints 6 | 7 | # Change ngpus to match the number of GPUs available. 8 | # If run out of GPU memory, increase "--batch-split" argument. 9 | 10 | ngpus=8 11 | args=" 12 | --data data/text8 \ 13 | --nlayers 12 \ 14 | --hid-sz 512 \ 15 | --inner-hid-sz 2048 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.3 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 900 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000005 \ 30 | --adapt-span-cache \ 31 | --distributed \ 32 | --checkpoint checkpoints/text8.pt 33 | " 34 | 35 | 36 | echo "Training ..." 37 | # using the pytorch distributed launching 38 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 39 | 40 | 41 | echo "Evaluation ..." 42 | # use a smaller batch size to reduce tokens without context and omitted tokens. 43 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 44 | --full-eval-mode --batch-sz 8 45 | -------------------------------------------------------------------------------- /experiments/text8_large.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/text8 \ 13 | --nlayers 24 \ 14 | --hid-sz 768 \ 15 | --inner-hid-sz 4096 \ 16 | --nheads 8 \ 17 | --attn-span 8192 \ 18 | --block-sz 512 \ 19 | --batch-sz 64 \ 20 | --lr 0.07 \ 21 | --momentum 0 \ 22 | --dropout 0.4 \ 23 | --optim adagrad \ 24 | --lr-warmup 32000 \ 25 | --grad-clip 0.03 \ 26 | --niter 250 \ 27 | --nbatches 1000 \ 28 | --adapt-span \ 29 | --adapt-span-loss 0.0000005 \ 30 | --adapt-span-cache \ 31 | --batch-split 2 \ 32 | --distributed \ 33 | --checkpoint checkpoints/text8_large.pt 34 | " 35 | 36 | 37 | echo "Training ..." 38 | # using the pytorch distributed launching 39 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 40 | 41 | 42 | echo "Fine-tuning ..." 43 | # train another 20k steps with a 10x smaller learning rate 44 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 45 | --lr 0.007 --niter 270 46 | 47 | 48 | echo "Evaluation ..." 49 | # use a smaller batch size to reduce tokens without context and omitted tokens. 50 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 51 | --full-eval-mode --batch-sz 8 52 | -------------------------------------------------------------------------------- /experiments/wiki103_pers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Change ngpus to match the number of GPUs available. 4 | # If run out of GPU memory, increase "--batch-split" argument. 5 | 6 | # get the data 7 | bash get_data.sh 8 | mkdir -p checkpoints 9 | 10 | ngpus=8 11 | args=" 12 | --data data/wikitext-103 \ 13 | --nlayers 36 \ 14 | --hid-sz 512 \ 15 | --inner-hid-sz 1 \ 16 | --nheads 8 \ 17 | --attn-span 2048 \ 18 | --block-sz 256 \ 19 | --batch-sz 64 \ 20 | --lr 0.00025 \ 21 | --momentum 0 \ 22 | --dropout 0.3 \ 23 | --emb-dropout 0.1 \ 24 | --optim adam \ 25 | --lr-warmup 8000 \ 26 | --grad-clip 1 \ 27 | --niter 800 \ 28 | --nbatches 1000 \ 29 | --adapt-span \ 30 | --adapt-span-loss 0.0000005 \ 31 | --adapt-span-cache \ 32 | --pers-mem-size 2048 \ 33 | --adapt-io \ 34 | --adapt-io-tied \ 35 | --data-unit ppl \ 36 | --batch-split 2 \ 37 | --distributed \ 38 | --checkpoint checkpoints/wiki103_pers.pt 39 | " 40 | 41 | echo "Training ..." 42 | # using the pytorch distributed launching 43 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args 44 | 45 | 46 | echo "Fine-tuning ..." 47 | # train another 50k steps with a 10x smaller learning rate 48 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 49 | --lr 0.000025 --niter 850 50 | 51 | 52 | echo "Evaluation ..." 53 | # use a smaller batch size to reduce tokens without context and omitted tokens. 54 | python3 -m torch.distributed.launch --nproc_per_node=$ngpus main.py $args \ 55 | --full-eval-mode --batch-sz 8 56 | -------------------------------------------------------------------------------- /get_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ ! -d 'data/enwik8' ]]; then 4 | mkdir -p data/enwik8 5 | cd data/enwik8 6 | echo "Downloading enwik8 data ..." 7 | wget --continue http://mattmahoney.net/dc/enwik8.zip 8 | wget https://raw.githubusercontent.com/salesforce/awd-lstm-lm/master/data/enwik8/prep_enwik8.py 9 | python3 prep_enwik8.py 10 | cd ../.. 11 | fi 12 | 13 | 14 | if [[ ! -d 'data/text8' ]]; then 15 | mkdir -p data/text8 16 | cd data/text8 17 | echo "Downloading text8 data ..." 18 | wget --continue http://mattmahoney.net/dc/text8.zip 19 | wget https://raw.githubusercontent.com/kimiyoung/transformer-xl/master/prep_text8.py 20 | python prep_text8.py 21 | cd ../.. 22 | fi 23 | 24 | if [[ ! -d 'data/wikitext-103' ]]; then 25 | mkdir -p data 26 | cd data 27 | echo "Downloading wikitext-103 data ..." 28 | wget --continue https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-v1.zip 29 | unzip -q wikitext-103-v1.zip 30 | cd wikitext-103 31 | mv wiki.train.tokens train.txt 32 | mv wiki.valid.tokens valid.txt 33 | mv wiki.test.tokens test.txt 34 | cd ../.. 35 | fi 36 | -------------------------------------------------------------------------------- /get_pretrained.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | url_root="https://dl.fbaipublicfiles.com/adaptive-span" 4 | 5 | mkdir -p checkpoints 6 | cd checkpoints 7 | 8 | wget "${url_root}/enwik8.pt" 9 | wget "${url_root}/text8.pt" 10 | wget "${url_root}/enwik8_large.pt" 11 | wget "${url_root}/text8_large.pt" 12 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import math 11 | import time 12 | 13 | import torch 14 | 15 | from config import PARAMS_CONFIG 16 | from data import get_train_val_test_data 17 | from models import TransformerSeq 18 | from trainer import train_iteration, full_eval 19 | from utils import ( 20 | get_params, 21 | set_up_env, 22 | get_optimizer_and_scheduler, 23 | load_checkpoint, 24 | save_checkpoint, 25 | Logger) 26 | 27 | 28 | def launch(env_params, 29 | model_params, 30 | adapt_io_params, 31 | adapt_span_params, 32 | pers_mem_params, 33 | optim_params, 34 | data_params, 35 | trainer_params): 36 | # ENVIRONMENT (device, distributed, etc.) 37 | set_up_env(env_params) 38 | device = env_params['device'] 39 | distributed = env_params['distributed'] 40 | 41 | if distributed == False or env_params['rank'] == 0: 42 | print('model_params:\t', model_params) 43 | print('optim_params:\t', optim_params) 44 | print('data_params:\t', data_params) 45 | print('trainer_params:\t', trainer_params) 46 | print('adapt_io_params:\t', adapt_io_params) 47 | print('adapt_span_params:\t', adapt_span_params) 48 | print('pers_mem_params:\t', pers_mem_params) 49 | 50 | # DATA 51 | train_data, val_data, test_data = get_train_val_test_data( 52 | data_params=data_params, 53 | env_params=env_params, 54 | batch_size=trainer_params['batch_size'], 55 | device=device, 56 | sort_dict=adapt_io_params['adapt_io_enabled']) 57 | 58 | # MODEL 59 | model = TransformerSeq( 60 | vocab_size=data_params['vocab_size'], **model_params, 61 | adapt_io_params=adapt_io_params, 62 | adapt_span_params=adapt_span_params, 63 | pers_mem_params=pers_mem_params) 64 | if distributed: 65 | local_rank = env_params['local_rank'] 66 | model = model.to(device) 67 | model = torch.nn.parallel.DistributedDataParallel( 68 | model, device_ids=[local_rank], output_device=local_rank) 69 | else: 70 | model = torch.nn.DataParallel(model) 71 | model = model.to(device) 72 | 73 | # OPTIMIZER AND SCHEDULER 74 | optimizer, scheduler = get_optimizer_and_scheduler( 75 | model=model, optim_params=optim_params) 76 | 77 | # create logger 78 | logger = Logger(data_params['data_unit']) 79 | 80 | # resume training from last checkpoint if exists 81 | iter_init = load_checkpoint( 82 | trainer_params['checkpoint_path'], model, optimizer, scheduler, 83 | logger, distributed) 84 | 85 | if trainer_params['full_eval_mode']: 86 | # evaluate the model on test data 87 | with torch.no_grad(): 88 | loss_val = full_eval(model, optimizer, scheduler, val_data, 89 | model_params['block_size'], 90 | model_params['hidden_size']) 91 | loss_test = full_eval(model, optimizer, scheduler, test_data, 92 | model_params['block_size'], 93 | model_params['hidden_size']) 94 | if distributed: 95 | # collect results into rank0 96 | stats = torch.tensor( 97 | [loss_val, loss_test]).to(device) 98 | torch.distributed.reduce(stats, 0) 99 | if env_params['rank'] == 0: 100 | loss_val = stats[0] / env_params['world_size'] 101 | loss_test = stats[1] / env_params['world_size'] 102 | else: 103 | return 104 | 105 | if data_params['data_unit'] == 'bpc': 106 | print('val: {:.3f}bpc'.format(loss_val / math.log(2))) 107 | print('test: {:.3f}bpc'.format(loss_test / math.log(2))) 108 | else: 109 | print('val: {:.2f}ppl'.format(math.exp(loss_val))) 110 | print('test: {:.2f}ppl'.format(math.exp(loss_test))) 111 | return 112 | 113 | # position of current batch 114 | data_pos = [0] * 2 115 | # initialize caches for train and valid 116 | hid_cache = [[ 117 | torch.zeros( 118 | train_data.size(0), 119 | layer.attn.attn.get_cache_size(), 120 | model_params['hidden_size']).to(device) 121 | for layer in model.module.layers] for _ in range(2)] 122 | 123 | nb_batches_per_iter = trainer_params['nb_batches_per_iter'] 124 | for iter_no in range(iter_init, trainer_params['nb_iter']): 125 | t_sta = time.time() 126 | loss_train, data_pos[0], hid_cache[0] = train_iteration( 127 | model, optimizer, scheduler, train_data, nb_batches_per_iter, 128 | model_params['block_size'], False, data_pos[0], hid_cache[0], 129 | trainer_params['batch_split']) 130 | elapsed = 1000 * (time.time() - t_sta) / nb_batches_per_iter 131 | with torch.no_grad(): 132 | loss_val, data_pos[1], hid_cache[1] = train_iteration( 133 | model, optimizer, scheduler, val_data, nb_batches_per_iter, 134 | model_params['block_size'], True, data_pos[1], hid_cache[1], 135 | trainer_params['batch_split']) 136 | 137 | if distributed: 138 | # collect results into rank0 139 | stats = torch.tensor( 140 | [loss_train, loss_val]).to(device) 141 | torch.distributed.reduce(stats, 0) 142 | if env_params['rank'] == 0: 143 | loss_train = stats[0] / env_params['world_size'] 144 | loss_val = stats[1] / env_params['world_size'] 145 | else: 146 | continue 147 | 148 | logger.log_iter(iter_no, nb_batches_per_iter, loss_train, 149 | loss_val, elapsed, model) 150 | save_checkpoint(trainer_params['checkpoint_path'], 151 | iter_no, model, optimizer, scheduler, logger) 152 | 153 | 154 | if __name__ == '__main__': 155 | launch(**get_params(params_config=PARAMS_CONFIG)) 156 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import math 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | 16 | from adaptive_span import AdaptiveSpan 17 | from persistent_memory import PersistentMemory 18 | from adaptive_io import build_adaptive_io, compute_dummy_loss 19 | 20 | # Size notations: 21 | # B = batch_size, H = hidden_size, M = block_size, L = attn_span 22 | 23 | 24 | def _skew(X, pad_value): 25 | """shift every row 1 step to right""" 26 | # X = B x M x L 27 | B, M, L = X.size() 28 | X = F.pad(X, (0, M + 1), value=pad_value) # B x M x (L+M+1) 29 | X = X.view(B, -1) # B x ML+MM+M 30 | X = X[:, :-M] # B x ML+MM 31 | X = X.view(B, M, M + L) # B x M x L+M 32 | return X 33 | 34 | 35 | def _unskew(X): 36 | """reverse _skew operation""" 37 | # X = B x M x L+M 38 | B, M, L = X.size() 39 | L -= M 40 | X = X.view(B, -1) # B x ML+MM 41 | X = F.pad(X, (0, M)) # B x ML+MM+M 42 | X = X.view(B, M, M + L + 1) # B x M x L+M+1 43 | X = X[:, :, :L] # B x M x L 44 | return X 45 | 46 | 47 | class SeqAttention(nn.Module): 48 | """Sequential self-attention layer. 49 | Each token will attend to its previous fixed number of steps. 50 | Note that attention doesn't include the current step itself. 51 | """ 52 | def __init__(self, hidden_size, nb_heads, attn_span, 53 | dropout, adapt_span_params, pers_mem_params, **kargs): 54 | nn.Module.__init__(self) 55 | self.dropout = nn.Dropout(dropout) 56 | self.hidden_size = hidden_size # size of a single head 57 | self.attn_span = attn_span 58 | self.adapt_span_enabled = adapt_span_params['adapt_span_enabled'] 59 | if self.adapt_span_enabled: 60 | self.adaptive_span = AdaptiveSpan(attn_span=attn_span, nb_heads=nb_heads, 61 | **adapt_span_params, **kargs) 62 | 63 | self.persistent_memory = None 64 | if pers_mem_params['pers_mem_size'] > 0: 65 | self.persistent_memory = PersistentMemory( 66 | pers_mem_params['pers_mem_size'], nb_heads, hidden_size, dropout) 67 | if self.adapt_span_enabled: 68 | self.persistent_memory.adaptive_span = self.adaptive_span 69 | 70 | def forward(self, query, key, value, key_pe): 71 | # query size = B x M x H 72 | # key, value sizes = B x (M+L) x H 73 | 74 | if self.adapt_span_enabled: 75 | # [optional] trim out memory to reduce unnecessary computation 76 | key, value, key_pe = self.adaptive_span.trim_memory( 77 | query, key, value, key_pe) 78 | 79 | # compute attention from context 80 | # B x M (dest) x (M+L) (src) 81 | attn_cont = torch.matmul(query, key.transpose(-1, -2)) 82 | attn_cont = _unskew(attn_cont) # B x M x L 83 | 84 | # compute the effect of position embedding 85 | attn_pos = torch.matmul(query, key_pe) # B x M x L_pos 86 | attn = attn_cont + attn_pos 87 | 88 | if self.persistent_memory is not None: 89 | attn, pers_mem_out = self.persistent_memory(query, attn) 90 | else: 91 | attn = attn / math.sqrt(self.hidden_size) # B x M X L_pos 92 | attn = F.softmax(attn, dim=-1) 93 | 94 | if self.adapt_span_enabled: 95 | # trim attention lengths according to the learned span 96 | attn = self.adaptive_span(attn) 97 | 98 | attn = self.dropout(attn) # B x M X L_pos 99 | 100 | attn_cont = _skew(attn, 0) # B x M X (L+M) 101 | out = torch.matmul(attn_cont, value) # B x M x H 102 | 103 | if self.persistent_memory is not None: 104 | out = out + pers_mem_out 105 | 106 | return out 107 | 108 | def get_cache_size(self): 109 | if self.adapt_span_enabled: 110 | return self.adaptive_span.get_cache_size() 111 | else: 112 | return self.attn_span 113 | 114 | 115 | class MultiHeadSeqAttention(nn.Module): 116 | def __init__(self, hidden_size, nb_heads, **kargs): 117 | nn.Module.__init__(self) 118 | assert hidden_size % nb_heads == 0 119 | self.nb_heads = nb_heads 120 | self.head_dim = hidden_size // nb_heads 121 | self.attn = SeqAttention( 122 | hidden_size=self.head_dim, nb_heads=nb_heads, **kargs) 123 | self.proj_query = nn.Linear(hidden_size, hidden_size, bias=False) 124 | self.proj_out = nn.Linear(hidden_size, hidden_size, bias=False) 125 | self.proj_val = nn.Linear(hidden_size, hidden_size, bias=False) 126 | self.proj_key = nn.Linear(hidden_size, hidden_size, bias=False) 127 | 128 | def head_reshape(self, x): 129 | K = self.nb_heads 130 | D = self.head_dim 131 | x = x.view(x.size()[:-1] + (K, D)) # B x (M+L) x K x D 132 | x = x.transpose(1, 2).contiguous() # B x K x (M+L) x D 133 | x = x.view(-1, x.size(-2), x.size(-1)) # B_K x (M+L) x D 134 | return x 135 | 136 | def forward(self, query, key, value, key_pe): 137 | B = query.size(0) 138 | K = self.nb_heads 139 | D = self.head_dim 140 | M = query.size(1) 141 | 142 | query = self.proj_query(query) 143 | query = self.head_reshape(query) 144 | value = self.proj_val(value) 145 | value = self.head_reshape(value) 146 | key = self.proj_key(key) 147 | key = self.head_reshape(key) 148 | 149 | out = self.attn(query, key, value, key_pe) # B_K x M x D 150 | out = out.view(B, K, M, D) # B x K x M x D 151 | out = out.transpose(1, 2).contiguous() # B x M x K x D 152 | out = out.view(B, M, -1) # B x M x K_D 153 | out = self.proj_out(out) 154 | return out 155 | 156 | 157 | class FeedForwardLayer(nn.Module): 158 | def __init__(self, hidden_size, inner_hidden_size, dropout, **kargs): 159 | nn.Module.__init__(self) 160 | self.fc1 = nn.Linear(hidden_size, inner_hidden_size) 161 | self.fc2 = nn.Linear(inner_hidden_size, hidden_size) 162 | self.dropout = nn.Dropout(dropout) 163 | 164 | def forward(self, h): 165 | h1 = F.relu(self.fc1(h)) 166 | h1 = self.dropout(h1) 167 | h2 = self.fc2(h1) 168 | return h2 169 | 170 | 171 | class TransformerSeqLayer(nn.Module): 172 | def __init__(self, hidden_size, **kargs): 173 | nn.Module.__init__(self) 174 | self.attn = MultiHeadSeqAttention(hidden_size=hidden_size, **kargs) 175 | self.norm1 = nn.LayerNorm(hidden_size) 176 | if kargs['pers_mem_params']['pers_mem_size'] > 0: 177 | # replacing FF with persistent memory 178 | self.ff = None 179 | else: 180 | self.ff = FeedForwardLayer(hidden_size=hidden_size, **kargs) 181 | self.norm2 = nn.LayerNorm(hidden_size) 182 | 183 | def forward(self, h, h_cache, key_pe): 184 | # h = B x M x H 185 | # h_cache = B x L x H 186 | h_all = torch.cat([h_cache, h], dim=1) # B x (M+L) x H 187 | attn_out = self.attn(h, h_all, h_all, key_pe) 188 | h = self.norm1(h + attn_out) # B x M x H 189 | if self.ff is not None: 190 | ff_out = self.ff(h) 191 | out = self.norm2(h + ff_out) # B x M x H 192 | else: 193 | out = h 194 | return out 195 | 196 | 197 | class TransformerSeq(nn.Module): 198 | def __init__(self, vocab_size, hidden_size, nb_heads, nb_layers, 199 | attn_span, emb_dropout, adapt_io_params, **kargs): 200 | nn.Module.__init__(self) 201 | # token embeddings 202 | self.adapt_io = adapt_io_params['adapt_io_enabled'] 203 | if self.adapt_io: 204 | self.in_emb, self.out_emb = build_adaptive_io( 205 | vocab_size, hidden_size, **adapt_io_params) 206 | else: 207 | self.in_emb = nn.Embedding(vocab_size, hidden_size) 208 | self.out_emb = nn.Linear(hidden_size, vocab_size) 209 | if emb_dropout > 0: 210 | self.emb_dropout = nn.Dropout(emb_dropout) 211 | else: 212 | self.emb_dropout = None 213 | # position embeddings 214 | self.key_pe = nn.Parameter( 215 | torch.randn(1, hidden_size // nb_heads, attn_span)) 216 | 217 | self.layers = nn.ModuleList() 218 | self.layers.extend( 219 | TransformerSeqLayer( 220 | hidden_size=hidden_size, nb_heads=nb_heads, 221 | attn_span=attn_span, **kargs) 222 | for _ in range(nb_layers)) 223 | 224 | def forward(self, x, h_cache, target=None): 225 | # x size = B x M 226 | block_size = x.size(1) 227 | h = self.in_emb(x) # B x M x H 228 | if self.emb_dropout is not None: 229 | h = self.emb_dropout(h) 230 | 231 | h_cache_next = [] 232 | for l, layer in enumerate(self.layers): 233 | cache_size = layer.attn.attn.get_cache_size() 234 | if cache_size > block_size: 235 | h_cache_next_l = torch.cat( 236 | [h_cache[l][:, -cache_size + block_size:, :], h], 237 | dim=1).detach() 238 | else: 239 | h_cache_next_l = h[:, -cache_size:, :].detach() 240 | h_cache_next.append(h_cache_next_l) 241 | h = layer(h, h_cache[l], self.key_pe) # B x M x H 242 | 243 | if self.emb_dropout is not None: 244 | h = self.emb_dropout(h) 245 | if self.adapt_io: 246 | # loss is computed here 247 | out = self.out_emb(h, target) 248 | dummy_loss = compute_dummy_loss(self.in_emb, self.out_emb) 249 | else: 250 | out = F.log_softmax(self.out_emb(h), dim=-1) 251 | dummy_loss = None 252 | 253 | return out, h_cache_next, dummy_loss 254 | -------------------------------------------------------------------------------- /persistent_memory.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | from argparse import Namespace 11 | import math 12 | import random 13 | import torch 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | 17 | 18 | class PersistentMemory(nn.Module): 19 | def __init__(self, size, nb_heads, head_dim, dropout): 20 | super(PersistentMemory, self).__init__() 21 | self.size = size 22 | self.nb_heads = nb_heads 23 | self.head_dim = head_dim 24 | # different heads have different vectors 25 | self.key = nn.Parameter(torch.randn(self.nb_heads, self.head_dim, self.size) / math.sqrt(self.head_dim)) 26 | self.val = nn.Parameter(torch.randn(self.nb_heads, self.size, self.head_dim) / math.sqrt(self.size)) 27 | self.dropout = nn.Dropout(dropout) 28 | self.adaptive_span = None 29 | 30 | def forward(self, query, attn): 31 | key = self.key.unsqueeze(0) 32 | val = self.val.unsqueeze(0) 33 | 34 | query = query.view((-1, self.nb_heads) + query.size()[1:]) 35 | attn_pers = torch.matmul(query, key * math.sqrt(self.head_dim)) 36 | attn_pers = attn_pers.view((-1,) + attn_pers.size()[2:]) 37 | 38 | # compute softmax jointly 39 | attn = torch.cat((attn, attn_pers), dim=-1) 40 | attn = attn / math.sqrt(self.head_dim) # B x M X L_total 41 | attn = F.softmax(attn, dim=-1) 42 | attn_pers = attn[:, :, -key.size(-1):] 43 | attn = attn[:, :, :-key.size(-1)] # B x M X L 44 | 45 | # adapt attention span 46 | if self.adaptive_span is not None: 47 | attn = self.adaptive_span(attn, normalize=False) 48 | # normalize the sum jointly! 49 | attn = torch.cat((attn, attn_pers), dim=-1) 50 | attn = attn / (attn.sum(-1, keepdim=True) + 1e-8) 51 | attn_pers = attn[:, :, -key.size(-1):] 52 | attn = attn[:, :, :-key.size(-1)] # B x M X L 53 | 54 | attn_pers = self.dropout(attn_pers) # B x M X L 55 | 56 | attn_pers = attn_pers.view((-1, self.nb_heads) + attn_pers.size()[1:]) 57 | out = torch.matmul(attn_pers, val * math.sqrt(self.size)) 58 | out = out.view((-1,) + out.size()[2:]) 59 | return attn, out 60 | -------------------------------------------------------------------------------- /trainer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import math 11 | import random 12 | 13 | import torch 14 | 15 | 16 | 17 | def _train_step(model, X, Y, h_cache, eval_only, loss_div=1): 18 | """Single training step.""" 19 | 20 | out, h_cache, dummy_loss = model(X, h_cache, target=Y) 21 | if model.module.adapt_io: 22 | loss = out.mean() + dummy_loss.sum() 23 | else: 24 | out = out.view(-1, out.size(-1)) 25 | loss = torch.nn.functional.nll_loss(out, Y.view(-1)) 26 | loss_value = loss.item() / loss_div 27 | 28 | if not eval_only: 29 | # loss term from adaptive-span 30 | if model.module.layers[0].attn.attn.adapt_span_enabled: 31 | loss += sum(layer.attn.attn.adaptive_span.get_loss() 32 | for layer in model.module.layers) 33 | 34 | (loss / loss_div).backward() 35 | 36 | return loss_value, h_cache 37 | 38 | 39 | def _train_batch(model, optimizer, scheduler, X, Y, h_cache, 40 | eval_only, batch_split): 41 | """Train on a batch.""" 42 | 43 | optimizer.zero_grad() 44 | 45 | if batch_split == 1: 46 | # process a batch in a single step (default behaviour) 47 | loss_value, h_cache = _train_step(model, X, Y, h_cache, eval_only) 48 | else: 49 | # split a batch into multiple pieces that each can fit in memory 50 | assert X.size(0) % batch_split == 0 51 | split_size = X.size(0) // batch_split 52 | loss_value = 0 53 | h_cache_list = [] 54 | for split_ind in range(batch_split): 55 | split_slice = slice(split_ind*split_size, (split_ind+1)*split_size) 56 | split_h_cache = [h[split_slice,:,:] for h in h_cache] 57 | split_loss_value, split_h_cache = _train_step( 58 | model, X[split_slice,:], Y[split_slice], 59 | split_h_cache, eval_only, batch_split) 60 | loss_value += split_loss_value 61 | h_cache_list.append(split_h_cache) 62 | h_cache = [ 63 | torch.cat( 64 | [h_cache_list[i][l] for i in range(batch_split)] 65 | , dim=0) for l in range(len(h_cache))] 66 | 67 | if not eval_only: 68 | if scheduler is not None: 69 | scheduler.step() 70 | if optimizer.grad_clip > 0: 71 | torch.nn.utils.clip_grad_norm_( 72 | model.parameters(), optimizer.grad_clip) 73 | optimizer.step() 74 | 75 | # make sure span parameters are in a correct range 76 | if model.module.layers[0].attn.attn.adapt_span_enabled: 77 | for layer in model.module.layers: 78 | layer.attn.attn.adaptive_span.clamp_param() 79 | 80 | return loss_value, h_cache 81 | 82 | 83 | def train_iteration(model, optimizer, scheduler, data, nb_batches_per_iter, 84 | block_size, eval_only, train_pos, h_cache, batch_split): 85 | """Single training iteration.""" 86 | if eval_only: 87 | model.eval() 88 | else: 89 | model.train() 90 | 91 | nb_batches_per_iter_max = nb_batches_per_iter 92 | if eval_only: 93 | # eval on fewer batches during training for speed-up 94 | nb_batches_per_iter_max = max(1, nb_batches_per_iter // 10) 95 | nb_batches_per_iter_max = min(nb_batches_per_iter_max, 96 | math.ceil(data.size(1) / block_size)) 97 | 98 | loss_all = 0 99 | actual_nb_batches_per_iter = 0 100 | for _ in range(nb_batches_per_iter_max): 101 | actual_nb_batches_per_iter += 1 102 | X = data[:, train_pos: train_pos + block_size].contiguous() 103 | Y = data[:, train_pos + 1: train_pos + block_size + 1].contiguous() 104 | 105 | loss, h_cache = _train_batch( 106 | model=model, 107 | optimizer=optimizer, 108 | scheduler=scheduler, 109 | X=X, Y=Y, 110 | h_cache=h_cache, 111 | eval_only=eval_only, 112 | batch_split=batch_split) 113 | loss_all += loss 114 | train_pos += block_size 115 | if train_pos >= data.size(1) - block_size: 116 | # reached the end. randomize the offset to reduce overfitting 117 | train_pos = random.randrange(block_size) 118 | # reset the cache 119 | for h in h_cache: 120 | h.fill_(0) 121 | 122 | loss_all = loss_all / actual_nb_batches_per_iter 123 | return loss_all, train_pos, h_cache 124 | 125 | 126 | # do full evaluation 127 | def full_eval(model, optimizer, scheduler, data, block_size, hidden_size): 128 | model.eval() 129 | train_pos = 0 130 | nb_batches_per_iter_max = math.ceil(data.size(1) / block_size) 131 | h_cache = [ 132 | torch.zeros( 133 | data.size(0), 134 | layer.attn.attn.get_cache_size(), 135 | hidden_size).to(data.device) 136 | for layer in model.module.layers] 137 | 138 | loss_all = 0 139 | actual_nb_batches_per_iter = 0 140 | for _ in range(nb_batches_per_iter_max): 141 | actual_nb_batches_per_iter += 1 142 | X = data[:, train_pos: train_pos + block_size].contiguous() 143 | Y = data[:, train_pos + 1: train_pos + block_size + 1].contiguous() 144 | 145 | loss, h_cache = _train_batch( 146 | model=model, 147 | optimizer=optimizer, 148 | scheduler=scheduler, 149 | X=X, Y=Y, 150 | h_cache=h_cache, 151 | eval_only=True, 152 | batch_split=1) 153 | loss_all += loss 154 | train_pos += block_size 155 | if train_pos >= data.size(1) - block_size: 156 | # Skip the remaining tokens as it can't make a whole block. 157 | # An effect on performance should be negligable for a large data. 158 | break 159 | 160 | loss_all = loss_all / actual_nb_batches_per_iter 161 | return loss_all 162 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | #!/usr/bin/env python3 9 | 10 | import os 11 | import math 12 | import argparse 13 | 14 | import torch 15 | from adagrad_with_grad_clip import AdagradWithGradClip 16 | 17 | 18 | def _parse_args(params_config, args): 19 | parser = argparse.ArgumentParser() 20 | for params_category in params_config: # e.g., 'model_params' 21 | for param_flag, param_config in params_config[params_category].items(): 22 | # e.g., param_flag = '--block-sz' 23 | parser.add_argument(param_flag, **param_config) 24 | return parser.parse_args(args) 25 | 26 | 27 | def get_params(params_config, args=None): 28 | namespace = _parse_args(params_config, args) 29 | return { 30 | params_category: { 31 | param_config['dest']: 32 | namespace.__getattribute__(param_config['dest']) 33 | for param_config in params_config[params_category].values() 34 | } 35 | for params_category in params_config 36 | } 37 | 38 | 39 | ############################################################################## 40 | # ENVIRONMENT 41 | ############################################################################## 42 | 43 | def _torch_distributed_init_process_group(local_rank): 44 | torch.distributed.init_process_group( 45 | backend='nccl', 46 | init_method='env://' 47 | ) 48 | rank = torch.distributed.get_rank() 49 | world_size = torch.distributed.get_world_size() 50 | print('my rank={} local_rank={}'.format(rank, local_rank)) 51 | torch.cuda.set_device(local_rank) 52 | return { 53 | 'rank': rank, 54 | 'world_size': world_size, 55 | } 56 | 57 | def set_up_env(env_params): 58 | assert torch.cuda.is_available() 59 | if env_params['distributed']: 60 | env_params.update( 61 | _torch_distributed_init_process_group( 62 | local_rank=env_params['local_rank'])) 63 | env_params['device'] = torch.device('cuda') 64 | 65 | 66 | ############################################################################## 67 | # OPTIMIZER AND SCHEDULER 68 | ############################################################################## 69 | 70 | def _get_grad_requiring_params(model): 71 | nb_parameters = 0 72 | grad_requiring_params = [] 73 | for param in model.parameters(): 74 | if param.requires_grad: 75 | nb_parameters += param.numel() 76 | grad_requiring_params.append(param) 77 | print('nb_parameters={:.2f}M'.format(nb_parameters / 1e6)) 78 | return grad_requiring_params 79 | 80 | 81 | def _get_optimizer(model, 82 | optim, 83 | lr: float, 84 | momentum: float, 85 | grad_clip: float): 86 | if optim == 'sgd': 87 | optimizer = torch.optim.SGD(_get_grad_requiring_params(model), 88 | lr=lr, 89 | momentum=momentum) 90 | optimizer.grad_clip = grad_clip 91 | return optimizer 92 | elif optim == 'adagrad': 93 | optimizer = AdagradWithGradClip(_get_grad_requiring_params(model), 94 | lr=lr, 95 | grad_clip=grad_clip) 96 | optimizer.grad_clip = 0 # done internally 97 | return optimizer 98 | elif optim == 'adam': 99 | optimizer = torch.optim.Adam(_get_grad_requiring_params(model), 100 | lr=lr) 101 | optimizer.grad_clip = grad_clip 102 | return optimizer 103 | else: 104 | raise RuntimeError("wrong type of optimizer " 105 | "- must be 'sgd', 'adagrad' or 'adam'") 106 | 107 | 108 | def _get_scheduler(optimizer, lr_warmup): 109 | if lr_warmup > 0: 110 | return torch.optim.lr_scheduler.LambdaLR( 111 | optimizer, lambda ep: min(1, ep / lr_warmup)) 112 | return None 113 | 114 | 115 | def get_optimizer_and_scheduler(model, optim_params): 116 | optimizer = _get_optimizer(model=model, 117 | optim=optim_params['optim'], 118 | lr=optim_params['lr'], 119 | momentum=optim_params['momentum'], 120 | grad_clip=optim_params['grad_clip']) 121 | scheduler = _get_scheduler(optimizer=optimizer, 122 | lr_warmup=optim_params['lr_warmup']) 123 | return optimizer, scheduler 124 | 125 | 126 | ############################################################################## 127 | # CHECKPOINT 128 | ############################################################################## 129 | 130 | def _load_checkpoint(checkpoint_path, model, optimizer, scheduler, logger, 131 | distributed): 132 | print('loading from a checkpoint at {}'.format(checkpoint_path)) 133 | if distributed: 134 | # the model is saved from gpu0 so we need to map it to CPU first 135 | checkpoint_state = torch.load( 136 | checkpoint_path, map_location=lambda storage, loc: storage) 137 | else: 138 | checkpoint_state = torch.load(checkpoint_path) 139 | iter_init = checkpoint_state['iter_no'] + 1 # next iteration 140 | model.load_state_dict(checkpoint_state['model']) 141 | optimizer.load_state_dict(checkpoint_state['optimizer']) 142 | logger.load_state_dict(checkpoint_state['logger']) 143 | if 'scheduler_iter' in checkpoint_state: 144 | # we only need the step count 145 | scheduler.step(checkpoint_state['scheduler_iter']) 146 | return iter_init 147 | 148 | 149 | def load_checkpoint(checkpoint_path, model, optimizer, scheduler, logger, 150 | distributed): 151 | if checkpoint_path and os.path.exists(checkpoint_path): 152 | return _load_checkpoint(checkpoint_path=checkpoint_path, 153 | model=model, 154 | optimizer=optimizer, 155 | scheduler=scheduler, 156 | logger=logger, 157 | distributed=distributed) 158 | return 0 159 | 160 | 161 | def save_checkpoint(checkpoint_path, iter_no, model, 162 | optimizer, scheduler, logger): 163 | if checkpoint_path: 164 | checkpoint_state = { 165 | 'iter_no': iter_no, # last completed iteration 166 | 'model': model.state_dict(), 167 | 'logger': logger.state_dict(), 168 | 'optimizer': optimizer.state_dict(), 169 | } 170 | if scheduler is not None: 171 | checkpoint_state['scheduler_iter'] = scheduler.last_epoch 172 | torch.save(checkpoint_state, checkpoint_path) 173 | 174 | 175 | ############################################################################## 176 | # LOGGER 177 | ############################################################################## 178 | 179 | class Logger: 180 | def __init__(self, data_unit): 181 | self.data_unit = data_unit 182 | self._state_dict = dict() 183 | 184 | def load_state_dict(self, state_dict): 185 | self._state_dict = state_dict 186 | 187 | def state_dict(self): 188 | return self._state_dict 189 | 190 | def _log(self, title, value): 191 | if title not in self._state_dict: 192 | self._state_dict[title] = [] 193 | self._state_dict[title].append(value) 194 | 195 | def log_iter(self, iter_no, nb_batches_per_iter, loss_train, loss_val, 196 | elapsed, model): 197 | step = (iter_no + 1) * nb_batches_per_iter 198 | self._log(title='step', value=step) 199 | msg = 'steps: {}'.format(step) 200 | if self.data_unit == 'bpc': 201 | train_bpc = float(loss_train / math.log(2)) 202 | val_bpc = float(loss_val / math.log(2)) 203 | msg += '\ttrain: {:.3f}bpc\tval: {:.3f}bpc'.format(train_bpc, val_bpc) 204 | self._log(title='train_bpc', value=train_bpc) 205 | self._log(title='val_bpc', value=val_bpc) 206 | else: 207 | train_ppl = math.exp(loss_train) 208 | val_ppl = math.exp(loss_val) 209 | msg += '\ttrain: {:.2f}ppl\tval: {:.2f}ppl'.format(train_ppl, val_ppl) 210 | self._log(title='train_ppl', value=train_ppl) 211 | self._log(title='val_ppl', value=val_ppl) 212 | msg += '\tms/batch: {:.1f}'.format(elapsed) 213 | 214 | if model.module.layers[0].attn.attn.adapt_span_enabled: 215 | avg_spans = [] 216 | max_spans = [] 217 | for layer in model.module.layers: 218 | avg_spans.append( 219 | layer.attn.attn.adaptive_span.get_current_avg_span()) 220 | max_spans.append( 221 | layer.attn.attn.adaptive_span.get_current_max_span()) 222 | span_avg = float(sum(avg_spans)) / len(avg_spans) 223 | span_max = float(max(max_spans)) 224 | self._log('span_avg', span_avg) 225 | self._log('span_max', span_max) 226 | msg += "\tspan_avg: {:.0f}\tspan_max: {:.0f}".format(span_avg, span_max) 227 | 228 | print(msg) 229 | --------------------------------------------------------------------------------