187Matt commited on
Commit
4a2440b
1 Parent(s): 9f6b6b2
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. bert-master/bert-master.gitignore +116 -0
  2. bert-master/bert-master/CONTRIBUTING.md +31 -0
  3. bert-master/bert-master/LICENSE +202 -0
  4. bert-master/bert-master/README.md +1117 -0
  5. bert-master/bert-master/__init__.py +15 -0
  6. bert-master/bert-master/create_pretraining_data.py +469 -0
  7. bert-master/bert-master/extract_features.py +419 -0
  8. bert-master/bert-master/modeling.py +986 -0
  9. bert-master/bert-master/modeling_test.py +277 -0
  10. bert-master/bert-master/multilingual.md +303 -0
  11. bert-master/bert-master/optimization.py +174 -0
  12. bert-master/bert-master/optimization_test.py +48 -0
  13. bert-master/bert-master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb +1231 -0
  14. bert-master/bert-master/requirements.txt +2 -0
  15. bert-master/bert-master/run_classifier.py +981 -0
  16. bert-master/bert-master/run_classifier_with_tfhub.py +314 -0
  17. bert-master/bert-master/run_pretraining.py +493 -0
  18. bert-master/bert-master/run_squad.py +1283 -0
  19. bert-master/bert-master/sample_text.txt +33 -0
  20. bert-master/bert-master/tokenization.py +399 -0
  21. bert-master/bert-master/tokenization_test.py +137 -0
  22. dark-bert-master/dark-bert-master/LICENSE +201 -0
  23. dark-bert-master/dark-bert-master/README.md +14 -0
  24. dark-bert-master/dark-bert-master/darkbert.py +151 -0
  25. dark-bert-master/dark-bert-master/requirements.txt +0 -0
  26. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master.gitignore +125 -0
  27. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/.circleci/config.yml +29 -0
  28. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/.github/stale.yml +17 -0
  29. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/LICENSE +202 -0
  30. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/MANIFEST.in +1 -0
  31. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/README.md +30 -0
  32. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docker/Dockerfile +7 -0
  33. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_constant_schedule.png +0 -0
  34. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_hard_restarts_schedule.png +0 -0
  35. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_schedule.png +0 -0
  36. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_warm_restarts_schedule.png +0 -0
  37. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_linear_schedule.png +0 -0
  38. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/extract_features.py +297 -0
  39. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/README.md +64 -0
  40. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/finetune_on_pregenerated.py +333 -0
  41. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/pregenerate_training_data.py +302 -0
  42. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/simple_lm_finetuning.py +642 -0
  43. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_classifier.py +1047 -0
  44. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_gpt2.py +133 -0
  45. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_openai_gpt.py +274 -0
  46. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_squad.py +1098 -0
  47. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_swag.py +551 -0
  48. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_transfo_xl.py +153 -0
  49. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/hubconf.py +187 -0
  50. dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb +0 -0
bert-master/bert-master.gitignore ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initially taken from Github's Python gitignore file
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+
62
+ # Flask stuff:
63
+ instance/
64
+ .webassets-cache
65
+
66
+ # Scrapy stuff:
67
+ .scrapy
68
+
69
+ # Sphinx documentation
70
+ docs/_build/
71
+
72
+ # PyBuilder
73
+ target/
74
+
75
+ # Jupyter Notebook
76
+ .ipynb_checkpoints
77
+
78
+ # IPython
79
+ profile_default/
80
+ ipython_config.py
81
+
82
+ # pyenv
83
+ .python-version
84
+
85
+ # celery beat schedule file
86
+ celerybeat-schedule
87
+
88
+ # SageMath parsed files
89
+ *.sage.py
90
+
91
+ # Environments
92
+ .env
93
+ .venv
94
+ env/
95
+ venv/
96
+ ENV/
97
+ env.bak/
98
+ venv.bak/
99
+
100
+ # Spyder project settings
101
+ .spyderproject
102
+ .spyproject
103
+
104
+ # Rope project settings
105
+ .ropeproject
106
+
107
+ # mkdocs documentation
108
+ /site
109
+
110
+ # mypy
111
+ .mypy_cache/
112
+ .dmypy.json
113
+ dmypy.json
114
+
115
+ # Pyre type checker
116
+ .pyre/
bert-master/bert-master/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to Contribute
2
+
3
+ BERT needs to maintain permanent compatibility with the pre-trained model files,
4
+ so we do not plan to make any major changes to this library (other than what was
5
+ promised in the README). However, we can accept small patches related to
6
+ re-factoring and documentation. To submit contributes, there are just a few
7
+ small guidelines you need to follow.
8
+
9
+ ## Contributor License Agreement
10
+
11
+ Contributions to this project must be accompanied by a Contributor License
12
+ Agreement. You (or your employer) retain the copyright to your contribution;
13
+ this simply gives us permission to use and redistribute your contributions as
14
+ part of the project. Head over to <https://cla.developers.google.com/> to see
15
+ your current agreements on file or to sign a new one.
16
+
17
+ You generally only need to submit a CLA once, so if you've already submitted one
18
+ (even if it was for a different project), you probably don't need to do it
19
+ again.
20
+
21
+ ## Code reviews
22
+
23
+ All submissions, including submissions by project members, require review. We
24
+ use GitHub pull requests for this purpose. Consult
25
+ [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
26
+ information on using pull requests.
27
+
28
+ ## Community Guidelines
29
+
30
+ This project follows
31
+ [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/).
bert-master/bert-master/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
bert-master/bert-master/README.md ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BERT
2
+
3
+ **\*\*\*\*\* New March 11th, 2020: Smaller BERT Models \*\*\*\*\***
4
+
5
+ This is a release of 24 smaller BERT models (English only, uncased, trained with WordPiece masking) referenced in [Well-Read Students Learn Better: On the Importance of Pre-training Compact Models](https://arxiv.org/abs/1908.08962).
6
+
7
+ We have shown that the standard BERT recipe (including model architecture and training objective) is effective on a wide range of model sizes, beyond BERT-Base and BERT-Large. The smaller BERT models are intended for environments with restricted computational resources. They can be fine-tuned in the same manner as the original BERT models. However, they are most effective in the context of knowledge distillation, where the fine-tuning labels are produced by a larger and more accurate teacher.
8
+
9
+ Our goal is to enable research in institutions with fewer computational resources and encourage the community to seek directions of innovation alternative to increasing model capacity.
10
+
11
+ You can download all 24 from [here][all], or individually from the table below:
12
+
13
+ | |H=128|H=256|H=512|H=768|
14
+ |---|:---:|:---:|:---:|:---:|
15
+ | **L=2** |[**2/128 (BERT-Tiny)**][2_128]|[2/256][2_256]|[2/512][2_512]|[2/768][2_768]|
16
+ | **L=4** |[4/128][4_128]|[**4/256 (BERT-Mini)**][4_256]|[**4/512 (BERT-Small)**][4_512]|[4/768][4_768]|
17
+ | **L=6** |[6/128][6_128]|[6/256][6_256]|[6/512][6_512]|[6/768][6_768]|
18
+ | **L=8** |[8/128][8_128]|[8/256][8_256]|[**8/512 (BERT-Medium)**][8_512]|[8/768][8_768]|
19
+ | **L=10** |[10/128][10_128]|[10/256][10_256]|[10/512][10_512]|[10/768][10_768]|
20
+ | **L=12** |[12/128][12_128]|[12/256][12_256]|[12/512][12_512]|[**12/768 (BERT-Base)**][12_768]|
21
+
22
+ Note that the BERT-Base model in this release is included for completeness only; it was re-trained under the same regime as the original model.
23
+
24
+ Here are the corresponding GLUE scores on the test set:
25
+
26
+ |Model|Score|CoLA|SST-2|MRPC|STS-B|QQP|MNLI-m|MNLI-mm|QNLI(v2)|RTE|WNLI|AX|
27
+ |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
28
+ |BERT-Tiny|64.2|0.0|83.2|81.1/71.1|74.3/73.6|62.2/83.4|70.2|70.3|81.5|57.2|62.3|21.0|
29
+ |BERT-Mini|65.8|0.0|85.9|81.1/71.8|75.4/73.3|66.4/86.2|74.8|74.3|84.1|57.9|62.3|26.1|
30
+ |BERT-Small|71.2|27.8|89.7|83.4/76.2|78.8/77.0|68.1/87.0|77.6|77.0|86.4|61.8|62.3|28.6|
31
+ |BERT-Medium|73.5|38.0|89.6|86.6/81.6|80.4/78.4|69.6/87.9|80.0|79.1|87.7|62.2|62.3|30.5|
32
+
33
+ For each task, we selected the best fine-tuning hyperparameters from the lists below, and trained for 4 epochs:
34
+ - batch sizes: 8, 16, 32, 64, 128
35
+ - learning rates: 3e-4, 1e-4, 5e-5, 3e-5
36
+
37
+ If you use these models, please cite the following paper:
38
+
39
+ ```
40
+ @article{turc2019,
41
+ title={Well-Read Students Learn Better: On the Importance of Pre-training Compact Models},
42
+ author={Turc, Iulia and Chang, Ming-Wei and Lee, Kenton and Toutanova, Kristina},
43
+ journal={arXiv preprint arXiv:1908.08962v2 },
44
+ year={2019}
45
+ }
46
+ ```
47
+
48
+ [2_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-2_H-128_A-2.zip
49
+ [2_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-2_H-256_A-4.zip
50
+ [2_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-2_H-512_A-8.zip
51
+ [2_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-2_H-768_A-12.zip
52
+ [4_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-4_H-128_A-2.zip
53
+ [4_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-4_H-256_A-4.zip
54
+ [4_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-4_H-512_A-8.zip
55
+ [4_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-4_H-768_A-12.zip
56
+ [6_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-6_H-128_A-2.zip
57
+ [6_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-6_H-256_A-4.zip
58
+ [6_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-6_H-512_A-8.zip
59
+ [6_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-6_H-768_A-12.zip
60
+ [8_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-8_H-128_A-2.zip
61
+ [8_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-8_H-256_A-4.zip
62
+ [8_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-8_H-512_A-8.zip
63
+ [8_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-8_H-768_A-12.zip
64
+ [10_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-10_H-128_A-2.zip
65
+ [10_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-10_H-256_A-4.zip
66
+ [10_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-10_H-512_A-8.zip
67
+ [10_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-10_H-768_A-12.zip
68
+ [12_128]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-12_H-128_A-2.zip
69
+ [12_256]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-12_H-256_A-4.zip
70
+ [12_512]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-12_H-512_A-8.zip
71
+ [12_768]: https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-12_H-768_A-12.zip
72
+ [all]: https://storage.googleapis.com/bert_models/2020_02_20/all_bert_models.zip
73
+
74
+ **\*\*\*\*\* New May 31st, 2019: Whole Word Masking Models \*\*\*\*\***
75
+
76
+ This is a release of several new models which were the result of an improvement
77
+ the pre-processing code.
78
+
79
+ In the original pre-processing code, we randomly select WordPiece tokens to
80
+ mask. For example:
81
+
82
+ `Input Text: the man jumped up , put his basket on phil ##am ##mon ' s head`
83
+ `Original Masked Input: [MASK] man [MASK] up , put his [MASK] on phil
84
+ [MASK] ##mon ' s head`
85
+
86
+ The new technique is called Whole Word Masking. In this case, we always mask
87
+ *all* of the the tokens corresponding to a word at once. The overall masking
88
+ rate remains the same.
89
+
90
+ `Whole Word Masked Input: the man [MASK] up , put his basket on [MASK] [MASK]
91
+ [MASK] ' s head`
92
+
93
+ The training is identical -- we still predict each masked WordPiece token
94
+ independently. The improvement comes from the fact that the original prediction
95
+ task was too 'easy' for words that had been split into multiple WordPieces.
96
+
97
+ This can be enabled during data generation by passing the flag
98
+ `--do_whole_word_mask=True` to `create_pretraining_data.py`.
99
+
100
+ Pre-trained models with Whole Word Masking are linked below. The data and
101
+ training were otherwise identical, and the models have identical structure and
102
+ vocab to the original models. We only include BERT-Large models. When using
103
+ these models, please make it clear in the paper that you are using the Whole
104
+ Word Masking variant of BERT-Large.
105
+
106
+ * **[`BERT-Large, Uncased (Whole Word Masking)`](https://storage.googleapis.com/bert_models/2019_05_30/wwm_uncased_L-24_H-1024_A-16.zip)**:
107
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
108
+
109
+ * **[`BERT-Large, Cased (Whole Word Masking)`](https://storage.googleapis.com/bert_models/2019_05_30/wwm_cased_L-24_H-1024_A-16.zip)**:
110
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
111
+
112
+ Model | SQUAD 1.1 F1/EM | Multi NLI Accuracy
113
+ ---------------------------------------- | :-------------: | :----------------:
114
+ BERT-Large, Uncased (Original) | 91.0/84.3 | 86.05
115
+ BERT-Large, Uncased (Whole Word Masking) | 92.8/86.7 | 87.07
116
+ BERT-Large, Cased (Original) | 91.5/84.8 | 86.09
117
+ BERT-Large, Cased (Whole Word Masking) | 92.9/86.7 | 86.46
118
+
119
+ **\*\*\*\*\* New February 7th, 2019: TfHub Module \*\*\*\*\***
120
+
121
+ BERT has been uploaded to [TensorFlow Hub](https://tfhub.dev). See
122
+ `run_classifier_with_tfhub.py` for an example of how to use the TF Hub module,
123
+ or run an example in the browser on
124
+ [Colab](https://colab.sandbox.google.com/github/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb).
125
+
126
+ **\*\*\*\*\* New November 23rd, 2018: Un-normalized multilingual model + Thai +
127
+ Mongolian \*\*\*\*\***
128
+
129
+ We uploaded a new multilingual model which does *not* perform any normalization
130
+ on the input (no lower casing, accent stripping, or Unicode normalization), and
131
+ additionally inclues Thai and Mongolian.
132
+
133
+ **It is recommended to use this version for developing multilingual models,
134
+ especially on languages with non-Latin alphabets.**
135
+
136
+ This does not require any code changes, and can be downloaded here:
137
+
138
+ * **[`BERT-Base, Multilingual Cased`](https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip)**:
139
+ 104 languages, 12-layer, 768-hidden, 12-heads, 110M parameters
140
+
141
+ **\*\*\*\*\* New November 15th, 2018: SOTA SQuAD 2.0 System \*\*\*\*\***
142
+
143
+ We released code changes to reproduce our 83% F1 SQuAD 2.0 system, which is
144
+ currently 1st place on the leaderboard by 3%. See the SQuAD 2.0 section of the
145
+ README for details.
146
+
147
+ **\*\*\*\*\* New November 5th, 2018: Third-party PyTorch and Chainer versions of
148
+ BERT available \*\*\*\*\***
149
+
150
+ NLP researchers from HuggingFace made a
151
+ [PyTorch version of BERT available](https://github.com/huggingface/pytorch-pretrained-BERT)
152
+ which is compatible with our pre-trained checkpoints and is able to reproduce
153
+ our results. Sosuke Kobayashi also made a
154
+ [Chainer version of BERT available](https://github.com/soskek/bert-chainer)
155
+ (Thanks!) We were not involved in the creation or maintenance of the PyTorch
156
+ implementation so please direct any questions towards the authors of that
157
+ repository.
158
+
159
+ **\*\*\*\*\* New November 3rd, 2018: Multilingual and Chinese models available
160
+ \*\*\*\*\***
161
+
162
+ We have made two new BERT models available:
163
+
164
+ * **[`BERT-Base, Multilingual`](https://storage.googleapis.com/bert_models/2018_11_03/multilingual_L-12_H-768_A-12.zip)
165
+ (Not recommended, use `Multilingual Cased` instead)**: 102 languages,
166
+ 12-layer, 768-hidden, 12-heads, 110M parameters
167
+ * **[`BERT-Base, Chinese`](https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip)**:
168
+ Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M
169
+ parameters
170
+
171
+ We use character-based tokenization for Chinese, and WordPiece tokenization for
172
+ all other languages. Both models should work out-of-the-box without any code
173
+ changes. We did update the implementation of `BasicTokenizer` in
174
+ `tokenization.py` to support Chinese character tokenization, so please update if
175
+ you forked it. However, we did not change the tokenization API.
176
+
177
+ For more, see the
178
+ [Multilingual README](https://github.com/google-research/bert/blob/master/multilingual.md).
179
+
180
+ **\*\*\*\*\* End new information \*\*\*\*\***
181
+
182
+ ## Introduction
183
+
184
+ **BERT**, or **B**idirectional **E**ncoder **R**epresentations from
185
+ **T**ransformers, is a new method of pre-training language representations which
186
+ obtains state-of-the-art results on a wide array of Natural Language Processing
187
+ (NLP) tasks.
188
+
189
+ Our academic paper which describes BERT in detail and provides full results on a
190
+ number of tasks can be found here:
191
+ [https://arxiv.org/abs/1810.04805](https://arxiv.org/abs/1810.04805).
192
+
193
+ To give a few numbers, here are the results on the
194
+ [SQuAD v1.1](https://rajpurkar.github.io/SQuAD-explorer/) question answering
195
+ task:
196
+
197
+ SQuAD v1.1 Leaderboard (Oct 8th 2018) | Test EM | Test F1
198
+ ------------------------------------- | :------: | :------:
199
+ 1st Place Ensemble - BERT | **87.4** | **93.2**
200
+ 2nd Place Ensemble - nlnet | 86.0 | 91.7
201
+ 1st Place Single Model - BERT | **85.1** | **91.8**
202
+ 2nd Place Single Model - nlnet | 83.5 | 90.1
203
+
204
+ And several natural language inference tasks:
205
+
206
+ System | MultiNLI | Question NLI | SWAG
207
+ ----------------------- | :------: | :----------: | :------:
208
+ BERT | **86.7** | **91.1** | **86.3**
209
+ OpenAI GPT (Prev. SOTA) | 82.2 | 88.1 | 75.0
210
+
211
+ Plus many other tasks.
212
+
213
+ Moreover, these results were all obtained with almost no task-specific neural
214
+ network architecture design.
215
+
216
+ If you already know what BERT is and you just want to get started, you can
217
+ [download the pre-trained models](#pre-trained-models) and
218
+ [run a state-of-the-art fine-tuning](#fine-tuning-with-bert) in only a few
219
+ minutes.
220
+
221
+ ## What is BERT?
222
+
223
+ BERT is a method of pre-training language representations, meaning that we train
224
+ a general-purpose "language understanding" model on a large text corpus (like
225
+ Wikipedia), and then use that model for downstream NLP tasks that we care about
226
+ (like question answering). BERT outperforms previous methods because it is the
227
+ first *unsupervised*, *deeply bidirectional* system for pre-training NLP.
228
+
229
+ *Unsupervised* means that BERT was trained using only a plain text corpus, which
230
+ is important because an enormous amount of plain text data is publicly available
231
+ on the web in many languages.
232
+
233
+ Pre-trained representations can also either be *context-free* or *contextual*,
234
+ and contextual representations can further be *unidirectional* or
235
+ *bidirectional*. Context-free models such as
236
+ [word2vec](https://www.tensorflow.org/tutorials/representation/word2vec) or
237
+ [GloVe](https://nlp.stanford.edu/projects/glove/) generate a single "word
238
+ embedding" representation for each word in the vocabulary, so `bank` would have
239
+ the same representation in `bank deposit` and `river bank`. Contextual models
240
+ instead generate a representation of each word that is based on the other words
241
+ in the sentence.
242
+
243
+ BERT was built upon recent work in pre-training contextual representations —
244
+ including [Semi-supervised Sequence Learning](https://arxiv.org/abs/1511.01432),
245
+ [Generative Pre-Training](https://blog.openai.com/language-unsupervised/),
246
+ [ELMo](https://allennlp.org/elmo), and
247
+ [ULMFit](http://nlp.fast.ai/classification/2018/05/15/introducting-ulmfit.html)
248
+ — but crucially these models are all *unidirectional* or *shallowly
249
+ bidirectional*. This means that each word is only contextualized using the words
250
+ to its left (or right). For example, in the sentence `I made a bank deposit` the
251
+ unidirectional representation of `bank` is only based on `I made a` but not
252
+ `deposit`. Some previous work does combine the representations from separate
253
+ left-context and right-context models, but only in a "shallow" manner. BERT
254
+ represents "bank" using both its left and right context — `I made a ... deposit`
255
+ — starting from the very bottom of a deep neural network, so it is *deeply
256
+ bidirectional*.
257
+
258
+ BERT uses a simple approach for this: We mask out 15% of the words in the input,
259
+ run the entire sequence through a deep bidirectional
260
+ [Transformer](https://arxiv.org/abs/1706.03762) encoder, and then predict only
261
+ the masked words. For example:
262
+
263
+ ```
264
+ Input: the man went to the [MASK1] . he bought a [MASK2] of milk.
265
+ Labels: [MASK1] = store; [MASK2] = gallon
266
+ ```
267
+
268
+ In order to learn relationships between sentences, we also train on a simple
269
+ task which can be generated from any monolingual corpus: Given two sentences `A`
270
+ and `B`, is `B` the actual next sentence that comes after `A`, or just a random
271
+ sentence from the corpus?
272
+
273
+ ```
274
+ Sentence A: the man went to the store .
275
+ Sentence B: he bought a gallon of milk .
276
+ Label: IsNextSentence
277
+ ```
278
+
279
+ ```
280
+ Sentence A: the man went to the store .
281
+ Sentence B: penguins are flightless .
282
+ Label: NotNextSentence
283
+ ```
284
+
285
+ We then train a large model (12-layer to 24-layer Transformer) on a large corpus
286
+ (Wikipedia + [BookCorpus](http://yknzhu.wixsite.com/mbweb)) for a long time (1M
287
+ update steps), and that's BERT.
288
+
289
+ Using BERT has two stages: *Pre-training* and *fine-tuning*.
290
+
291
+ **Pre-training** is fairly expensive (four days on 4 to 16 Cloud TPUs), but is a
292
+ one-time procedure for each language (current models are English-only, but
293
+ multilingual models will be released in the near future). We are releasing a
294
+ number of pre-trained models from the paper which were pre-trained at Google.
295
+ Most NLP researchers will never need to pre-train their own model from scratch.
296
+
297
+ **Fine-tuning** is inexpensive. All of the results in the paper can be
298
+ replicated in at most 1 hour on a single Cloud TPU, or a few hours on a GPU,
299
+ starting from the exact same pre-trained model. SQuAD, for example, can be
300
+ trained in around 30 minutes on a single Cloud TPU to achieve a Dev F1 score of
301
+ 91.0%, which is the single system state-of-the-art.
302
+
303
+ The other important aspect of BERT is that it can be adapted to many types of
304
+ NLP tasks very easily. In the paper, we demonstrate state-of-the-art results on
305
+ sentence-level (e.g., SST-2), sentence-pair-level (e.g., MultiNLI), word-level
306
+ (e.g., NER), and span-level (e.g., SQuAD) tasks with almost no task-specific
307
+ modifications.
308
+
309
+ ## What has been released in this repository?
310
+
311
+ We are releasing the following:
312
+
313
+ * TensorFlow code for the BERT model architecture (which is mostly a standard
314
+ [Transformer](https://arxiv.org/abs/1706.03762) architecture).
315
+ * Pre-trained checkpoints for both the lowercase and cased version of
316
+ `BERT-Base` and `BERT-Large` from the paper.
317
+ * TensorFlow code for push-button replication of the most important
318
+ fine-tuning experiments from the paper, including SQuAD, MultiNLI, and MRPC.
319
+
320
+ All of the code in this repository works out-of-the-box with CPU, GPU, and Cloud
321
+ TPU.
322
+
323
+ ## Pre-trained models
324
+
325
+ We are releasing the `BERT-Base` and `BERT-Large` models from the paper.
326
+ `Uncased` means that the text has been lowercased before WordPiece tokenization,
327
+ e.g., `John Smith` becomes `john smith`. The `Uncased` model also strips out any
328
+ accent markers. `Cased` means that the true case and accent markers are
329
+ preserved. Typically, the `Uncased` model is better unless you know that case
330
+ information is important for your task (e.g., Named Entity Recognition or
331
+ Part-of-Speech tagging).
332
+
333
+ These models are all released under the same license as the source code (Apache
334
+ 2.0).
335
+
336
+ For information about the Multilingual and Chinese model, see the
337
+ [Multilingual README](https://github.com/google-research/bert/blob/master/multilingual.md).
338
+
339
+ **When using a cased model, make sure to pass `--do_lower=False` to the training
340
+ scripts. (Or pass `do_lower_case=False` directly to `FullTokenizer` if you're
341
+ using your own script.)**
342
+
343
+ The links to the models are here (right-click, 'Save link as...' on the name):
344
+
345
+ * **[`BERT-Large, Uncased (Whole Word Masking)`](https://storage.googleapis.com/bert_models/2019_05_30/wwm_uncased_L-24_H-1024_A-16.zip)**:
346
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
347
+ * **[`BERT-Large, Cased (Whole Word Masking)`](https://storage.googleapis.com/bert_models/2019_05_30/wwm_cased_L-24_H-1024_A-16.zip)**:
348
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
349
+ * **[`BERT-Base, Uncased`](https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip)**:
350
+ 12-layer, 768-hidden, 12-heads, 110M parameters
351
+ * **[`BERT-Large, Uncased`](https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-24_H-1024_A-16.zip)**:
352
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
353
+ * **[`BERT-Base, Cased`](https://storage.googleapis.com/bert_models/2018_10_18/cased_L-12_H-768_A-12.zip)**:
354
+ 12-layer, 768-hidden, 12-heads , 110M parameters
355
+ * **[`BERT-Large, Cased`](https://storage.googleapis.com/bert_models/2018_10_18/cased_L-24_H-1024_A-16.zip)**:
356
+ 24-layer, 1024-hidden, 16-heads, 340M parameters
357
+ * **[`BERT-Base, Multilingual Cased (New, recommended)`](https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip)**:
358
+ 104 languages, 12-layer, 768-hidden, 12-heads, 110M parameters
359
+ * **[`BERT-Base, Multilingual Uncased (Orig, not recommended)`](https://storage.googleapis.com/bert_models/2018_11_03/multilingual_L-12_H-768_A-12.zip)
360
+ (Not recommended, use `Multilingual Cased` instead)**: 102 languages,
361
+ 12-layer, 768-hidden, 12-heads, 110M parameters
362
+ * **[`BERT-Base, Chinese`](https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip)**:
363
+ Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M
364
+ parameters
365
+
366
+ Each .zip file contains three items:
367
+
368
+ * A TensorFlow checkpoint (`bert_model.ckpt`) containing the pre-trained
369
+ weights (which is actually 3 files).
370
+ * A vocab file (`vocab.txt`) to map WordPiece to word id.
371
+ * A config file (`bert_config.json`) which specifies the hyperparameters of
372
+ the model.
373
+
374
+ ## Fine-tuning with BERT
375
+
376
+ **Important**: All results on the paper were fine-tuned on a single Cloud TPU,
377
+ which has 64GB of RAM. It is currently not possible to re-produce most of the
378
+ `BERT-Large` results on the paper using a GPU with 12GB - 16GB of RAM, because
379
+ the maximum batch size that can fit in memory is too small. We are working on
380
+ adding code to this repository which allows for much larger effective batch size
381
+ on the GPU. See the section on [out-of-memory issues](#out-of-memory-issues) for
382
+ more details.
383
+
384
+ This code was tested with TensorFlow 1.11.0. It was tested with Python2 and
385
+ Python3 (but more thoroughly with Python2, since this is what's used internally
386
+ in Google).
387
+
388
+ The fine-tuning examples which use `BERT-Base` should be able to run on a GPU
389
+ that has at least 12GB of RAM using the hyperparameters given.
390
+
391
+ ### Fine-tuning with Cloud TPUs
392
+
393
+ Most of the examples below assumes that you will be running training/evaluation
394
+ on your local machine, using a GPU like a Titan X or GTX 1080.
395
+
396
+ However, if you have access to a Cloud TPU that you want to train on, just add
397
+ the following flags to `run_classifier.py` or `run_squad.py`:
398
+
399
+ ```
400
+ --use_tpu=True \
401
+ --tpu_name=$TPU_NAME
402
+ ```
403
+
404
+ Please see the
405
+ [Google Cloud TPU tutorial](https://cloud.google.com/tpu/docs/tutorials/mnist)
406
+ for how to use Cloud TPUs. Alternatively, you can use the Google Colab notebook
407
+ "[BERT FineTuning with Cloud TPUs](https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/bert_finetuning_with_cloud_tpus.ipynb)".
408
+
409
+ On Cloud TPUs, the pretrained model and the output directory will need to be on
410
+ Google Cloud Storage. For example, if you have a bucket named `some_bucket`, you
411
+ might use the following flags instead:
412
+
413
+ ```
414
+ --output_dir=gs://some_bucket/my_output_dir/
415
+ ```
416
+
417
+ The unzipped pre-trained model files can also be found in the Google Cloud
418
+ Storage folder `gs://bert_models/2018_10_18`. For example:
419
+
420
+ ```
421
+ export BERT_BASE_DIR=gs://bert_models/2018_10_18/uncased_L-12_H-768_A-12
422
+ ```
423
+
424
+ ### Sentence (and sentence-pair) classification tasks
425
+
426
+ Before running this example you must download the
427
+ [GLUE data](https://gluebenchmark.com/tasks) by running
428
+ [this script](https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e)
429
+ and unpack it to some directory `$GLUE_DIR`. Next, download the `BERT-Base`
430
+ checkpoint and unzip it to some directory `$BERT_BASE_DIR`.
431
+
432
+ This example code fine-tunes `BERT-Base` on the Microsoft Research Paraphrase
433
+ Corpus (MRPC) corpus, which only contains 3,600 examples and can fine-tune in a
434
+ few minutes on most GPUs.
435
+
436
+ ```shell
437
+ export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
438
+ export GLUE_DIR=/path/to/glue
439
+
440
+ python run_classifier.py \
441
+ --task_name=MRPC \
442
+ --do_train=true \
443
+ --do_eval=true \
444
+ --data_dir=$GLUE_DIR/MRPC \
445
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
446
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
447
+ --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
448
+ --max_seq_length=128 \
449
+ --train_batch_size=32 \
450
+ --learning_rate=2e-5 \
451
+ --num_train_epochs=3.0 \
452
+ --output_dir=/tmp/mrpc_output/
453
+ ```
454
+
455
+ You should see output like this:
456
+
457
+ ```
458
+ ***** Eval results *****
459
+ eval_accuracy = 0.845588
460
+ eval_loss = 0.505248
461
+ global_step = 343
462
+ loss = 0.505248
463
+ ```
464
+
465
+ This means that the Dev set accuracy was 84.55%. Small sets like MRPC have a
466
+ high variance in the Dev set accuracy, even when starting from the same
467
+ pre-training checkpoint. If you re-run multiple times (making sure to point to
468
+ different `output_dir`), you should see results between 84% and 88%.
469
+
470
+ A few other pre-trained models are implemented off-the-shelf in
471
+ `run_classifier.py`, so it should be straightforward to follow those examples to
472
+ use BERT for any single-sentence or sentence-pair classification task.
473
+
474
+ Note: You might see a message `Running train on CPU`. This really just means
475
+ that it's running on something other than a Cloud TPU, which includes a GPU.
476
+
477
+ #### Prediction from classifier
478
+
479
+ Once you have trained your classifier you can use it in inference mode by using
480
+ the --do_predict=true command. You need to have a file named test.tsv in the
481
+ input folder. Output will be created in file called test_results.tsv in the
482
+ output folder. Each line will contain output for each sample, columns are the
483
+ class probabilities.
484
+
485
+ ```shell
486
+ export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
487
+ export GLUE_DIR=/path/to/glue
488
+ export TRAINED_CLASSIFIER=/path/to/fine/tuned/classifier
489
+
490
+ python run_classifier.py \
491
+ --task_name=MRPC \
492
+ --do_predict=true \
493
+ --data_dir=$GLUE_DIR/MRPC \
494
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
495
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
496
+ --init_checkpoint=$TRAINED_CLASSIFIER \
497
+ --max_seq_length=128 \
498
+ --output_dir=/tmp/mrpc_output/
499
+ ```
500
+
501
+ ### SQuAD 1.1
502
+
503
+ The Stanford Question Answering Dataset (SQuAD) is a popular question answering
504
+ benchmark dataset. BERT (at the time of the release) obtains state-of-the-art
505
+ results on SQuAD with almost no task-specific network architecture modifications
506
+ or data augmentation. However, it does require semi-complex data pre-processing
507
+ and post-processing to deal with (a) the variable-length nature of SQuAD context
508
+ paragraphs, and (b) the character-level answer annotations which are used for
509
+ SQuAD training. This processing is implemented and documented in `run_squad.py`.
510
+
511
+ To run on SQuAD, you will first need to download the dataset. The
512
+ [SQuAD website](https://rajpurkar.github.io/SQuAD-explorer/) does not seem to
513
+ link to the v1.1 datasets any longer, but the necessary files can be found here:
514
+
515
+ * [train-v1.1.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json)
516
+ * [dev-v1.1.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json)
517
+ * [evaluate-v1.1.py](https://github.com/allenai/bi-att-flow/blob/master/squad/evaluate-v1.1.py)
518
+
519
+ Download these to some directory `$SQUAD_DIR`.
520
+
521
+ The state-of-the-art SQuAD results from the paper currently cannot be reproduced
522
+ on a 12GB-16GB GPU due to memory constraints (in fact, even batch size 1 does
523
+ not seem to fit on a 12GB GPU using `BERT-Large`). However, a reasonably strong
524
+ `BERT-Base` model can be trained on the GPU with these hyperparameters:
525
+
526
+ ```shell
527
+ python run_squad.py \
528
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
529
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
530
+ --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
531
+ --do_train=True \
532
+ --train_file=$SQUAD_DIR/train-v1.1.json \
533
+ --do_predict=True \
534
+ --predict_file=$SQUAD_DIR/dev-v1.1.json \
535
+ --train_batch_size=12 \
536
+ --learning_rate=3e-5 \
537
+ --num_train_epochs=2.0 \
538
+ --max_seq_length=384 \
539
+ --doc_stride=128 \
540
+ --output_dir=/tmp/squad_base/
541
+ ```
542
+
543
+ The dev set predictions will be saved into a file called `predictions.json` in
544
+ the `output_dir`:
545
+
546
+ ```shell
547
+ python $SQUAD_DIR/evaluate-v1.1.py $SQUAD_DIR/dev-v1.1.json ./squad/predictions.json
548
+ ```
549
+
550
+ Which should produce an output like this:
551
+
552
+ ```shell
553
+ {"f1": 88.41249612335034, "exact_match": 81.2488174077578}
554
+ ```
555
+
556
+ You should see a result similar to the 88.5% reported in the paper for
557
+ `BERT-Base`.
558
+
559
+ If you have access to a Cloud TPU, you can train with `BERT-Large`. Here is a
560
+ set of hyperparameters (slightly different than the paper) which consistently
561
+ obtain around 90.5%-91.0% F1 single-system trained only on SQuAD:
562
+
563
+ ```shell
564
+ python run_squad.py \
565
+ --vocab_file=$BERT_LARGE_DIR/vocab.txt \
566
+ --bert_config_file=$BERT_LARGE_DIR/bert_config.json \
567
+ --init_checkpoint=$BERT_LARGE_DIR/bert_model.ckpt \
568
+ --do_train=True \
569
+ --train_file=$SQUAD_DIR/train-v1.1.json \
570
+ --do_predict=True \
571
+ --predict_file=$SQUAD_DIR/dev-v1.1.json \
572
+ --train_batch_size=24 \
573
+ --learning_rate=3e-5 \
574
+ --num_train_epochs=2.0 \
575
+ --max_seq_length=384 \
576
+ --doc_stride=128 \
577
+ --output_dir=gs://some_bucket/squad_large/ \
578
+ --use_tpu=True \
579
+ --tpu_name=$TPU_NAME
580
+ ```
581
+
582
+ For example, one random run with these parameters produces the following Dev
583
+ scores:
584
+
585
+ ```shell
586
+ {"f1": 90.87081895814865, "exact_match": 84.38978240302744}
587
+ ```
588
+
589
+ If you fine-tune for one epoch on
590
+ [TriviaQA](http://nlp.cs.washington.edu/triviaqa/) before this the results will
591
+ be even better, but you will need to convert TriviaQA into the SQuAD json
592
+ format.
593
+
594
+ ### SQuAD 2.0
595
+
596
+ This model is also implemented and documented in `run_squad.py`.
597
+
598
+ To run on SQuAD 2.0, you will first need to download the dataset. The necessary
599
+ files can be found here:
600
+
601
+ * [train-v2.0.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json)
602
+ * [dev-v2.0.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json)
603
+ * [evaluate-v2.0.py](https://worksheets.codalab.org/rest/bundles/0x6b567e1cf2e041ec80d7098f031c5c9e/contents/blob/)
604
+
605
+ Download these to some directory `$SQUAD_DIR`.
606
+
607
+ On Cloud TPU you can run with BERT-Large as follows:
608
+
609
+ ```shell
610
+ python run_squad.py \
611
+ --vocab_file=$BERT_LARGE_DIR/vocab.txt \
612
+ --bert_config_file=$BERT_LARGE_DIR/bert_config.json \
613
+ --init_checkpoint=$BERT_LARGE_DIR/bert_model.ckpt \
614
+ --do_train=True \
615
+ --train_file=$SQUAD_DIR/train-v2.0.json \
616
+ --do_predict=True \
617
+ --predict_file=$SQUAD_DIR/dev-v2.0.json \
618
+ --train_batch_size=24 \
619
+ --learning_rate=3e-5 \
620
+ --num_train_epochs=2.0 \
621
+ --max_seq_length=384 \
622
+ --doc_stride=128 \
623
+ --output_dir=gs://some_bucket/squad_large/ \
624
+ --use_tpu=True \
625
+ --tpu_name=$TPU_NAME \
626
+ --version_2_with_negative=True
627
+ ```
628
+
629
+ We assume you have copied everything from the output directory to a local
630
+ directory called ./squad/. The initial dev set predictions will be at
631
+ ./squad/predictions.json and the differences between the score of no answer ("")
632
+ and the best non-null answer for each question will be in the file
633
+ ./squad/null_odds.json
634
+
635
+ Run this script to tune a threshold for predicting null versus non-null answers:
636
+
637
+ python $SQUAD_DIR/evaluate-v2.0.py $SQUAD_DIR/dev-v2.0.json
638
+ ./squad/predictions.json --na-prob-file ./squad/null_odds.json
639
+
640
+ Assume the script outputs "best_f1_thresh" THRESH. (Typical values are between
641
+ -1.0 and -5.0). You can now re-run the model to generate predictions with the
642
+ derived threshold or alternatively you can extract the appropriate answers from
643
+ ./squad/nbest_predictions.json.
644
+
645
+ ```shell
646
+ python run_squad.py \
647
+ --vocab_file=$BERT_LARGE_DIR/vocab.txt \
648
+ --bert_config_file=$BERT_LARGE_DIR/bert_config.json \
649
+ --init_checkpoint=$BERT_LARGE_DIR/bert_model.ckpt \
650
+ --do_train=False \
651
+ --train_file=$SQUAD_DIR/train-v2.0.json \
652
+ --do_predict=True \
653
+ --predict_file=$SQUAD_DIR/dev-v2.0.json \
654
+ --train_batch_size=24 \
655
+ --learning_rate=3e-5 \
656
+ --num_train_epochs=2.0 \
657
+ --max_seq_length=384 \
658
+ --doc_stride=128 \
659
+ --output_dir=gs://some_bucket/squad_large/ \
660
+ --use_tpu=True \
661
+ --tpu_name=$TPU_NAME \
662
+ --version_2_with_negative=True \
663
+ --null_score_diff_threshold=$THRESH
664
+ ```
665
+
666
+ ### Out-of-memory issues
667
+
668
+ All experiments in the paper were fine-tuned on a Cloud TPU, which has 64GB of
669
+ device RAM. Therefore, when using a GPU with 12GB - 16GB of RAM, you are likely
670
+ to encounter out-of-memory issues if you use the same hyperparameters described
671
+ in the paper.
672
+
673
+ The factors that affect memory usage are:
674
+
675
+ * **`max_seq_length`**: The released models were trained with sequence lengths
676
+ up to 512, but you can fine-tune with a shorter max sequence length to save
677
+ substantial memory. This is controlled by the `max_seq_length` flag in our
678
+ example code.
679
+
680
+ * **`train_batch_size`**: The memory usage is also directly proportional to
681
+ the batch size.
682
+
683
+ * **Model type, `BERT-Base` vs. `BERT-Large`**: The `BERT-Large` model
684
+ requires significantly more memory than `BERT-Base`.
685
+
686
+ * **Optimizer**: The default optimizer for BERT is Adam, which requires a lot
687
+ of extra memory to store the `m` and `v` vectors. Switching to a more memory
688
+ efficient optimizer can reduce memory usage, but can also affect the
689
+ results. We have not experimented with other optimizers for fine-tuning.
690
+
691
+ Using the default training scripts (`run_classifier.py` and `run_squad.py`), we
692
+ benchmarked the maximum batch size on single Titan X GPU (12GB RAM) with
693
+ TensorFlow 1.11.0:
694
+
695
+ System | Seq Length | Max Batch Size
696
+ ------------ | ---------- | --------------
697
+ `BERT-Base` | 64 | 64
698
+ ... | 128 | 32
699
+ ... | 256 | 16
700
+ ... | 320 | 14
701
+ ... | 384 | 12
702
+ ... | 512 | 6
703
+ `BERT-Large` | 64 | 12
704
+ ... | 128 | 6
705
+ ... | 256 | 2
706
+ ... | 320 | 1
707
+ ... | 384 | 0
708
+ ... | 512 | 0
709
+
710
+ Unfortunately, these max batch sizes for `BERT-Large` are so small that they
711
+ will actually harm the model accuracy, regardless of the learning rate used. We
712
+ are working on adding code to this repository which will allow much larger
713
+ effective batch sizes to be used on the GPU. The code will be based on one (or
714
+ both) of the following techniques:
715
+
716
+ * **Gradient accumulation**: The samples in a minibatch are typically
717
+ independent with respect to gradient computation (excluding batch
718
+ normalization, which is not used here). This means that the gradients of
719
+ multiple smaller minibatches can be accumulated before performing the weight
720
+ update, and this will be exactly equivalent to a single larger update.
721
+
722
+ * [**Gradient checkpointing**](https://github.com/openai/gradient-checkpointing):
723
+ The major use of GPU/TPU memory during DNN training is caching the
724
+ intermediate activations in the forward pass that are necessary for
725
+ efficient computation in the backward pass. "Gradient checkpointing" trades
726
+ memory for compute time by re-computing the activations in an intelligent
727
+ way.
728
+
729
+ **However, this is not implemented in the current release.**
730
+
731
+ ## Using BERT to extract fixed feature vectors (like ELMo)
732
+
733
+ In certain cases, rather than fine-tuning the entire pre-trained model
734
+ end-to-end, it can be beneficial to obtained *pre-trained contextual
735
+ embeddings*, which are fixed contextual representations of each input token
736
+ generated from the hidden layers of the pre-trained model. This should also
737
+ mitigate most of the out-of-memory issues.
738
+
739
+ As an example, we include the script `extract_features.py` which can be used
740
+ like this:
741
+
742
+ ```shell
743
+ # Sentence A and Sentence B are separated by the ||| delimiter for sentence
744
+ # pair tasks like question answering and entailment.
745
+ # For single sentence inputs, put one sentence per line and DON'T use the
746
+ # delimiter.
747
+ echo 'Who was Jim Henson ? ||| Jim Henson was a puppeteer' > /tmp/input.txt
748
+
749
+ python extract_features.py \
750
+ --input_file=/tmp/input.txt \
751
+ --output_file=/tmp/output.jsonl \
752
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
753
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
754
+ --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
755
+ --layers=-1,-2,-3,-4 \
756
+ --max_seq_length=128 \
757
+ --batch_size=8
758
+ ```
759
+
760
+ This will create a JSON file (one line per line of input) containing the BERT
761
+ activations from each Transformer layer specified by `layers` (-1 is the final
762
+ hidden layer of the Transformer, etc.)
763
+
764
+ Note that this script will produce very large output files (by default, around
765
+ 15kb for every input token).
766
+
767
+ If you need to maintain alignment between the original and tokenized words (for
768
+ projecting training labels), see the [Tokenization](#tokenization) section
769
+ below.
770
+
771
+ **Note:** You may see a message like `Could not find trained model in model_dir:
772
+ /tmp/tmpuB5g5c, running initialization to predict.` This message is expected, it
773
+ just means that we are using the `init_from_checkpoint()` API rather than the
774
+ saved model API. If you don't specify a checkpoint or specify an invalid
775
+ checkpoint, this script will complain.
776
+
777
+ ## Tokenization
778
+
779
+ For sentence-level tasks (or sentence-pair) tasks, tokenization is very simple.
780
+ Just follow the example code in `run_classifier.py` and `extract_features.py`.
781
+ The basic procedure for sentence-level tasks is:
782
+
783
+ 1. Instantiate an instance of `tokenizer = tokenization.FullTokenizer`
784
+
785
+ 2. Tokenize the raw text with `tokens = tokenizer.tokenize(raw_text)`.
786
+
787
+ 3. Truncate to the maximum sequence length. (You can use up to 512, but you
788
+ probably want to use shorter if possible for memory and speed reasons.)
789
+
790
+ 4. Add the `[CLS]` and `[SEP]` tokens in the right place.
791
+
792
+ Word-level and span-level tasks (e.g., SQuAD and NER) are more complex, since
793
+ you need to maintain alignment between your input text and output text so that
794
+ you can project your training labels. SQuAD is a particularly complex example
795
+ because the input labels are *character*-based, and SQuAD paragraphs are often
796
+ longer than our maximum sequence length. See the code in `run_squad.py` to show
797
+ how we handle this.
798
+
799
+ Before we describe the general recipe for handling word-level tasks, it's
800
+ important to understand what exactly our tokenizer is doing. It has three main
801
+ steps:
802
+
803
+ 1. **Text normalization**: Convert all whitespace characters to spaces, and
804
+ (for the `Uncased` model) lowercase the input and strip out accent markers.
805
+ E.g., `John Johanson's, → john johanson's,`.
806
+
807
+ 2. **Punctuation splitting**: Split *all* punctuation characters on both sides
808
+ (i.e., add whitespace around all punctuation characters). Punctuation
809
+ characters are defined as (a) Anything with a `P*` Unicode class, (b) any
810
+ non-letter/number/space ASCII character (e.g., characters like `$` which are
811
+ technically not punctuation). E.g., `john johanson's, → john johanson ' s ,`
812
+
813
+ 3. **WordPiece tokenization**: Apply whitespace tokenization to the output of
814
+ the above procedure, and apply
815
+ [WordPiece](https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/text_encoder.py)
816
+ tokenization to each token separately. (Our implementation is directly based
817
+ on the one from `tensor2tensor`, which is linked). E.g., `john johanson ' s
818
+ , → john johan ##son ' s ,`
819
+
820
+ The advantage of this scheme is that it is "compatible" with most existing
821
+ English tokenizers. For example, imagine that you have a part-of-speech tagging
822
+ task which looks like this:
823
+
824
+ ```
825
+ Input: John Johanson 's house
826
+ Labels: NNP NNP POS NN
827
+ ```
828
+
829
+ The tokenized output will look like this:
830
+
831
+ ```
832
+ Tokens: john johan ##son ' s house
833
+ ```
834
+
835
+ Crucially, this would be the same output as if the raw text were `John
836
+ Johanson's house` (with no space before the `'s`).
837
+
838
+ If you have a pre-tokenized representation with word-level annotations, you can
839
+ simply tokenize each input word independently, and deterministically maintain an
840
+ original-to-tokenized alignment:
841
+
842
+ ```python
843
+ ### Input
844
+ orig_tokens = ["John", "Johanson", "'s", "house"]
845
+ labels = ["NNP", "NNP", "POS", "NN"]
846
+
847
+ ### Output
848
+ bert_tokens = []
849
+
850
+ # Token map will be an int -> int mapping between the `orig_tokens` index and
851
+ # the `bert_tokens` index.
852
+ orig_to_tok_map = []
853
+
854
+ tokenizer = tokenization.FullTokenizer(
855
+ vocab_file=vocab_file, do_lower_case=True)
856
+
857
+ bert_tokens.append("[CLS]")
858
+ for orig_token in orig_tokens:
859
+ orig_to_tok_map.append(len(bert_tokens))
860
+ bert_tokens.extend(tokenizer.tokenize(orig_token))
861
+ bert_tokens.append("[SEP]")
862
+
863
+ # bert_tokens == ["[CLS]", "john", "johan", "##son", "'", "s", "house", "[SEP]"]
864
+ # orig_to_tok_map == [1, 2, 4, 6]
865
+ ```
866
+
867
+ Now `orig_to_tok_map` can be used to project `labels` to the tokenized
868
+ representation.
869
+
870
+ There are common English tokenization schemes which will cause a slight mismatch
871
+ between how BERT was pre-trained. For example, if your input tokenization splits
872
+ off contractions like `do n't`, this will cause a mismatch. If it is possible to
873
+ do so, you should pre-process your data to convert these back to raw-looking
874
+ text, but if it's not possible, this mismatch is likely not a big deal.
875
+
876
+ ## Pre-training with BERT
877
+
878
+ We are releasing code to do "masked LM" and "next sentence prediction" on an
879
+ arbitrary text corpus. Note that this is *not* the exact code that was used for
880
+ the paper (the original code was written in C++, and had some additional
881
+ complexity), but this code does generate pre-training data as described in the
882
+ paper.
883
+
884
+ Here's how to run the data generation. The input is a plain text file, with one
885
+ sentence per line. (It is important that these be actual sentences for the "next
886
+ sentence prediction" task). Documents are delimited by empty lines. The output
887
+ is a set of `tf.train.Example`s serialized into `TFRecord` file format.
888
+
889
+ You can perform sentence segmentation with an off-the-shelf NLP toolkit such as
890
+ [spaCy](https://spacy.io/). The `create_pretraining_data.py` script will
891
+ concatenate segments until they reach the maximum sequence length to minimize
892
+ computational waste from padding (see the script for more details). However, you
893
+ may want to intentionally add a slight amount of noise to your input data (e.g.,
894
+ randomly truncate 2% of input segments) to make it more robust to non-sentential
895
+ input during fine-tuning.
896
+
897
+ This script stores all of the examples for the entire input file in memory, so
898
+ for large data files you should shard the input file and call the script
899
+ multiple times. (You can pass in a file glob to `run_pretraining.py`, e.g.,
900
+ `tf_examples.tf_record*`.)
901
+
902
+ The `max_predictions_per_seq` is the maximum number of masked LM predictions per
903
+ sequence. You should set this to around `max_seq_length` * `masked_lm_prob` (the
904
+ script doesn't do that automatically because the exact value needs to be passed
905
+ to both scripts).
906
+
907
+ ```shell
908
+ python create_pretraining_data.py \
909
+ --input_file=./sample_text.txt \
910
+ --output_file=/tmp/tf_examples.tfrecord \
911
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
912
+ --do_lower_case=True \
913
+ --max_seq_length=128 \
914
+ --max_predictions_per_seq=20 \
915
+ --masked_lm_prob=0.15 \
916
+ --random_seed=12345 \
917
+ --dupe_factor=5
918
+ ```
919
+
920
+ Here's how to run the pre-training. Do not include `init_checkpoint` if you are
921
+ pre-training from scratch. The model configuration (including vocab size) is
922
+ specified in `bert_config_file`. This demo code only pre-trains for a small
923
+ number of steps (20), but in practice you will probably want to set
924
+ `num_train_steps` to 10000 steps or more. The `max_seq_length` and
925
+ `max_predictions_per_seq` parameters passed to `run_pretraining.py` must be the
926
+ same as `create_pretraining_data.py`.
927
+
928
+ ```shell
929
+ python run_pretraining.py \
930
+ --input_file=/tmp/tf_examples.tfrecord \
931
+ --output_dir=/tmp/pretraining_output \
932
+ --do_train=True \
933
+ --do_eval=True \
934
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
935
+ --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
936
+ --train_batch_size=32 \
937
+ --max_seq_length=128 \
938
+ --max_predictions_per_seq=20 \
939
+ --num_train_steps=20 \
940
+ --num_warmup_steps=10 \
941
+ --learning_rate=2e-5
942
+ ```
943
+
944
+ This will produce an output like this:
945
+
946
+ ```
947
+ ***** Eval results *****
948
+ global_step = 20
949
+ loss = 0.0979674
950
+ masked_lm_accuracy = 0.985479
951
+ masked_lm_loss = 0.0979328
952
+ next_sentence_accuracy = 1.0
953
+ next_sentence_loss = 3.45724e-05
954
+ ```
955
+
956
+ Note that since our `sample_text.txt` file is very small, this example training
957
+ will overfit that data in only a few steps and produce unrealistically high
958
+ accuracy numbers.
959
+
960
+ ### Pre-training tips and caveats
961
+
962
+ * **If using your own vocabulary, make sure to change `vocab_size` in
963
+ `bert_config.json`. If you use a larger vocabulary without changing this,
964
+ you will likely get NaNs when training on GPU or TPU due to unchecked
965
+ out-of-bounds access.**
966
+ * If your task has a large domain-specific corpus available (e.g., "movie
967
+ reviews" or "scientific papers"), it will likely be beneficial to run
968
+ additional steps of pre-training on your corpus, starting from the BERT
969
+ checkpoint.
970
+ * The learning rate we used in the paper was 1e-4. However, if you are doing
971
+ additional steps of pre-training starting from an existing BERT checkpoint,
972
+ you should use a smaller learning rate (e.g., 2e-5).
973
+ * Current BERT models are English-only, but we do plan to release a
974
+ multilingual model which has been pre-trained on a lot of languages in the
975
+ near future (hopefully by the end of November 2018).
976
+ * Longer sequences are disproportionately expensive because attention is
977
+ quadratic to the sequence length. In other words, a batch of 64 sequences of
978
+ length 512 is much more expensive than a batch of 256 sequences of
979
+ length 128. The fully-connected/convolutional cost is the same, but the
980
+ attention cost is far greater for the 512-length sequences. Therefore, one
981
+ good recipe is to pre-train for, say, 90,000 steps with a sequence length of
982
+ 128 and then for 10,000 additional steps with a sequence length of 512. The
983
+ very long sequences are mostly needed to learn positional embeddings, which
984
+ can be learned fairly quickly. Note that this does require generating the
985
+ data twice with different values of `max_seq_length`.
986
+ * If you are pre-training from scratch, be prepared that pre-training is
987
+ computationally expensive, especially on GPUs. If you are pre-training from
988
+ scratch, our recommended recipe is to pre-train a `BERT-Base` on a single
989
+ [preemptible Cloud TPU v2](https://cloud.google.com/tpu/docs/pricing), which
990
+ takes about 2 weeks at a cost of about $500 USD (based on the pricing in
991
+ October 2018). You will have to scale down the batch size when only training
992
+ on a single Cloud TPU, compared to what was used in the paper. It is
993
+ recommended to use the largest batch size that fits into TPU memory.
994
+
995
+ ### Pre-training data
996
+
997
+ We will **not** be able to release the pre-processed datasets used in the paper.
998
+ For Wikipedia, the recommended pre-processing is to download
999
+ [the latest dump](https://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2),
1000
+ extract the text with
1001
+ [`WikiExtractor.py`](https://github.com/attardi/wikiextractor), and then apply
1002
+ any necessary cleanup to convert it into plain text.
1003
+
1004
+ Unfortunately the researchers who collected the
1005
+ [BookCorpus](http://yknzhu.wixsite.com/mbweb) no longer have it available for
1006
+ public download. The
1007
+ [Project Guttenberg Dataset](https://web.eecs.umich.edu/~lahiri/gutenberg_dataset.html)
1008
+ is a somewhat smaller (200M word) collection of older books that are public
1009
+ domain.
1010
+
1011
+ [Common Crawl](http://commoncrawl.org/) is another very large collection of
1012
+ text, but you will likely have to do substantial pre-processing and cleanup to
1013
+ extract a usable corpus for pre-training BERT.
1014
+
1015
+ ### Learning a new WordPiece vocabulary
1016
+
1017
+ This repository does not include code for *learning* a new WordPiece vocabulary.
1018
+ The reason is that the code used in the paper was implemented in C++ with
1019
+ dependencies on Google's internal libraries. For English, it is almost always
1020
+ better to just start with our vocabulary and pre-trained models. For learning
1021
+ vocabularies of other languages, there are a number of open source options
1022
+ available. However, keep in mind that these are not compatible with our
1023
+ `tokenization.py` library:
1024
+
1025
+ * [Google's SentencePiece library](https://github.com/google/sentencepiece)
1026
+
1027
+ * [tensor2tensor's WordPiece generation script](https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/text_encoder_build_subword.py)
1028
+
1029
+ * [Rico Sennrich's Byte Pair Encoding library](https://github.com/rsennrich/subword-nmt)
1030
+
1031
+ ## Using BERT in Colab
1032
+
1033
+ If you want to use BERT with [Colab](https://colab.research.google.com), you can
1034
+ get started with the notebook
1035
+ "[BERT FineTuning with Cloud TPUs](https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/bert_finetuning_with_cloud_tpus.ipynb)".
1036
+ **At the time of this writing (October 31st, 2018), Colab users can access a
1037
+ Cloud TPU completely for free.** Note: One per user, availability limited,
1038
+ requires a Google Cloud Platform account with storage (although storage may be
1039
+ purchased with free credit for signing up with GCP), and this capability may not
1040
+ longer be available in the future. Click on the BERT Colab that was just linked
1041
+ for more information.
1042
+
1043
+ ## FAQ
1044
+
1045
+ #### Is this code compatible with Cloud TPUs? What about GPUs?
1046
+
1047
+ Yes, all of the code in this repository works out-of-the-box with CPU, GPU, and
1048
+ Cloud TPU. However, GPU training is single-GPU only.
1049
+
1050
+ #### I am getting out-of-memory errors, what is wrong?
1051
+
1052
+ See the section on [out-of-memory issues](#out-of-memory-issues) for more
1053
+ information.
1054
+
1055
+ #### Is there a PyTorch version available?
1056
+
1057
+ There is no official PyTorch implementation. However, NLP researchers from
1058
+ HuggingFace made a
1059
+ [PyTorch version of BERT available](https://github.com/huggingface/pytorch-pretrained-BERT)
1060
+ which is compatible with our pre-trained checkpoints and is able to reproduce
1061
+ our results. We were not involved in the creation or maintenance of the PyTorch
1062
+ implementation so please direct any questions towards the authors of that
1063
+ repository.
1064
+
1065
+ #### Is there a Chainer version available?
1066
+
1067
+ There is no official Chainer implementation. However, Sosuke Kobayashi made a
1068
+ [Chainer version of BERT available](https://github.com/soskek/bert-chainer)
1069
+ which is compatible with our pre-trained checkpoints and is able to reproduce
1070
+ our results. We were not involved in the creation or maintenance of the Chainer
1071
+ implementation so please direct any questions towards the authors of that
1072
+ repository.
1073
+
1074
+ #### Will models in other languages be released?
1075
+
1076
+ Yes, we plan to release a multi-lingual BERT model in the near future. We cannot
1077
+ make promises about exactly which languages will be included, but it will likely
1078
+ be a single model which includes *most* of the languages which have a
1079
+ significantly-sized Wikipedia.
1080
+
1081
+ #### Will models larger than `BERT-Large` be released?
1082
+
1083
+ So far we have not attempted to train anything larger than `BERT-Large`. It is
1084
+ possible that we will release larger models if we are able to obtain significant
1085
+ improvements.
1086
+
1087
+ #### What license is this library released under?
1088
+
1089
+ All code *and* models are released under the Apache 2.0 license. See the
1090
+ `LICENSE` file for more information.
1091
+
1092
+ #### How do I cite BERT?
1093
+
1094
+ For now, cite [the Arxiv paper](https://arxiv.org/abs/1810.04805):
1095
+
1096
+ ```
1097
+ @article{devlin2018bert,
1098
+ title={BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding},
1099
+ author={Devlin, Jacob and Chang, Ming-Wei and Lee, Kenton and Toutanova, Kristina},
1100
+ journal={arXiv preprint arXiv:1810.04805},
1101
+ year={2018}
1102
+ }
1103
+ ```
1104
+
1105
+ If we submit the paper to a conference or journal, we will update the BibTeX.
1106
+
1107
+ ## Disclaimer
1108
+
1109
+ This is not an official Google product.
1110
+
1111
+ ## Contact information
1112
+
1113
+ For help or issues using BERT, please submit a GitHub issue.
1114
+
1115
+ For personal communication related to BERT, please contact Jacob Devlin
1116
+ (`jacobdevlin@google.com`), Ming-Wei Chang (`mingweichang@google.com`), or
1117
+ Kenton Lee (`kentonl@google.com`).
bert-master/bert-master/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
bert-master/bert-master/create_pretraining_data.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Create masked LM/next sentence masked_lm TF examples for BERT."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import collections
22
+ import random
23
+ import tokenization
24
+ import tensorflow as tf
25
+
26
+ flags = tf.flags
27
+
28
+ FLAGS = flags.FLAGS
29
+
30
+ flags.DEFINE_string("input_file", None,
31
+ "Input raw text file (or comma-separated list of files).")
32
+
33
+ flags.DEFINE_string(
34
+ "output_file", None,
35
+ "Output TF example file (or comma-separated list of files).")
36
+
37
+ flags.DEFINE_string("vocab_file", None,
38
+ "The vocabulary file that the BERT model was trained on.")
39
+
40
+ flags.DEFINE_bool(
41
+ "do_lower_case", True,
42
+ "Whether to lower case the input text. Should be True for uncased "
43
+ "models and False for cased models.")
44
+
45
+ flags.DEFINE_bool(
46
+ "do_whole_word_mask", False,
47
+ "Whether to use whole word masking rather than per-WordPiece masking.")
48
+
49
+ flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.")
50
+
51
+ flags.DEFINE_integer("max_predictions_per_seq", 20,
52
+ "Maximum number of masked LM predictions per sequence.")
53
+
54
+ flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.")
55
+
56
+ flags.DEFINE_integer(
57
+ "dupe_factor", 10,
58
+ "Number of times to duplicate the input data (with different masks).")
59
+
60
+ flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.")
61
+
62
+ flags.DEFINE_float(
63
+ "short_seq_prob", 0.1,
64
+ "Probability of creating sequences which are shorter than the "
65
+ "maximum length.")
66
+
67
+
68
+ class TrainingInstance(object):
69
+ """A single training instance (sentence pair)."""
70
+
71
+ def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels,
72
+ is_random_next):
73
+ self.tokens = tokens
74
+ self.segment_ids = segment_ids
75
+ self.is_random_next = is_random_next
76
+ self.masked_lm_positions = masked_lm_positions
77
+ self.masked_lm_labels = masked_lm_labels
78
+
79
+ def __str__(self):
80
+ s = ""
81
+ s += "tokens: %s\n" % (" ".join(
82
+ [tokenization.printable_text(x) for x in self.tokens]))
83
+ s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids]))
84
+ s += "is_random_next: %s\n" % self.is_random_next
85
+ s += "masked_lm_positions: %s\n" % (" ".join(
86
+ [str(x) for x in self.masked_lm_positions]))
87
+ s += "masked_lm_labels: %s\n" % (" ".join(
88
+ [tokenization.printable_text(x) for x in self.masked_lm_labels]))
89
+ s += "\n"
90
+ return s
91
+
92
+ def __repr__(self):
93
+ return self.__str__()
94
+
95
+
96
+ def write_instance_to_example_files(instances, tokenizer, max_seq_length,
97
+ max_predictions_per_seq, output_files):
98
+ """Create TF example files from `TrainingInstance`s."""
99
+ writers = []
100
+ for output_file in output_files:
101
+ writers.append(tf.python_io.TFRecordWriter(output_file))
102
+
103
+ writer_index = 0
104
+
105
+ total_written = 0
106
+ for (inst_index, instance) in enumerate(instances):
107
+ input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
108
+ input_mask = [1] * len(input_ids)
109
+ segment_ids = list(instance.segment_ids)
110
+ assert len(input_ids) <= max_seq_length
111
+
112
+ while len(input_ids) < max_seq_length:
113
+ input_ids.append(0)
114
+ input_mask.append(0)
115
+ segment_ids.append(0)
116
+
117
+ assert len(input_ids) == max_seq_length
118
+ assert len(input_mask) == max_seq_length
119
+ assert len(segment_ids) == max_seq_length
120
+
121
+ masked_lm_positions = list(instance.masked_lm_positions)
122
+ masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels)
123
+ masked_lm_weights = [1.0] * len(masked_lm_ids)
124
+
125
+ while len(masked_lm_positions) < max_predictions_per_seq:
126
+ masked_lm_positions.append(0)
127
+ masked_lm_ids.append(0)
128
+ masked_lm_weights.append(0.0)
129
+
130
+ next_sentence_label = 1 if instance.is_random_next else 0
131
+
132
+ features = collections.OrderedDict()
133
+ features["input_ids"] = create_int_feature(input_ids)
134
+ features["input_mask"] = create_int_feature(input_mask)
135
+ features["segment_ids"] = create_int_feature(segment_ids)
136
+ features["masked_lm_positions"] = create_int_feature(masked_lm_positions)
137
+ features["masked_lm_ids"] = create_int_feature(masked_lm_ids)
138
+ features["masked_lm_weights"] = create_float_feature(masked_lm_weights)
139
+ features["next_sentence_labels"] = create_int_feature([next_sentence_label])
140
+
141
+ tf_example = tf.train.Example(features=tf.train.Features(feature=features))
142
+
143
+ writers[writer_index].write(tf_example.SerializeToString())
144
+ writer_index = (writer_index + 1) % len(writers)
145
+
146
+ total_written += 1
147
+
148
+ if inst_index < 20:
149
+ tf.logging.info("*** Example ***")
150
+ tf.logging.info("tokens: %s" % " ".join(
151
+ [tokenization.printable_text(x) for x in instance.tokens]))
152
+
153
+ for feature_name in features.keys():
154
+ feature = features[feature_name]
155
+ values = []
156
+ if feature.int64_list.value:
157
+ values = feature.int64_list.value
158
+ elif feature.float_list.value:
159
+ values = feature.float_list.value
160
+ tf.logging.info(
161
+ "%s: %s" % (feature_name, " ".join([str(x) for x in values])))
162
+
163
+ for writer in writers:
164
+ writer.close()
165
+
166
+ tf.logging.info("Wrote %d total instances", total_written)
167
+
168
+
169
+ def create_int_feature(values):
170
+ feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
171
+ return feature
172
+
173
+
174
+ def create_float_feature(values):
175
+ feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
176
+ return feature
177
+
178
+
179
+ def create_training_instances(input_files, tokenizer, max_seq_length,
180
+ dupe_factor, short_seq_prob, masked_lm_prob,
181
+ max_predictions_per_seq, rng):
182
+ """Create `TrainingInstance`s from raw text."""
183
+ all_documents = [[]]
184
+
185
+ # Input file format:
186
+ # (1) One sentence per line. These should ideally be actual sentences, not
187
+ # entire paragraphs or arbitrary spans of text. (Because we use the
188
+ # sentence boundaries for the "next sentence prediction" task).
189
+ # (2) Blank lines between documents. Document boundaries are needed so
190
+ # that the "next sentence prediction" task doesn't span between documents.
191
+ for input_file in input_files:
192
+ with tf.gfile.GFile(input_file, "r") as reader:
193
+ while True:
194
+ line = tokenization.convert_to_unicode(reader.readline())
195
+ if not line:
196
+ break
197
+ line = line.strip()
198
+
199
+ # Empty lines are used as document delimiters
200
+ if not line:
201
+ all_documents.append([])
202
+ tokens = tokenizer.tokenize(line)
203
+ if tokens:
204
+ all_documents[-1].append(tokens)
205
+
206
+ # Remove empty documents
207
+ all_documents = [x for x in all_documents if x]
208
+ rng.shuffle(all_documents)
209
+
210
+ vocab_words = list(tokenizer.vocab.keys())
211
+ instances = []
212
+ for _ in range(dupe_factor):
213
+ for document_index in range(len(all_documents)):
214
+ instances.extend(
215
+ create_instances_from_document(
216
+ all_documents, document_index, max_seq_length, short_seq_prob,
217
+ masked_lm_prob, max_predictions_per_seq, vocab_words, rng))
218
+
219
+ rng.shuffle(instances)
220
+ return instances
221
+
222
+
223
+ def create_instances_from_document(
224
+ all_documents, document_index, max_seq_length, short_seq_prob,
225
+ masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
226
+ """Creates `TrainingInstance`s for a single document."""
227
+ document = all_documents[document_index]
228
+
229
+ # Account for [CLS], [SEP], [SEP]
230
+ max_num_tokens = max_seq_length - 3
231
+
232
+ # We *usually* want to fill up the entire sequence since we are padding
233
+ # to `max_seq_length` anyways, so short sequences are generally wasted
234
+ # computation. However, we *sometimes*
235
+ # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
236
+ # sequences to minimize the mismatch between pre-training and fine-tuning.
237
+ # The `target_seq_length` is just a rough target however, whereas
238
+ # `max_seq_length` is a hard limit.
239
+ target_seq_length = max_num_tokens
240
+ if rng.random() < short_seq_prob:
241
+ target_seq_length = rng.randint(2, max_num_tokens)
242
+
243
+ # We DON'T just concatenate all of the tokens from a document into a long
244
+ # sequence and choose an arbitrary split point because this would make the
245
+ # next sentence prediction task too easy. Instead, we split the input into
246
+ # segments "A" and "B" based on the actual "sentences" provided by the user
247
+ # input.
248
+ instances = []
249
+ current_chunk = []
250
+ current_length = 0
251
+ i = 0
252
+ while i < len(document):
253
+ segment = document[i]
254
+ current_chunk.append(segment)
255
+ current_length += len(segment)
256
+ if i == len(document) - 1 or current_length >= target_seq_length:
257
+ if current_chunk:
258
+ # `a_end` is how many segments from `current_chunk` go into the `A`
259
+ # (first) sentence.
260
+ a_end = 1
261
+ if len(current_chunk) >= 2:
262
+ a_end = rng.randint(1, len(current_chunk) - 1)
263
+
264
+ tokens_a = []
265
+ for j in range(a_end):
266
+ tokens_a.extend(current_chunk[j])
267
+
268
+ tokens_b = []
269
+ # Random next
270
+ is_random_next = False
271
+ if len(current_chunk) == 1 or rng.random() < 0.5:
272
+ is_random_next = True
273
+ target_b_length = target_seq_length - len(tokens_a)
274
+
275
+ # This should rarely go for more than one iteration for large
276
+ # corpora. However, just to be careful, we try to make sure that
277
+ # the random document is not the same as the document
278
+ # we're processing.
279
+ for _ in range(10):
280
+ random_document_index = rng.randint(0, len(all_documents) - 1)
281
+ if random_document_index != document_index:
282
+ break
283
+
284
+ random_document = all_documents[random_document_index]
285
+ random_start = rng.randint(0, len(random_document) - 1)
286
+ for j in range(random_start, len(random_document)):
287
+ tokens_b.extend(random_document[j])
288
+ if len(tokens_b) >= target_b_length:
289
+ break
290
+ # We didn't actually use these segments so we "put them back" so
291
+ # they don't go to waste.
292
+ num_unused_segments = len(current_chunk) - a_end
293
+ i -= num_unused_segments
294
+ # Actual next
295
+ else:
296
+ is_random_next = False
297
+ for j in range(a_end, len(current_chunk)):
298
+ tokens_b.extend(current_chunk[j])
299
+ truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)
300
+
301
+ assert len(tokens_a) >= 1
302
+ assert len(tokens_b) >= 1
303
+
304
+ tokens = []
305
+ segment_ids = []
306
+ tokens.append("[CLS]")
307
+ segment_ids.append(0)
308
+ for token in tokens_a:
309
+ tokens.append(token)
310
+ segment_ids.append(0)
311
+
312
+ tokens.append("[SEP]")
313
+ segment_ids.append(0)
314
+
315
+ for token in tokens_b:
316
+ tokens.append(token)
317
+ segment_ids.append(1)
318
+ tokens.append("[SEP]")
319
+ segment_ids.append(1)
320
+
321
+ (tokens, masked_lm_positions,
322
+ masked_lm_labels) = create_masked_lm_predictions(
323
+ tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)
324
+ instance = TrainingInstance(
325
+ tokens=tokens,
326
+ segment_ids=segment_ids,
327
+ is_random_next=is_random_next,
328
+ masked_lm_positions=masked_lm_positions,
329
+ masked_lm_labels=masked_lm_labels)
330
+ instances.append(instance)
331
+ current_chunk = []
332
+ current_length = 0
333
+ i += 1
334
+
335
+ return instances
336
+
337
+
338
+ MaskedLmInstance = collections.namedtuple("MaskedLmInstance",
339
+ ["index", "label"])
340
+
341
+
342
+ def create_masked_lm_predictions(tokens, masked_lm_prob,
343
+ max_predictions_per_seq, vocab_words, rng):
344
+ """Creates the predictions for the masked LM objective."""
345
+
346
+ cand_indexes = []
347
+ for (i, token) in enumerate(tokens):
348
+ if token == "[CLS]" or token == "[SEP]":
349
+ continue
350
+ # Whole Word Masking means that if we mask all of the wordpieces
351
+ # corresponding to an original word. When a word has been split into
352
+ # WordPieces, the first token does not have any marker and any subsequence
353
+ # tokens are prefixed with ##. So whenever we see the ## token, we
354
+ # append it to the previous set of word indexes.
355
+ #
356
+ # Note that Whole Word Masking does *not* change the training code
357
+ # at all -- we still predict each WordPiece independently, softmaxed
358
+ # over the entire vocabulary.
359
+ if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and
360
+ token.startswith("##")):
361
+ cand_indexes[-1].append(i)
362
+ else:
363
+ cand_indexes.append([i])
364
+
365
+ rng.shuffle(cand_indexes)
366
+
367
+ output_tokens = list(tokens)
368
+
369
+ num_to_predict = min(max_predictions_per_seq,
370
+ max(1, int(round(len(tokens) * masked_lm_prob))))
371
+
372
+ masked_lms = []
373
+ covered_indexes = set()
374
+ for index_set in cand_indexes:
375
+ if len(masked_lms) >= num_to_predict:
376
+ break
377
+ # If adding a whole-word mask would exceed the maximum number of
378
+ # predictions, then just skip this candidate.
379
+ if len(masked_lms) + len(index_set) > num_to_predict:
380
+ continue
381
+ is_any_index_covered = False
382
+ for index in index_set:
383
+ if index in covered_indexes:
384
+ is_any_index_covered = True
385
+ break
386
+ if is_any_index_covered:
387
+ continue
388
+ for index in index_set:
389
+ covered_indexes.add(index)
390
+
391
+ masked_token = None
392
+ # 80% of the time, replace with [MASK]
393
+ if rng.random() < 0.8:
394
+ masked_token = "[MASK]"
395
+ else:
396
+ # 10% of the time, keep original
397
+ if rng.random() < 0.5:
398
+ masked_token = tokens[index]
399
+ # 10% of the time, replace with random word
400
+ else:
401
+ masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
402
+
403
+ output_tokens[index] = masked_token
404
+
405
+ masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))
406
+ assert len(masked_lms) <= num_to_predict
407
+ masked_lms = sorted(masked_lms, key=lambda x: x.index)
408
+
409
+ masked_lm_positions = []
410
+ masked_lm_labels = []
411
+ for p in masked_lms:
412
+ masked_lm_positions.append(p.index)
413
+ masked_lm_labels.append(p.label)
414
+
415
+ return (output_tokens, masked_lm_positions, masked_lm_labels)
416
+
417
+
418
+ def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
419
+ """Truncates a pair of sequences to a maximum sequence length."""
420
+ while True:
421
+ total_length = len(tokens_a) + len(tokens_b)
422
+ if total_length <= max_num_tokens:
423
+ break
424
+
425
+ trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
426
+ assert len(trunc_tokens) >= 1
427
+
428
+ # We want to sometimes truncate from the front and sometimes from the
429
+ # back to add more randomness and avoid biases.
430
+ if rng.random() < 0.5:
431
+ del trunc_tokens[0]
432
+ else:
433
+ trunc_tokens.pop()
434
+
435
+
436
+ def main(_):
437
+ tf.logging.set_verbosity(tf.logging.INFO)
438
+
439
+ tokenizer = tokenization.FullTokenizer(
440
+ vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
441
+
442
+ input_files = []
443
+ for input_pattern in FLAGS.input_file.split(","):
444
+ input_files.extend(tf.gfile.Glob(input_pattern))
445
+
446
+ tf.logging.info("*** Reading from input files ***")
447
+ for input_file in input_files:
448
+ tf.logging.info(" %s", input_file)
449
+
450
+ rng = random.Random(FLAGS.random_seed)
451
+ instances = create_training_instances(
452
+ input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,
453
+ FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq,
454
+ rng)
455
+
456
+ output_files = FLAGS.output_file.split(",")
457
+ tf.logging.info("*** Writing to output files ***")
458
+ for output_file in output_files:
459
+ tf.logging.info(" %s", output_file)
460
+
461
+ write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,
462
+ FLAGS.max_predictions_per_seq, output_files)
463
+
464
+
465
+ if __name__ == "__main__":
466
+ flags.mark_flag_as_required("input_file")
467
+ flags.mark_flag_as_required("output_file")
468
+ flags.mark_flag_as_required("vocab_file")
469
+ tf.app.run()
bert-master/bert-master/extract_features.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Extract pre-computed feature vectors from BERT."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import codecs
22
+ import collections
23
+ import json
24
+ import re
25
+
26
+ import modeling
27
+ import tokenization
28
+ import tensorflow as tf
29
+
30
+ flags = tf.flags
31
+
32
+ FLAGS = flags.FLAGS
33
+
34
+ flags.DEFINE_string("input_file", None, "")
35
+
36
+ flags.DEFINE_string("output_file", None, "")
37
+
38
+ flags.DEFINE_string("layers", "-1,-2,-3,-4", "")
39
+
40
+ flags.DEFINE_string(
41
+ "bert_config_file", None,
42
+ "The config json file corresponding to the pre-trained BERT model. "
43
+ "This specifies the model architecture.")
44
+
45
+ flags.DEFINE_integer(
46
+ "max_seq_length", 128,
47
+ "The maximum total input sequence length after WordPiece tokenization. "
48
+ "Sequences longer than this will be truncated, and sequences shorter "
49
+ "than this will be padded.")
50
+
51
+ flags.DEFINE_string(
52
+ "init_checkpoint", None,
53
+ "Initial checkpoint (usually from a pre-trained BERT model).")
54
+
55
+ flags.DEFINE_string("vocab_file", None,
56
+ "The vocabulary file that the BERT model was trained on.")
57
+
58
+ flags.DEFINE_bool(
59
+ "do_lower_case", True,
60
+ "Whether to lower case the input text. Should be True for uncased "
61
+ "models and False for cased models.")
62
+
63
+ flags.DEFINE_integer("batch_size", 32, "Batch size for predictions.")
64
+
65
+ flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
66
+
67
+ flags.DEFINE_string("master", None,
68
+ "If using a TPU, the address of the master.")
69
+
70
+ flags.DEFINE_integer(
71
+ "num_tpu_cores", 8,
72
+ "Only used if `use_tpu` is True. Total number of TPU cores to use.")
73
+
74
+ flags.DEFINE_bool(
75
+ "use_one_hot_embeddings", False,
76
+ "If True, tf.one_hot will be used for embedding lookups, otherwise "
77
+ "tf.nn.embedding_lookup will be used. On TPUs, this should be True "
78
+ "since it is much faster.")
79
+
80
+
81
+ class InputExample(object):
82
+
83
+ def __init__(self, unique_id, text_a, text_b):
84
+ self.unique_id = unique_id
85
+ self.text_a = text_a
86
+ self.text_b = text_b
87
+
88
+
89
+ class InputFeatures(object):
90
+ """A single set of features of data."""
91
+
92
+ def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
93
+ self.unique_id = unique_id
94
+ self.tokens = tokens
95
+ self.input_ids = input_ids
96
+ self.input_mask = input_mask
97
+ self.input_type_ids = input_type_ids
98
+
99
+
100
+ def input_fn_builder(features, seq_length):
101
+ """Creates an `input_fn` closure to be passed to TPUEstimator."""
102
+
103
+ all_unique_ids = []
104
+ all_input_ids = []
105
+ all_input_mask = []
106
+ all_input_type_ids = []
107
+
108
+ for feature in features:
109
+ all_unique_ids.append(feature.unique_id)
110
+ all_input_ids.append(feature.input_ids)
111
+ all_input_mask.append(feature.input_mask)
112
+ all_input_type_ids.append(feature.input_type_ids)
113
+
114
+ def input_fn(params):
115
+ """The actual input function."""
116
+ batch_size = params["batch_size"]
117
+
118
+ num_examples = len(features)
119
+
120
+ # This is for demo purposes and does NOT scale to large data sets. We do
121
+ # not use Dataset.from_generator() because that uses tf.py_func which is
122
+ # not TPU compatible. The right way to load data is with TFRecordReader.
123
+ d = tf.data.Dataset.from_tensor_slices({
124
+ "unique_ids":
125
+ tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32),
126
+ "input_ids":
127
+ tf.constant(
128
+ all_input_ids, shape=[num_examples, seq_length],
129
+ dtype=tf.int32),
130
+ "input_mask":
131
+ tf.constant(
132
+ all_input_mask,
133
+ shape=[num_examples, seq_length],
134
+ dtype=tf.int32),
135
+ "input_type_ids":
136
+ tf.constant(
137
+ all_input_type_ids,
138
+ shape=[num_examples, seq_length],
139
+ dtype=tf.int32),
140
+ })
141
+
142
+ d = d.batch(batch_size=batch_size, drop_remainder=False)
143
+ return d
144
+
145
+ return input_fn
146
+
147
+
148
+ def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu,
149
+ use_one_hot_embeddings):
150
+ """Returns `model_fn` closure for TPUEstimator."""
151
+
152
+ def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
153
+ """The `model_fn` for TPUEstimator."""
154
+
155
+ unique_ids = features["unique_ids"]
156
+ input_ids = features["input_ids"]
157
+ input_mask = features["input_mask"]
158
+ input_type_ids = features["input_type_ids"]
159
+
160
+ model = modeling.BertModel(
161
+ config=bert_config,
162
+ is_training=False,
163
+ input_ids=input_ids,
164
+ input_mask=input_mask,
165
+ token_type_ids=input_type_ids,
166
+ use_one_hot_embeddings=use_one_hot_embeddings)
167
+
168
+ if mode != tf.estimator.ModeKeys.PREDICT:
169
+ raise ValueError("Only PREDICT modes are supported: %s" % (mode))
170
+
171
+ tvars = tf.trainable_variables()
172
+ scaffold_fn = None
173
+ (assignment_map,
174
+ initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(
175
+ tvars, init_checkpoint)
176
+ if use_tpu:
177
+
178
+ def tpu_scaffold():
179
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
180
+ return tf.train.Scaffold()
181
+
182
+ scaffold_fn = tpu_scaffold
183
+ else:
184
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
185
+
186
+ tf.logging.info("**** Trainable Variables ****")
187
+ for var in tvars:
188
+ init_string = ""
189
+ if var.name in initialized_variable_names:
190
+ init_string = ", *INIT_FROM_CKPT*"
191
+ tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
192
+ init_string)
193
+
194
+ all_layers = model.get_all_encoder_layers()
195
+
196
+ predictions = {
197
+ "unique_id": unique_ids,
198
+ }
199
+
200
+ for (i, layer_index) in enumerate(layer_indexes):
201
+ predictions["layer_output_%d" % i] = all_layers[layer_index]
202
+
203
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
204
+ mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
205
+ return output_spec
206
+
207
+ return model_fn
208
+
209
+
210
+ def convert_examples_to_features(examples, seq_length, tokenizer):
211
+ """Loads a data file into a list of `InputBatch`s."""
212
+
213
+ features = []
214
+ for (ex_index, example) in enumerate(examples):
215
+ tokens_a = tokenizer.tokenize(example.text_a)
216
+
217
+ tokens_b = None
218
+ if example.text_b:
219
+ tokens_b = tokenizer.tokenize(example.text_b)
220
+
221
+ if tokens_b:
222
+ # Modifies `tokens_a` and `tokens_b` in place so that the total
223
+ # length is less than the specified length.
224
+ # Account for [CLS], [SEP], [SEP] with "- 3"
225
+ _truncate_seq_pair(tokens_a, tokens_b, seq_length - 3)
226
+ else:
227
+ # Account for [CLS] and [SEP] with "- 2"
228
+ if len(tokens_a) > seq_length - 2:
229
+ tokens_a = tokens_a[0:(seq_length - 2)]
230
+
231
+ # The convention in BERT is:
232
+ # (a) For sequence pairs:
233
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
234
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
235
+ # (b) For single sequences:
236
+ # tokens: [CLS] the dog is hairy . [SEP]
237
+ # type_ids: 0 0 0 0 0 0 0
238
+ #
239
+ # Where "type_ids" are used to indicate whether this is the first
240
+ # sequence or the second sequence. The embedding vectors for `type=0` and
241
+ # `type=1` were learned during pre-training and are added to the wordpiece
242
+ # embedding vector (and position vector). This is not *strictly* necessary
243
+ # since the [SEP] token unambiguously separates the sequences, but it makes
244
+ # it easier for the model to learn the concept of sequences.
245
+ #
246
+ # For classification tasks, the first vector (corresponding to [CLS]) is
247
+ # used as as the "sentence vector". Note that this only makes sense because
248
+ # the entire model is fine-tuned.
249
+ tokens = []
250
+ input_type_ids = []
251
+ tokens.append("[CLS]")
252
+ input_type_ids.append(0)
253
+ for token in tokens_a:
254
+ tokens.append(token)
255
+ input_type_ids.append(0)
256
+ tokens.append("[SEP]")
257
+ input_type_ids.append(0)
258
+
259
+ if tokens_b:
260
+ for token in tokens_b:
261
+ tokens.append(token)
262
+ input_type_ids.append(1)
263
+ tokens.append("[SEP]")
264
+ input_type_ids.append(1)
265
+
266
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
267
+
268
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
269
+ # tokens are attended to.
270
+ input_mask = [1] * len(input_ids)
271
+
272
+ # Zero-pad up to the sequence length.
273
+ while len(input_ids) < seq_length:
274
+ input_ids.append(0)
275
+ input_mask.append(0)
276
+ input_type_ids.append(0)
277
+
278
+ assert len(input_ids) == seq_length
279
+ assert len(input_mask) == seq_length
280
+ assert len(input_type_ids) == seq_length
281
+
282
+ if ex_index < 5:
283
+ tf.logging.info("*** Example ***")
284
+ tf.logging.info("unique_id: %s" % (example.unique_id))
285
+ tf.logging.info("tokens: %s" % " ".join(
286
+ [tokenization.printable_text(x) for x in tokens]))
287
+ tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
288
+ tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
289
+ tf.logging.info(
290
+ "input_type_ids: %s" % " ".join([str(x) for x in input_type_ids]))
291
+
292
+ features.append(
293
+ InputFeatures(
294
+ unique_id=example.unique_id,
295
+ tokens=tokens,
296
+ input_ids=input_ids,
297
+ input_mask=input_mask,
298
+ input_type_ids=input_type_ids))
299
+ return features
300
+
301
+
302
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
303
+ """Truncates a sequence pair in place to the maximum length."""
304
+
305
+ # This is a simple heuristic which will always truncate the longer sequence
306
+ # one token at a time. This makes more sense than truncating an equal percent
307
+ # of tokens from each, since if one sequence is very short then each token
308
+ # that's truncated likely contains more information than a longer sequence.
309
+ while True:
310
+ total_length = len(tokens_a) + len(tokens_b)
311
+ if total_length <= max_length:
312
+ break
313
+ if len(tokens_a) > len(tokens_b):
314
+ tokens_a.pop()
315
+ else:
316
+ tokens_b.pop()
317
+
318
+
319
+ def read_examples(input_file):
320
+ """Read a list of `InputExample`s from an input file."""
321
+ examples = []
322
+ unique_id = 0
323
+ with tf.gfile.GFile(input_file, "r") as reader:
324
+ while True:
325
+ line = tokenization.convert_to_unicode(reader.readline())
326
+ if not line:
327
+ break
328
+ line = line.strip()
329
+ text_a = None
330
+ text_b = None
331
+ m = re.match(r"^(.*) \|\|\| (.*)$", line)
332
+ if m is None:
333
+ text_a = line
334
+ else:
335
+ text_a = m.group(1)
336
+ text_b = m.group(2)
337
+ examples.append(
338
+ InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
339
+ unique_id += 1
340
+ return examples
341
+
342
+
343
+ def main(_):
344
+ tf.logging.set_verbosity(tf.logging.INFO)
345
+
346
+ layer_indexes = [int(x) for x in FLAGS.layers.split(",")]
347
+
348
+ bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
349
+
350
+ tokenizer = tokenization.FullTokenizer(
351
+ vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
352
+
353
+ is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
354
+ run_config = tf.contrib.tpu.RunConfig(
355
+ master=FLAGS.master,
356
+ tpu_config=tf.contrib.tpu.TPUConfig(
357
+ num_shards=FLAGS.num_tpu_cores,
358
+ per_host_input_for_training=is_per_host))
359
+
360
+ examples = read_examples(FLAGS.input_file)
361
+
362
+ features = convert_examples_to_features(
363
+ examples=examples, seq_length=FLAGS.max_seq_length, tokenizer=tokenizer)
364
+
365
+ unique_id_to_feature = {}
366
+ for feature in features:
367
+ unique_id_to_feature[feature.unique_id] = feature
368
+
369
+ model_fn = model_fn_builder(
370
+ bert_config=bert_config,
371
+ init_checkpoint=FLAGS.init_checkpoint,
372
+ layer_indexes=layer_indexes,
373
+ use_tpu=FLAGS.use_tpu,
374
+ use_one_hot_embeddings=FLAGS.use_one_hot_embeddings)
375
+
376
+ # If TPU is not available, this will fall back to normal Estimator on CPU
377
+ # or GPU.
378
+ estimator = tf.contrib.tpu.TPUEstimator(
379
+ use_tpu=FLAGS.use_tpu,
380
+ model_fn=model_fn,
381
+ config=run_config,
382
+ predict_batch_size=FLAGS.batch_size)
383
+
384
+ input_fn = input_fn_builder(
385
+ features=features, seq_length=FLAGS.max_seq_length)
386
+
387
+ with codecs.getwriter("utf-8")(tf.gfile.Open(FLAGS.output_file,
388
+ "w")) as writer:
389
+ for result in estimator.predict(input_fn, yield_single_examples=True):
390
+ unique_id = int(result["unique_id"])
391
+ feature = unique_id_to_feature[unique_id]
392
+ output_json = collections.OrderedDict()
393
+ output_json["linex_index"] = unique_id
394
+ all_features = []
395
+ for (i, token) in enumerate(feature.tokens):
396
+ all_layers = []
397
+ for (j, layer_index) in enumerate(layer_indexes):
398
+ layer_output = result["layer_output_%d" % j]
399
+ layers = collections.OrderedDict()
400
+ layers["index"] = layer_index
401
+ layers["values"] = [
402
+ round(float(x), 6) for x in layer_output[i:(i + 1)].flat
403
+ ]
404
+ all_layers.append(layers)
405
+ features = collections.OrderedDict()
406
+ features["token"] = token
407
+ features["layers"] = all_layers
408
+ all_features.append(features)
409
+ output_json["features"] = all_features
410
+ writer.write(json.dumps(output_json) + "\n")
411
+
412
+
413
+ if __name__ == "__main__":
414
+ flags.mark_flag_as_required("input_file")
415
+ flags.mark_flag_as_required("vocab_file")
416
+ flags.mark_flag_as_required("bert_config_file")
417
+ flags.mark_flag_as_required("init_checkpoint")
418
+ flags.mark_flag_as_required("output_file")
419
+ tf.app.run()
bert-master/bert-master/modeling.py ADDED
@@ -0,0 +1,986 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """The main BERT model and related functions."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import collections
22
+ import copy
23
+ import json
24
+ import math
25
+ import re
26
+ import numpy as np
27
+ import six
28
+ import tensorflow as tf
29
+
30
+
31
+ class BertConfig(object):
32
+ """Configuration for `BertModel`."""
33
+
34
+ def __init__(self,
35
+ vocab_size,
36
+ hidden_size=768,
37
+ num_hidden_layers=12,
38
+ num_attention_heads=12,
39
+ intermediate_size=3072,
40
+ hidden_act="gelu",
41
+ hidden_dropout_prob=0.1,
42
+ attention_probs_dropout_prob=0.1,
43
+ max_position_embeddings=512,
44
+ type_vocab_size=16,
45
+ initializer_range=0.02):
46
+ """Constructs BertConfig.
47
+
48
+ Args:
49
+ vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
50
+ hidden_size: Size of the encoder layers and the pooler layer.
51
+ num_hidden_layers: Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads: Number of attention heads for each attention layer in
53
+ the Transformer encoder.
54
+ intermediate_size: The size of the "intermediate" (i.e., feed-forward)
55
+ layer in the Transformer encoder.
56
+ hidden_act: The non-linear activation function (function or string) in the
57
+ encoder and pooler.
58
+ hidden_dropout_prob: The dropout probability for all fully connected
59
+ layers in the embeddings, encoder, and pooler.
60
+ attention_probs_dropout_prob: The dropout ratio for the attention
61
+ probabilities.
62
+ max_position_embeddings: The maximum sequence length that this model might
63
+ ever be used with. Typically set this to something large just in case
64
+ (e.g., 512 or 1024 or 2048).
65
+ type_vocab_size: The vocabulary size of the `token_type_ids` passed into
66
+ `BertModel`.
67
+ initializer_range: The stdev of the truncated_normal_initializer for
68
+ initializing all weight matrices.
69
+ """
70
+ self.vocab_size = vocab_size
71
+ self.hidden_size = hidden_size
72
+ self.num_hidden_layers = num_hidden_layers
73
+ self.num_attention_heads = num_attention_heads
74
+ self.hidden_act = hidden_act
75
+ self.intermediate_size = intermediate_size
76
+ self.hidden_dropout_prob = hidden_dropout_prob
77
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
78
+ self.max_position_embeddings = max_position_embeddings
79
+ self.type_vocab_size = type_vocab_size
80
+ self.initializer_range = initializer_range
81
+
82
+ @classmethod
83
+ def from_dict(cls, json_object):
84
+ """Constructs a `BertConfig` from a Python dictionary of parameters."""
85
+ config = BertConfig(vocab_size=None)
86
+ for (key, value) in six.iteritems(json_object):
87
+ config.__dict__[key] = value
88
+ return config
89
+
90
+ @classmethod
91
+ def from_json_file(cls, json_file):
92
+ """Constructs a `BertConfig` from a json file of parameters."""
93
+ with tf.gfile.GFile(json_file, "r") as reader:
94
+ text = reader.read()
95
+ return cls.from_dict(json.loads(text))
96
+
97
+ def to_dict(self):
98
+ """Serializes this instance to a Python dictionary."""
99
+ output = copy.deepcopy(self.__dict__)
100
+ return output
101
+
102
+ def to_json_string(self):
103
+ """Serializes this instance to a JSON string."""
104
+ return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
105
+
106
+
107
+ class BertModel(object):
108
+ """BERT model ("Bidirectional Encoder Representations from Transformers").
109
+
110
+ Example usage:
111
+
112
+ ```python
113
+ # Already been converted into WordPiece token ids
114
+ input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
115
+ input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
116
+ token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])
117
+
118
+ config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
119
+ num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
120
+
121
+ model = modeling.BertModel(config=config, is_training=True,
122
+ input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
123
+
124
+ label_embeddings = tf.get_variable(...)
125
+ pooled_output = model.get_pooled_output()
126
+ logits = tf.matmul(pooled_output, label_embeddings)
127
+ ...
128
+ ```
129
+ """
130
+
131
+ def __init__(self,
132
+ config,
133
+ is_training,
134
+ input_ids,
135
+ input_mask=None,
136
+ token_type_ids=None,
137
+ use_one_hot_embeddings=False,
138
+ scope=None):
139
+ """Constructor for BertModel.
140
+
141
+ Args:
142
+ config: `BertConfig` instance.
143
+ is_training: bool. true for training model, false for eval model. Controls
144
+ whether dropout will be applied.
145
+ input_ids: int32 Tensor of shape [batch_size, seq_length].
146
+ input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].
147
+ token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
148
+ use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
149
+ embeddings or tf.embedding_lookup() for the word embeddings.
150
+ scope: (optional) variable scope. Defaults to "bert".
151
+
152
+ Raises:
153
+ ValueError: The config is invalid or one of the input tensor shapes
154
+ is invalid.
155
+ """
156
+ config = copy.deepcopy(config)
157
+ if not is_training:
158
+ config.hidden_dropout_prob = 0.0
159
+ config.attention_probs_dropout_prob = 0.0
160
+
161
+ input_shape = get_shape_list(input_ids, expected_rank=2)
162
+ batch_size = input_shape[0]
163
+ seq_length = input_shape[1]
164
+
165
+ if input_mask is None:
166
+ input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)
167
+
168
+ if token_type_ids is None:
169
+ token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)
170
+
171
+ with tf.variable_scope(scope, default_name="bert"):
172
+ with tf.variable_scope("embeddings"):
173
+ # Perform embedding lookup on the word ids.
174
+ (self.embedding_output, self.embedding_table) = embedding_lookup(
175
+ input_ids=input_ids,
176
+ vocab_size=config.vocab_size,
177
+ embedding_size=config.hidden_size,
178
+ initializer_range=config.initializer_range,
179
+ word_embedding_name="word_embeddings",
180
+ use_one_hot_embeddings=use_one_hot_embeddings)
181
+
182
+ # Add positional embeddings and token type embeddings, then layer
183
+ # normalize and perform dropout.
184
+ self.embedding_output = embedding_postprocessor(
185
+ input_tensor=self.embedding_output,
186
+ use_token_type=True,
187
+ token_type_ids=token_type_ids,
188
+ token_type_vocab_size=config.type_vocab_size,
189
+ token_type_embedding_name="token_type_embeddings",
190
+ use_position_embeddings=True,
191
+ position_embedding_name="position_embeddings",
192
+ initializer_range=config.initializer_range,
193
+ max_position_embeddings=config.max_position_embeddings,
194
+ dropout_prob=config.hidden_dropout_prob)
195
+
196
+ with tf.variable_scope("encoder"):
197
+ # This converts a 2D mask of shape [batch_size, seq_length] to a 3D
198
+ # mask of shape [batch_size, seq_length, seq_length] which is used
199
+ # for the attention scores.
200
+ attention_mask = create_attention_mask_from_input_mask(
201
+ input_ids, input_mask)
202
+
203
+ # Run the stacked transformer.
204
+ # `sequence_output` shape = [batch_size, seq_length, hidden_size].
205
+ self.all_encoder_layers = transformer_model(
206
+ input_tensor=self.embedding_output,
207
+ attention_mask=attention_mask,
208
+ hidden_size=config.hidden_size,
209
+ num_hidden_layers=config.num_hidden_layers,
210
+ num_attention_heads=config.num_attention_heads,
211
+ intermediate_size=config.intermediate_size,
212
+ intermediate_act_fn=get_activation(config.hidden_act),
213
+ hidden_dropout_prob=config.hidden_dropout_prob,
214
+ attention_probs_dropout_prob=config.attention_probs_dropout_prob,
215
+ initializer_range=config.initializer_range,
216
+ do_return_all_layers=True)
217
+
218
+ self.sequence_output = self.all_encoder_layers[-1]
219
+ # The "pooler" converts the encoded sequence tensor of shape
220
+ # [batch_size, seq_length, hidden_size] to a tensor of shape
221
+ # [batch_size, hidden_size]. This is necessary for segment-level
222
+ # (or segment-pair-level) classification tasks where we need a fixed
223
+ # dimensional representation of the segment.
224
+ with tf.variable_scope("pooler"):
225
+ # We "pool" the model by simply taking the hidden state corresponding
226
+ # to the first token. We assume that this has been pre-trained
227
+ first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
228
+ self.pooled_output = tf.layers.dense(
229
+ first_token_tensor,
230
+ config.hidden_size,
231
+ activation=tf.tanh,
232
+ kernel_initializer=create_initializer(config.initializer_range))
233
+
234
+ def get_pooled_output(self):
235
+ return self.pooled_output
236
+
237
+ def get_sequence_output(self):
238
+ """Gets final hidden layer of encoder.
239
+
240
+ Returns:
241
+ float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
242
+ to the final hidden of the transformer encoder.
243
+ """
244
+ return self.sequence_output
245
+
246
+ def get_all_encoder_layers(self):
247
+ return self.all_encoder_layers
248
+
249
+ def get_embedding_output(self):
250
+ """Gets output of the embedding lookup (i.e., input to the transformer).
251
+
252
+ Returns:
253
+ float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
254
+ to the output of the embedding layer, after summing the word
255
+ embeddings with the positional embeddings and the token type embeddings,
256
+ then performing layer normalization. This is the input to the transformer.
257
+ """
258
+ return self.embedding_output
259
+
260
+ def get_embedding_table(self):
261
+ return self.embedding_table
262
+
263
+
264
+ def gelu(x):
265
+ """Gaussian Error Linear Unit.
266
+
267
+ This is a smoother version of the RELU.
268
+ Original paper: https://arxiv.org/abs/1606.08415
269
+ Args:
270
+ x: float Tensor to perform activation.
271
+
272
+ Returns:
273
+ `x` with the GELU activation applied.
274
+ """
275
+ cdf = 0.5 * (1.0 + tf.tanh(
276
+ (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
277
+ return x * cdf
278
+
279
+
280
+ def get_activation(activation_string):
281
+ """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
282
+
283
+ Args:
284
+ activation_string: String name of the activation function.
285
+
286
+ Returns:
287
+ A Python function corresponding to the activation function. If
288
+ `activation_string` is None, empty, or "linear", this will return None.
289
+ If `activation_string` is not a string, it will return `activation_string`.
290
+
291
+ Raises:
292
+ ValueError: The `activation_string` does not correspond to a known
293
+ activation.
294
+ """
295
+
296
+ # We assume that anything that"s not a string is already an activation
297
+ # function, so we just return it.
298
+ if not isinstance(activation_string, six.string_types):
299
+ return activation_string
300
+
301
+ if not activation_string:
302
+ return None
303
+
304
+ act = activation_string.lower()
305
+ if act == "linear":
306
+ return None
307
+ elif act == "relu":
308
+ return tf.nn.relu
309
+ elif act == "gelu":
310
+ return gelu
311
+ elif act == "tanh":
312
+ return tf.tanh
313
+ else:
314
+ raise ValueError("Unsupported activation: %s" % act)
315
+
316
+
317
+ def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
318
+ """Compute the union of the current variables and checkpoint variables."""
319
+ assignment_map = {}
320
+ initialized_variable_names = {}
321
+
322
+ name_to_variable = collections.OrderedDict()
323
+ for var in tvars:
324
+ name = var.name
325
+ m = re.match("^(.*):\\d+$", name)
326
+ if m is not None:
327
+ name = m.group(1)
328
+ name_to_variable[name] = var
329
+
330
+ init_vars = tf.train.list_variables(init_checkpoint)
331
+
332
+ assignment_map = collections.OrderedDict()
333
+ for x in init_vars:
334
+ (name, var) = (x[0], x[1])
335
+ if name not in name_to_variable:
336
+ continue
337
+ assignment_map[name] = name
338
+ initialized_variable_names[name] = 1
339
+ initialized_variable_names[name + ":0"] = 1
340
+
341
+ return (assignment_map, initialized_variable_names)
342
+
343
+
344
+ def dropout(input_tensor, dropout_prob):
345
+ """Perform dropout.
346
+
347
+ Args:
348
+ input_tensor: float Tensor.
349
+ dropout_prob: Python float. The probability of dropping out a value (NOT of
350
+ *keeping* a dimension as in `tf.nn.dropout`).
351
+
352
+ Returns:
353
+ A version of `input_tensor` with dropout applied.
354
+ """
355
+ if dropout_prob is None or dropout_prob == 0.0:
356
+ return input_tensor
357
+
358
+ output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
359
+ return output
360
+
361
+
362
+ def layer_norm(input_tensor, name=None):
363
+ """Run layer normalization on the last dimension of the tensor."""
364
+ return tf.contrib.layers.layer_norm(
365
+ inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
366
+
367
+
368
+ def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
369
+ """Runs layer normalization followed by dropout."""
370
+ output_tensor = layer_norm(input_tensor, name)
371
+ output_tensor = dropout(output_tensor, dropout_prob)
372
+ return output_tensor
373
+
374
+
375
+ def create_initializer(initializer_range=0.02):
376
+ """Creates a `truncated_normal_initializer` with the given range."""
377
+ return tf.truncated_normal_initializer(stddev=initializer_range)
378
+
379
+
380
+ def embedding_lookup(input_ids,
381
+ vocab_size,
382
+ embedding_size=128,
383
+ initializer_range=0.02,
384
+ word_embedding_name="word_embeddings",
385
+ use_one_hot_embeddings=False):
386
+ """Looks up words embeddings for id tensor.
387
+
388
+ Args:
389
+ input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
390
+ ids.
391
+ vocab_size: int. Size of the embedding vocabulary.
392
+ embedding_size: int. Width of the word embeddings.
393
+ initializer_range: float. Embedding initialization range.
394
+ word_embedding_name: string. Name of the embedding table.
395
+ use_one_hot_embeddings: bool. If True, use one-hot method for word
396
+ embeddings. If False, use `tf.gather()`.
397
+
398
+ Returns:
399
+ float Tensor of shape [batch_size, seq_length, embedding_size].
400
+ """
401
+ # This function assumes that the input is of shape [batch_size, seq_length,
402
+ # num_inputs].
403
+ #
404
+ # If the input is a 2D tensor of shape [batch_size, seq_length], we
405
+ # reshape to [batch_size, seq_length, 1].
406
+ if input_ids.shape.ndims == 2:
407
+ input_ids = tf.expand_dims(input_ids, axis=[-1])
408
+
409
+ embedding_table = tf.get_variable(
410
+ name=word_embedding_name,
411
+ shape=[vocab_size, embedding_size],
412
+ initializer=create_initializer(initializer_range))
413
+
414
+ flat_input_ids = tf.reshape(input_ids, [-1])
415
+ if use_one_hot_embeddings:
416
+ one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
417
+ output = tf.matmul(one_hot_input_ids, embedding_table)
418
+ else:
419
+ output = tf.gather(embedding_table, flat_input_ids)
420
+
421
+ input_shape = get_shape_list(input_ids)
422
+
423
+ output = tf.reshape(output,
424
+ input_shape[0:-1] + [input_shape[-1] * embedding_size])
425
+ return (output, embedding_table)
426
+
427
+
428
+ def embedding_postprocessor(input_tensor,
429
+ use_token_type=False,
430
+ token_type_ids=None,
431
+ token_type_vocab_size=16,
432
+ token_type_embedding_name="token_type_embeddings",
433
+ use_position_embeddings=True,
434
+ position_embedding_name="position_embeddings",
435
+ initializer_range=0.02,
436
+ max_position_embeddings=512,
437
+ dropout_prob=0.1):
438
+ """Performs various post-processing on a word embedding tensor.
439
+
440
+ Args:
441
+ input_tensor: float Tensor of shape [batch_size, seq_length,
442
+ embedding_size].
443
+ use_token_type: bool. Whether to add embeddings for `token_type_ids`.
444
+ token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
445
+ Must be specified if `use_token_type` is True.
446
+ token_type_vocab_size: int. The vocabulary size of `token_type_ids`.
447
+ token_type_embedding_name: string. The name of the embedding table variable
448
+ for token type ids.
449
+ use_position_embeddings: bool. Whether to add position embeddings for the
450
+ position of each token in the sequence.
451
+ position_embedding_name: string. The name of the embedding table variable
452
+ for positional embeddings.
453
+ initializer_range: float. Range of the weight initialization.
454
+ max_position_embeddings: int. Maximum sequence length that might ever be
455
+ used with this model. This can be longer than the sequence length of
456
+ input_tensor, but cannot be shorter.
457
+ dropout_prob: float. Dropout probability applied to the final output tensor.
458
+
459
+ Returns:
460
+ float tensor with same shape as `input_tensor`.
461
+
462
+ Raises:
463
+ ValueError: One of the tensor shapes or input values is invalid.
464
+ """
465
+ input_shape = get_shape_list(input_tensor, expected_rank=3)
466
+ batch_size = input_shape[0]
467
+ seq_length = input_shape[1]
468
+ width = input_shape[2]
469
+
470
+ output = input_tensor
471
+
472
+ if use_token_type:
473
+ if token_type_ids is None:
474
+ raise ValueError("`token_type_ids` must be specified if"
475
+ "`use_token_type` is True.")
476
+ token_type_table = tf.get_variable(
477
+ name=token_type_embedding_name,
478
+ shape=[token_type_vocab_size, width],
479
+ initializer=create_initializer(initializer_range))
480
+ # This vocab will be small so we always do one-hot here, since it is always
481
+ # faster for a small vocabulary.
482
+ flat_token_type_ids = tf.reshape(token_type_ids, [-1])
483
+ one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
484
+ token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
485
+ token_type_embeddings = tf.reshape(token_type_embeddings,
486
+ [batch_size, seq_length, width])
487
+ output += token_type_embeddings
488
+
489
+ if use_position_embeddings:
490
+ assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)
491
+ with tf.control_dependencies([assert_op]):
492
+ full_position_embeddings = tf.get_variable(
493
+ name=position_embedding_name,
494
+ shape=[max_position_embeddings, width],
495
+ initializer=create_initializer(initializer_range))
496
+ # Since the position embedding table is a learned variable, we create it
497
+ # using a (long) sequence length `max_position_embeddings`. The actual
498
+ # sequence length might be shorter than this, for faster training of
499
+ # tasks that do not have long sequences.
500
+ #
501
+ # So `full_position_embeddings` is effectively an embedding table
502
+ # for position [0, 1, 2, ..., max_position_embeddings-1], and the current
503
+ # sequence has positions [0, 1, 2, ... seq_length-1], so we can just
504
+ # perform a slice.
505
+ position_embeddings = tf.slice(full_position_embeddings, [0, 0],
506
+ [seq_length, -1])
507
+ num_dims = len(output.shape.as_list())
508
+
509
+ # Only the last two dimensions are relevant (`seq_length` and `width`), so
510
+ # we broadcast among the first dimensions, which is typically just
511
+ # the batch size.
512
+ position_broadcast_shape = []
513
+ for _ in range(num_dims - 2):
514
+ position_broadcast_shape.append(1)
515
+ position_broadcast_shape.extend([seq_length, width])
516
+ position_embeddings = tf.reshape(position_embeddings,
517
+ position_broadcast_shape)
518
+ output += position_embeddings
519
+
520
+ output = layer_norm_and_dropout(output, dropout_prob)
521
+ return output
522
+
523
+
524
+ def create_attention_mask_from_input_mask(from_tensor, to_mask):
525
+ """Create 3D attention mask from a 2D tensor mask.
526
+
527
+ Args:
528
+ from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
529
+ to_mask: int32 Tensor of shape [batch_size, to_seq_length].
530
+
531
+ Returns:
532
+ float Tensor of shape [batch_size, from_seq_length, to_seq_length].
533
+ """
534
+ from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
535
+ batch_size = from_shape[0]
536
+ from_seq_length = from_shape[1]
537
+
538
+ to_shape = get_shape_list(to_mask, expected_rank=2)
539
+ to_seq_length = to_shape[1]
540
+
541
+ to_mask = tf.cast(
542
+ tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)
543
+
544
+ # We don't assume that `from_tensor` is a mask (although it could be). We
545
+ # don't actually care if we attend *from* padding tokens (only *to* padding)
546
+ # tokens so we create a tensor of all ones.
547
+ #
548
+ # `broadcast_ones` = [batch_size, from_seq_length, 1]
549
+ broadcast_ones = tf.ones(
550
+ shape=[batch_size, from_seq_length, 1], dtype=tf.float32)
551
+
552
+ # Here we broadcast along two dimensions to create the mask.
553
+ mask = broadcast_ones * to_mask
554
+
555
+ return mask
556
+
557
+
558
+ def attention_layer(from_tensor,
559
+ to_tensor,
560
+ attention_mask=None,
561
+ num_attention_heads=1,
562
+ size_per_head=512,
563
+ query_act=None,
564
+ key_act=None,
565
+ value_act=None,
566
+ attention_probs_dropout_prob=0.0,
567
+ initializer_range=0.02,
568
+ do_return_2d_tensor=False,
569
+ batch_size=None,
570
+ from_seq_length=None,
571
+ to_seq_length=None):
572
+ """Performs multi-headed attention from `from_tensor` to `to_tensor`.
573
+
574
+ This is an implementation of multi-headed attention based on "Attention
575
+ is all you Need". If `from_tensor` and `to_tensor` are the same, then
576
+ this is self-attention. Each timestep in `from_tensor` attends to the
577
+ corresponding sequence in `to_tensor`, and returns a fixed-with vector.
578
+
579
+ This function first projects `from_tensor` into a "query" tensor and
580
+ `to_tensor` into "key" and "value" tensors. These are (effectively) a list
581
+ of tensors of length `num_attention_heads`, where each tensor is of shape
582
+ [batch_size, seq_length, size_per_head].
583
+
584
+ Then, the query and key tensors are dot-producted and scaled. These are
585
+ softmaxed to obtain attention probabilities. The value tensors are then
586
+ interpolated by these probabilities, then concatenated back to a single
587
+ tensor and returned.
588
+
589
+ In practice, the multi-headed attention are done with transposes and
590
+ reshapes rather than actual separate tensors.
591
+
592
+ Args:
593
+ from_tensor: float Tensor of shape [batch_size, from_seq_length,
594
+ from_width].
595
+ to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
596
+ attention_mask: (optional) int32 Tensor of shape [batch_size,
597
+ from_seq_length, to_seq_length]. The values should be 1 or 0. The
598
+ attention scores will effectively be set to -infinity for any positions in
599
+ the mask that are 0, and will be unchanged for positions that are 1.
600
+ num_attention_heads: int. Number of attention heads.
601
+ size_per_head: int. Size of each attention head.
602
+ query_act: (optional) Activation function for the query transform.
603
+ key_act: (optional) Activation function for the key transform.
604
+ value_act: (optional) Activation function for the value transform.
605
+ attention_probs_dropout_prob: (optional) float. Dropout probability of the
606
+ attention probabilities.
607
+ initializer_range: float. Range of the weight initializer.
608
+ do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
609
+ * from_seq_length, num_attention_heads * size_per_head]. If False, the
610
+ output will be of shape [batch_size, from_seq_length, num_attention_heads
611
+ * size_per_head].
612
+ batch_size: (Optional) int. If the input is 2D, this might be the batch size
613
+ of the 3D version of the `from_tensor` and `to_tensor`.
614
+ from_seq_length: (Optional) If the input is 2D, this might be the seq length
615
+ of the 3D version of the `from_tensor`.
616
+ to_seq_length: (Optional) If the input is 2D, this might be the seq length
617
+ of the 3D version of the `to_tensor`.
618
+
619
+ Returns:
620
+ float Tensor of shape [batch_size, from_seq_length,
621
+ num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
622
+ true, this will be of shape [batch_size * from_seq_length,
623
+ num_attention_heads * size_per_head]).
624
+
625
+ Raises:
626
+ ValueError: Any of the arguments or tensor shapes are invalid.
627
+ """
628
+
629
+ def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
630
+ seq_length, width):
631
+ output_tensor = tf.reshape(
632
+ input_tensor, [batch_size, seq_length, num_attention_heads, width])
633
+
634
+ output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
635
+ return output_tensor
636
+
637
+ from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
638
+ to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
639
+
640
+ if len(from_shape) != len(to_shape):
641
+ raise ValueError(
642
+ "The rank of `from_tensor` must match the rank of `to_tensor`.")
643
+
644
+ if len(from_shape) == 3:
645
+ batch_size = from_shape[0]
646
+ from_seq_length = from_shape[1]
647
+ to_seq_length = to_shape[1]
648
+ elif len(from_shape) == 2:
649
+ if (batch_size is None or from_seq_length is None or to_seq_length is None):
650
+ raise ValueError(
651
+ "When passing in rank 2 tensors to attention_layer, the values "
652
+ "for `batch_size`, `from_seq_length`, and `to_seq_length` "
653
+ "must all be specified.")
654
+
655
+ # Scalar dimensions referenced here:
656
+ # B = batch size (number of sequences)
657
+ # F = `from_tensor` sequence length
658
+ # T = `to_tensor` sequence length
659
+ # N = `num_attention_heads`
660
+ # H = `size_per_head`
661
+
662
+ from_tensor_2d = reshape_to_matrix(from_tensor)
663
+ to_tensor_2d = reshape_to_matrix(to_tensor)
664
+
665
+ # `query_layer` = [B*F, N*H]
666
+ query_layer = tf.layers.dense(
667
+ from_tensor_2d,
668
+ num_attention_heads * size_per_head,
669
+ activation=query_act,
670
+ name="query",
671
+ kernel_initializer=create_initializer(initializer_range))
672
+
673
+ # `key_layer` = [B*T, N*H]
674
+ key_layer = tf.layers.dense(
675
+ to_tensor_2d,
676
+ num_attention_heads * size_per_head,
677
+ activation=key_act,
678
+ name="key",
679
+ kernel_initializer=create_initializer(initializer_range))
680
+
681
+ # `value_layer` = [B*T, N*H]
682
+ value_layer = tf.layers.dense(
683
+ to_tensor_2d,
684
+ num_attention_heads * size_per_head,
685
+ activation=value_act,
686
+ name="value",
687
+ kernel_initializer=create_initializer(initializer_range))
688
+
689
+ # `query_layer` = [B, N, F, H]
690
+ query_layer = transpose_for_scores(query_layer, batch_size,
691
+ num_attention_heads, from_seq_length,
692
+ size_per_head)
693
+
694
+ # `key_layer` = [B, N, T, H]
695
+ key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
696
+ to_seq_length, size_per_head)
697
+
698
+ # Take the dot product between "query" and "key" to get the raw
699
+ # attention scores.
700
+ # `attention_scores` = [B, N, F, T]
701
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
702
+ attention_scores = tf.multiply(attention_scores,
703
+ 1.0 / math.sqrt(float(size_per_head)))
704
+
705
+ if attention_mask is not None:
706
+ # `attention_mask` = [B, 1, F, T]
707
+ attention_mask = tf.expand_dims(attention_mask, axis=[1])
708
+
709
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
710
+ # masked positions, this operation will create a tensor which is 0.0 for
711
+ # positions we want to attend and -10000.0 for masked positions.
712
+ adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0
713
+
714
+ # Since we are adding it to the raw scores before the softmax, this is
715
+ # effectively the same as removing these entirely.
716
+ attention_scores += adder
717
+
718
+ # Normalize the attention scores to probabilities.
719
+ # `attention_probs` = [B, N, F, T]
720
+ attention_probs = tf.nn.softmax(attention_scores)
721
+
722
+ # This is actually dropping out entire tokens to attend to, which might
723
+ # seem a bit unusual, but is taken from the original Transformer paper.
724
+ attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
725
+
726
+ # `value_layer` = [B, T, N, H]
727
+ value_layer = tf.reshape(
728
+ value_layer,
729
+ [batch_size, to_seq_length, num_attention_heads, size_per_head])
730
+
731
+ # `value_layer` = [B, N, T, H]
732
+ value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
733
+
734
+ # `context_layer` = [B, N, F, H]
735
+ context_layer = tf.matmul(attention_probs, value_layer)
736
+
737
+ # `context_layer` = [B, F, N, H]
738
+ context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
739
+
740
+ if do_return_2d_tensor:
741
+ # `context_layer` = [B*F, N*H]
742
+ context_layer = tf.reshape(
743
+ context_layer,
744
+ [batch_size * from_seq_length, num_attention_heads * size_per_head])
745
+ else:
746
+ # `context_layer` = [B, F, N*H]
747
+ context_layer = tf.reshape(
748
+ context_layer,
749
+ [batch_size, from_seq_length, num_attention_heads * size_per_head])
750
+
751
+ return context_layer
752
+
753
+
754
+ def transformer_model(input_tensor,
755
+ attention_mask=None,
756
+ hidden_size=768,
757
+ num_hidden_layers=12,
758
+ num_attention_heads=12,
759
+ intermediate_size=3072,
760
+ intermediate_act_fn=gelu,
761
+ hidden_dropout_prob=0.1,
762
+ attention_probs_dropout_prob=0.1,
763
+ initializer_range=0.02,
764
+ do_return_all_layers=False):
765
+ """Multi-headed, multi-layer Transformer from "Attention is All You Need".
766
+
767
+ This is almost an exact implementation of the original Transformer encoder.
768
+
769
+ See the original paper:
770
+ https://arxiv.org/abs/1706.03762
771
+
772
+ Also see:
773
+ https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
774
+
775
+ Args:
776
+ input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
777
+ attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
778
+ seq_length], with 1 for positions that can be attended to and 0 in
779
+ positions that should not be.
780
+ hidden_size: int. Hidden size of the Transformer.
781
+ num_hidden_layers: int. Number of layers (blocks) in the Transformer.
782
+ num_attention_heads: int. Number of attention heads in the Transformer.
783
+ intermediate_size: int. The size of the "intermediate" (a.k.a., feed
784
+ forward) layer.
785
+ intermediate_act_fn: function. The non-linear activation function to apply
786
+ to the output of the intermediate/feed-forward layer.
787
+ hidden_dropout_prob: float. Dropout probability for the hidden layers.
788
+ attention_probs_dropout_prob: float. Dropout probability of the attention
789
+ probabilities.
790
+ initializer_range: float. Range of the initializer (stddev of truncated
791
+ normal).
792
+ do_return_all_layers: Whether to also return all layers or just the final
793
+ layer.
794
+
795
+ Returns:
796
+ float Tensor of shape [batch_size, seq_length, hidden_size], the final
797
+ hidden layer of the Transformer.
798
+
799
+ Raises:
800
+ ValueError: A Tensor shape or parameter is invalid.
801
+ """
802
+ if hidden_size % num_attention_heads != 0:
803
+ raise ValueError(
804
+ "The hidden size (%d) is not a multiple of the number of attention "
805
+ "heads (%d)" % (hidden_size, num_attention_heads))
806
+
807
+ attention_head_size = int(hidden_size / num_attention_heads)
808
+ input_shape = get_shape_list(input_tensor, expected_rank=3)
809
+ batch_size = input_shape[0]
810
+ seq_length = input_shape[1]
811
+ input_width = input_shape[2]
812
+
813
+ # The Transformer performs sum residuals on all layers so the input needs
814
+ # to be the same as the hidden size.
815
+ if input_width != hidden_size:
816
+ raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
817
+ (input_width, hidden_size))
818
+
819
+ # We keep the representation as a 2D tensor to avoid re-shaping it back and
820
+ # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
821
+ # the GPU/CPU but may not be free on the TPU, so we want to minimize them to
822
+ # help the optimizer.
823
+ prev_output = reshape_to_matrix(input_tensor)
824
+
825
+ all_layer_outputs = []
826
+ for layer_idx in range(num_hidden_layers):
827
+ with tf.variable_scope("layer_%d" % layer_idx):
828
+ layer_input = prev_output
829
+
830
+ with tf.variable_scope("attention"):
831
+ attention_heads = []
832
+ with tf.variable_scope("self"):
833
+ attention_head = attention_layer(
834
+ from_tensor=layer_input,
835
+ to_tensor=layer_input,
836
+ attention_mask=attention_mask,
837
+ num_attention_heads=num_attention_heads,
838
+ size_per_head=attention_head_size,
839
+ attention_probs_dropout_prob=attention_probs_dropout_prob,
840
+ initializer_range=initializer_range,
841
+ do_return_2d_tensor=True,
842
+ batch_size=batch_size,
843
+ from_seq_length=seq_length,
844
+ to_seq_length=seq_length)
845
+ attention_heads.append(attention_head)
846
+
847
+ attention_output = None
848
+ if len(attention_heads) == 1:
849
+ attention_output = attention_heads[0]
850
+ else:
851
+ # In the case where we have other sequences, we just concatenate
852
+ # them to the self-attention head before the projection.
853
+ attention_output = tf.concat(attention_heads, axis=-1)
854
+
855
+ # Run a linear projection of `hidden_size` then add a residual
856
+ # with `layer_input`.
857
+ with tf.variable_scope("output"):
858
+ attention_output = tf.layers.dense(
859
+ attention_output,
860
+ hidden_size,
861
+ kernel_initializer=create_initializer(initializer_range))
862
+ attention_output = dropout(attention_output, hidden_dropout_prob)
863
+ attention_output = layer_norm(attention_output + layer_input)
864
+
865
+ # The activation is only applied to the "intermediate" hidden layer.
866
+ with tf.variable_scope("intermediate"):
867
+ intermediate_output = tf.layers.dense(
868
+ attention_output,
869
+ intermediate_size,
870
+ activation=intermediate_act_fn,
871
+ kernel_initializer=create_initializer(initializer_range))
872
+
873
+ # Down-project back to `hidden_size` then add the residual.
874
+ with tf.variable_scope("output"):
875
+ layer_output = tf.layers.dense(
876
+ intermediate_output,
877
+ hidden_size,
878
+ kernel_initializer=create_initializer(initializer_range))
879
+ layer_output = dropout(layer_output, hidden_dropout_prob)
880
+ layer_output = layer_norm(layer_output + attention_output)
881
+ prev_output = layer_output
882
+ all_layer_outputs.append(layer_output)
883
+
884
+ if do_return_all_layers:
885
+ final_outputs = []
886
+ for layer_output in all_layer_outputs:
887
+ final_output = reshape_from_matrix(layer_output, input_shape)
888
+ final_outputs.append(final_output)
889
+ return final_outputs
890
+ else:
891
+ final_output = reshape_from_matrix(prev_output, input_shape)
892
+ return final_output
893
+
894
+
895
+ def get_shape_list(tensor, expected_rank=None, name=None):
896
+ """Returns a list of the shape of tensor, preferring static dimensions.
897
+
898
+ Args:
899
+ tensor: A tf.Tensor object to find the shape of.
900
+ expected_rank: (optional) int. The expected rank of `tensor`. If this is
901
+ specified and the `tensor` has a different rank, and exception will be
902
+ thrown.
903
+ name: Optional name of the tensor for the error message.
904
+
905
+ Returns:
906
+ A list of dimensions of the shape of tensor. All static dimensions will
907
+ be returned as python integers, and dynamic dimensions will be returned
908
+ as tf.Tensor scalars.
909
+ """
910
+ if name is None:
911
+ name = tensor.name
912
+
913
+ if expected_rank is not None:
914
+ assert_rank(tensor, expected_rank, name)
915
+
916
+ shape = tensor.shape.as_list()
917
+
918
+ non_static_indexes = []
919
+ for (index, dim) in enumerate(shape):
920
+ if dim is None:
921
+ non_static_indexes.append(index)
922
+
923
+ if not non_static_indexes:
924
+ return shape
925
+
926
+ dyn_shape = tf.shape(tensor)
927
+ for index in non_static_indexes:
928
+ shape[index] = dyn_shape[index]
929
+ return shape
930
+
931
+
932
+ def reshape_to_matrix(input_tensor):
933
+ """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
934
+ ndims = input_tensor.shape.ndims
935
+ if ndims < 2:
936
+ raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
937
+ (input_tensor.shape))
938
+ if ndims == 2:
939
+ return input_tensor
940
+
941
+ width = input_tensor.shape[-1]
942
+ output_tensor = tf.reshape(input_tensor, [-1, width])
943
+ return output_tensor
944
+
945
+
946
+ def reshape_from_matrix(output_tensor, orig_shape_list):
947
+ """Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
948
+ if len(orig_shape_list) == 2:
949
+ return output_tensor
950
+
951
+ output_shape = get_shape_list(output_tensor)
952
+
953
+ orig_dims = orig_shape_list[0:-1]
954
+ width = output_shape[-1]
955
+
956
+ return tf.reshape(output_tensor, orig_dims + [width])
957
+
958
+
959
+ def assert_rank(tensor, expected_rank, name=None):
960
+ """Raises an exception if the tensor rank is not of the expected rank.
961
+
962
+ Args:
963
+ tensor: A tf.Tensor to check the rank of.
964
+ expected_rank: Python integer or list of integers, expected rank.
965
+ name: Optional name of the tensor for the error message.
966
+
967
+ Raises:
968
+ ValueError: If the expected shape doesn't match the actual shape.
969
+ """
970
+ if name is None:
971
+ name = tensor.name
972
+
973
+ expected_rank_dict = {}
974
+ if isinstance(expected_rank, six.integer_types):
975
+ expected_rank_dict[expected_rank] = True
976
+ else:
977
+ for x in expected_rank:
978
+ expected_rank_dict[x] = True
979
+
980
+ actual_rank = tensor.shape.ndims
981
+ if actual_rank not in expected_rank_dict:
982
+ scope_name = tf.get_variable_scope().name
983
+ raise ValueError(
984
+ "For the tensor `%s` in scope `%s`, the actual rank "
985
+ "`%d` (shape = %s) is not equal to the expected rank `%s`" %
986
+ (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
bert-master/bert-master/modeling_test.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import collections
20
+ import json
21
+ import random
22
+ import re
23
+
24
+ import modeling
25
+ import six
26
+ import tensorflow as tf
27
+
28
+
29
+ class BertModelTest(tf.test.TestCase):
30
+
31
+ class BertModelTester(object):
32
+
33
+ def __init__(self,
34
+ parent,
35
+ batch_size=13,
36
+ seq_length=7,
37
+ is_training=True,
38
+ use_input_mask=True,
39
+ use_token_type_ids=True,
40
+ vocab_size=99,
41
+ hidden_size=32,
42
+ num_hidden_layers=5,
43
+ num_attention_heads=4,
44
+ intermediate_size=37,
45
+ hidden_act="gelu",
46
+ hidden_dropout_prob=0.1,
47
+ attention_probs_dropout_prob=0.1,
48
+ max_position_embeddings=512,
49
+ type_vocab_size=16,
50
+ initializer_range=0.02,
51
+ scope=None):
52
+ self.parent = parent
53
+ self.batch_size = batch_size
54
+ self.seq_length = seq_length
55
+ self.is_training = is_training
56
+ self.use_input_mask = use_input_mask
57
+ self.use_token_type_ids = use_token_type_ids
58
+ self.vocab_size = vocab_size
59
+ self.hidden_size = hidden_size
60
+ self.num_hidden_layers = num_hidden_layers
61
+ self.num_attention_heads = num_attention_heads
62
+ self.intermediate_size = intermediate_size
63
+ self.hidden_act = hidden_act
64
+ self.hidden_dropout_prob = hidden_dropout_prob
65
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
66
+ self.max_position_embeddings = max_position_embeddings
67
+ self.type_vocab_size = type_vocab_size
68
+ self.initializer_range = initializer_range
69
+ self.scope = scope
70
+
71
+ def create_model(self):
72
+ input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length],
73
+ self.vocab_size)
74
+
75
+ input_mask = None
76
+ if self.use_input_mask:
77
+ input_mask = BertModelTest.ids_tensor(
78
+ [self.batch_size, self.seq_length], vocab_size=2)
79
+
80
+ token_type_ids = None
81
+ if self.use_token_type_ids:
82
+ token_type_ids = BertModelTest.ids_tensor(
83
+ [self.batch_size, self.seq_length], self.type_vocab_size)
84
+
85
+ config = modeling.BertConfig(
86
+ vocab_size=self.vocab_size,
87
+ hidden_size=self.hidden_size,
88
+ num_hidden_layers=self.num_hidden_layers,
89
+ num_attention_heads=self.num_attention_heads,
90
+ intermediate_size=self.intermediate_size,
91
+ hidden_act=self.hidden_act,
92
+ hidden_dropout_prob=self.hidden_dropout_prob,
93
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
94
+ max_position_embeddings=self.max_position_embeddings,
95
+ type_vocab_size=self.type_vocab_size,
96
+ initializer_range=self.initializer_range)
97
+
98
+ model = modeling.BertModel(
99
+ config=config,
100
+ is_training=self.is_training,
101
+ input_ids=input_ids,
102
+ input_mask=input_mask,
103
+ token_type_ids=token_type_ids,
104
+ scope=self.scope)
105
+
106
+ outputs = {
107
+ "embedding_output": model.get_embedding_output(),
108
+ "sequence_output": model.get_sequence_output(),
109
+ "pooled_output": model.get_pooled_output(),
110
+ "all_encoder_layers": model.get_all_encoder_layers(),
111
+ }
112
+ return outputs
113
+
114
+ def check_output(self, result):
115
+ self.parent.assertAllEqual(
116
+ result["embedding_output"].shape,
117
+ [self.batch_size, self.seq_length, self.hidden_size])
118
+
119
+ self.parent.assertAllEqual(
120
+ result["sequence_output"].shape,
121
+ [self.batch_size, self.seq_length, self.hidden_size])
122
+
123
+ self.parent.assertAllEqual(result["pooled_output"].shape,
124
+ [self.batch_size, self.hidden_size])
125
+
126
+ def test_default(self):
127
+ self.run_tester(BertModelTest.BertModelTester(self))
128
+
129
+ def test_config_to_json_string(self):
130
+ config = modeling.BertConfig(vocab_size=99, hidden_size=37)
131
+ obj = json.loads(config.to_json_string())
132
+ self.assertEqual(obj["vocab_size"], 99)
133
+ self.assertEqual(obj["hidden_size"], 37)
134
+
135
+ def run_tester(self, tester):
136
+ with self.test_session() as sess:
137
+ ops = tester.create_model()
138
+ init_op = tf.group(tf.global_variables_initializer(),
139
+ tf.local_variables_initializer())
140
+ sess.run(init_op)
141
+ output_result = sess.run(ops)
142
+ tester.check_output(output_result)
143
+
144
+ self.assert_all_tensors_reachable(sess, [init_op, ops])
145
+
146
+ @classmethod
147
+ def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
148
+ """Creates a random int32 tensor of the shape within the vocab size."""
149
+ if rng is None:
150
+ rng = random.Random()
151
+
152
+ total_dims = 1
153
+ for dim in shape:
154
+ total_dims *= dim
155
+
156
+ values = []
157
+ for _ in range(total_dims):
158
+ values.append(rng.randint(0, vocab_size - 1))
159
+
160
+ return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name)
161
+
162
+ def assert_all_tensors_reachable(self, sess, outputs):
163
+ """Checks that all the tensors in the graph are reachable from outputs."""
164
+ graph = sess.graph
165
+
166
+ ignore_strings = [
167
+ "^.*/assert_less_equal/.*$",
168
+ "^.*/dilation_rate$",
169
+ "^.*/Tensordot/concat$",
170
+ "^.*/Tensordot/concat/axis$",
171
+ "^testing/.*$",
172
+ ]
173
+
174
+ ignore_regexes = [re.compile(x) for x in ignore_strings]
175
+
176
+ unreachable = self.get_unreachable_ops(graph, outputs)
177
+ filtered_unreachable = []
178
+ for x in unreachable:
179
+ do_ignore = False
180
+ for r in ignore_regexes:
181
+ m = r.match(x.name)
182
+ if m is not None:
183
+ do_ignore = True
184
+ if do_ignore:
185
+ continue
186
+ filtered_unreachable.append(x)
187
+ unreachable = filtered_unreachable
188
+
189
+ self.assertEqual(
190
+ len(unreachable), 0, "The following ops are unreachable: %s" %
191
+ (" ".join([x.name for x in unreachable])))
192
+
193
+ @classmethod
194
+ def get_unreachable_ops(cls, graph, outputs):
195
+ """Finds all of the tensors in graph that are unreachable from outputs."""
196
+ outputs = cls.flatten_recursive(outputs)
197
+ output_to_op = collections.defaultdict(list)
198
+ op_to_all = collections.defaultdict(list)
199
+ assign_out_to_in = collections.defaultdict(list)
200
+
201
+ for op in graph.get_operations():
202
+ for x in op.inputs:
203
+ op_to_all[op.name].append(x.name)
204
+ for y in op.outputs:
205
+ output_to_op[y.name].append(op.name)
206
+ op_to_all[op.name].append(y.name)
207
+ if str(op.type) == "Assign":
208
+ for y in op.outputs:
209
+ for x in op.inputs:
210
+ assign_out_to_in[y.name].append(x.name)
211
+
212
+ assign_groups = collections.defaultdict(list)
213
+ for out_name in assign_out_to_in.keys():
214
+ name_group = assign_out_to_in[out_name]
215
+ for n1 in name_group:
216
+ assign_groups[n1].append(out_name)
217
+ for n2 in name_group:
218
+ if n1 != n2:
219
+ assign_groups[n1].append(n2)
220
+
221
+ seen_tensors = {}
222
+ stack = [x.name for x in outputs]
223
+ while stack:
224
+ name = stack.pop()
225
+ if name in seen_tensors:
226
+ continue
227
+ seen_tensors[name] = True
228
+
229
+ if name in output_to_op:
230
+ for op_name in output_to_op[name]:
231
+ if op_name in op_to_all:
232
+ for input_name in op_to_all[op_name]:
233
+ if input_name not in stack:
234
+ stack.append(input_name)
235
+
236
+ expanded_names = []
237
+ if name in assign_groups:
238
+ for assign_name in assign_groups[name]:
239
+ expanded_names.append(assign_name)
240
+
241
+ for expanded_name in expanded_names:
242
+ if expanded_name not in stack:
243
+ stack.append(expanded_name)
244
+
245
+ unreachable_ops = []
246
+ for op in graph.get_operations():
247
+ is_unreachable = False
248
+ all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs]
249
+ for name in all_names:
250
+ if name not in seen_tensors:
251
+ is_unreachable = True
252
+ if is_unreachable:
253
+ unreachable_ops.append(op)
254
+ return unreachable_ops
255
+
256
+ @classmethod
257
+ def flatten_recursive(cls, item):
258
+ """Flattens (potentially nested) a tuple/dictionary/list to a list."""
259
+ output = []
260
+ if isinstance(item, list):
261
+ output.extend(item)
262
+ elif isinstance(item, tuple):
263
+ output.extend(list(item))
264
+ elif isinstance(item, dict):
265
+ for (_, v) in six.iteritems(item):
266
+ output.append(v)
267
+ else:
268
+ return [item]
269
+
270
+ flat_output = []
271
+ for x in output:
272
+ flat_output.extend(cls.flatten_recursive(x))
273
+ return flat_output
274
+
275
+
276
+ if __name__ == "__main__":
277
+ tf.test.main()
bert-master/bert-master/multilingual.md ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Models
2
+
3
+ There are two multilingual models currently available. We do not plan to release
4
+ more single-language models, but we may release `BERT-Large` versions of these
5
+ two in the future:
6
+
7
+ * **[`BERT-Base, Multilingual Cased (New, recommended)`](https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip)**:
8
+ 104 languages, 12-layer, 768-hidden, 12-heads, 110M parameters
9
+ * **[`BERT-Base, Multilingual Uncased (Orig, not recommended)`](https://storage.googleapis.com/bert_models/2018_11_03/multilingual_L-12_H-768_A-12.zip)**:
10
+ 102 languages, 12-layer, 768-hidden, 12-heads, 110M parameters
11
+ * **[`BERT-Base, Chinese`](https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip)**:
12
+ Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M
13
+ parameters
14
+
15
+ **The `Multilingual Cased (New)` model also fixes normalization issues in many
16
+ languages, so it is recommended in languages with non-Latin alphabets (and is
17
+ often better for most languages with Latin alphabets). When using this model,
18
+ make sure to pass `--do_lower_case=false` to `run_pretraining.py` and other
19
+ scripts.**
20
+
21
+ See the [list of languages](#list-of-languages) that the Multilingual model
22
+ supports. The Multilingual model does include Chinese (and English), but if your
23
+ fine-tuning data is Chinese-only, then the Chinese model will likely produce
24
+ better results.
25
+
26
+ ## Results
27
+
28
+ To evaluate these systems, we use the
29
+ [XNLI dataset](https://github.com/facebookresearch/XNLI) dataset, which is a
30
+ version of [MultiNLI](https://www.nyu.edu/projects/bowman/multinli/) where the
31
+ dev and test sets have been translated (by humans) into 15 languages. Note that
32
+ the training set was *machine* translated (we used the translations provided by
33
+ XNLI, not Google NMT). For clarity, we only report on 6 languages below:
34
+
35
+ <!-- mdformat off(no table) -->
36
+
37
+ | System | English | Chinese | Spanish | German | Arabic | Urdu |
38
+ | --------------------------------- | -------- | -------- | -------- | -------- | -------- | -------- |
39
+ | XNLI Baseline - Translate Train | 73.7 | 67.0 | 68.8 | 66.5 | 65.8 | 56.6 |
40
+ | XNLI Baseline - Translate Test | 73.7 | 68.3 | 70.7 | 68.7 | 66.8 | 59.3 |
41
+ | BERT - Translate Train Cased | **81.9** | **76.6** | **77.8** | **75.9** | **70.7** | 61.6 |
42
+ | BERT - Translate Train Uncased | 81.4 | 74.2 | 77.3 | 75.2 | 70.5 | 61.7 |
43
+ | BERT - Translate Test Uncased | 81.4 | 70.1 | 74.9 | 74.4 | 70.4 | **62.1** |
44
+ | BERT - Zero Shot Uncased | 81.4 | 63.8 | 74.3 | 70.5 | 62.1 | 58.3 |
45
+
46
+ <!-- mdformat on -->
47
+
48
+ The first two rows are baselines from the XNLI paper and the last three rows are
49
+ our results with BERT.
50
+
51
+ **Translate Train** means that the MultiNLI training set was machine translated
52
+ from English into the foreign language. So training and evaluation were both
53
+ done in the foreign language. Unfortunately, training was done on
54
+ machine-translated data, so it is impossible to quantify how much of the lower
55
+ accuracy (compared to English) is due to the quality of the machine translation
56
+ vs. the quality of the pre-trained model.
57
+
58
+ **Translate Test** means that the XNLI test set was machine translated from the
59
+ foreign language into English. So training and evaluation were both done on
60
+ English. However, test evaluation was done on machine-translated English, so the
61
+ accuracy depends on the quality of the machine translation system.
62
+
63
+ **Zero Shot** means that the Multilingual BERT system was fine-tuned on English
64
+ MultiNLI, and then evaluated on the foreign language XNLI test. In this case,
65
+ machine translation was not involved at all in either the pre-training or
66
+ fine-tuning.
67
+
68
+ Note that the English result is worse than the 84.2 MultiNLI baseline because
69
+ this training used Multilingual BERT rather than English-only BERT. This implies
70
+ that for high-resource languages, the Multilingual model is somewhat worse than
71
+ a single-language model. However, it is not feasible for us to train and
72
+ maintain dozens of single-language models. Therefore, if your goal is to maximize
73
+ performance with a language other than English or Chinese, you might find it
74
+ beneficial to run pre-training for additional steps starting from our
75
+ Multilingual model on data from your language of interest.
76
+
77
+ Here is a comparison of training Chinese models with the Multilingual
78
+ `BERT-Base` and Chinese-only `BERT-Base`:
79
+
80
+ System | Chinese
81
+ ----------------------- | -------
82
+ XNLI Baseline | 67.0
83
+ BERT Multilingual Model | 74.2
84
+ BERT Chinese-only Model | 77.2
85
+
86
+ Similar to English, the single-language model does 3% better than the
87
+ Multilingual model.
88
+
89
+ ## Fine-tuning Example
90
+
91
+ The multilingual model does **not** require any special consideration or API
92
+ changes. We did update the implementation of `BasicTokenizer` in
93
+ `tokenization.py` to support Chinese character tokenization, so please update if
94
+ you forked it. However, we did not change the tokenization API.
95
+
96
+ To test the new models, we did modify `run_classifier.py` to add support for the
97
+ [XNLI dataset](https://github.com/facebookresearch/XNLI). This is a 15-language
98
+ version of MultiNLI where the dev/test sets have been human-translated, and the
99
+ training set has been machine-translated.
100
+
101
+ To run the fine-tuning code, please download the
102
+ [XNLI dev/test set](https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip) and the
103
+ [XNLI machine-translated training set](https://www.nyu.edu/projects/bowman/xnli/XNLI-MT-1.0.zip)
104
+ and then unpack both .zip files into some directory `$XNLI_DIR`.
105
+
106
+ To run fine-tuning on XNLI. The language is hard-coded into `run_classifier.py`
107
+ (Chinese by default), so please modify `XnliProcessor` if you want to run on
108
+ another language.
109
+
110
+ This is a large dataset, so this will training will take a few hours on a GPU
111
+ (or about 30 minutes on a Cloud TPU). To run an experiment quickly for
112
+ debugging, just set `num_train_epochs` to a small value like `0.1`.
113
+
114
+ ```shell
115
+ export BERT_BASE_DIR=/path/to/bert/chinese_L-12_H-768_A-12 # or multilingual_L-12_H-768_A-12
116
+ export XNLI_DIR=/path/to/xnli
117
+
118
+ python run_classifier.py \
119
+ --task_name=XNLI \
120
+ --do_train=true \
121
+ --do_eval=true \
122
+ --data_dir=$XNLI_DIR \
123
+ --vocab_file=$BERT_BASE_DIR/vocab.txt \
124
+ --bert_config_file=$BERT_BASE_DIR/bert_config.json \
125
+ --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
126
+ --max_seq_length=128 \
127
+ --train_batch_size=32 \
128
+ --learning_rate=5e-5 \
129
+ --num_train_epochs=2.0 \
130
+ --output_dir=/tmp/xnli_output/
131
+ ```
132
+
133
+ With the Chinese-only model, the results should look something like this:
134
+
135
+ ```
136
+ ***** Eval results *****
137
+ eval_accuracy = 0.774116
138
+ eval_loss = 0.83554
139
+ global_step = 24543
140
+ loss = 0.74603
141
+ ```
142
+
143
+ ## Details
144
+
145
+ ### Data Source and Sampling
146
+
147
+ The languages chosen were the
148
+ [top 100 languages with the largest Wikipedias](https://meta.wikimedia.org/wiki/List_of_Wikipedias).
149
+ The entire Wikipedia dump for each language (excluding user and talk pages) was
150
+ taken as the training data for each language
151
+
152
+ However, the size of the Wikipedia for a given language varies greatly, and
153
+ therefore low-resource languages may be "under-represented" in terms of the
154
+ neural network model (under the assumption that languages are "competing" for
155
+ limited model capacity to some extent). At the same time, we also don't want
156
+ to overfit the model by performing thousands of epochs over a tiny Wikipedia
157
+ for a particular language.
158
+
159
+ To balance these two factors, we performed exponentially smoothed weighting of
160
+ the data during pre-training data creation (and WordPiece vocab creation). In
161
+ other words, let's say that the probability of a language is *P(L)*, e.g.,
162
+ *P(English) = 0.21* means that after concatenating all of the Wikipedias
163
+ together, 21% of our data is English. We exponentiate each probability by some
164
+ factor *S* and then re-normalize, and sample from that distribution. In our case
165
+ we use *S=0.7*. So, high-resource languages like English will be under-sampled,
166
+ and low-resource languages like Icelandic will be over-sampled. E.g., in the
167
+ original distribution English would be sampled 1000x more than Icelandic, but
168
+ after smoothing it's only sampled 100x more.
169
+
170
+ ### Tokenization
171
+
172
+ For tokenization, we use a 110k shared WordPiece vocabulary. The word counts are
173
+ weighted the same way as the data, so low-resource languages are upweighted by
174
+ some factor. We intentionally do *not* use any marker to denote the input
175
+ language (so that zero-shot training can work).
176
+
177
+ Because Chinese (and Japanese Kanji and Korean Hanja) does not have whitespace
178
+ characters, we add spaces around every character in the
179
+ [CJK Unicode range](https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_\(Unicode_block\))
180
+ before applying WordPiece. This means that Chinese is effectively
181
+ character-tokenized. Note that the CJK Unicode block only includes
182
+ Chinese-origin characters and does *not* include Hangul Korean or
183
+ Katakana/Hiragana Japanese, which are tokenized with whitespace+WordPiece like
184
+ all other languages.
185
+
186
+ For all other languages, we apply the
187
+ [same recipe as English](https://github.com/google-research/bert#tokenization):
188
+ (a) lower casing+accent removal, (b) punctuation splitting, (c) whitespace
189
+ tokenization. We understand that accent markers have substantial meaning in some
190
+ languages, but felt that the benefits of reducing the effective vocabulary make
191
+ up for this. Generally the strong contextual models of BERT should make up for
192
+ any ambiguity introduced by stripping accent markers.
193
+
194
+ ### List of Languages
195
+
196
+ The multilingual model supports the following languages. These languages were
197
+ chosen because they are the top 100 languages with the largest Wikipedias:
198
+
199
+ * Afrikaans
200
+ * Albanian
201
+ * Arabic
202
+ * Aragonese
203
+ * Armenian
204
+ * Asturian
205
+ * Azerbaijani
206
+ * Bashkir
207
+ * Basque
208
+ * Bavarian
209
+ * Belarusian
210
+ * Bengali
211
+ * Bishnupriya Manipuri
212
+ * Bosnian
213
+ * Breton
214
+ * Bulgarian
215
+ * Burmese
216
+ * Catalan
217
+ * Cebuano
218
+ * Chechen
219
+ * Chinese (Simplified)
220
+ * Chinese (Traditional)
221
+ * Chuvash
222
+ * Croatian
223
+ * Czech
224
+ * Danish
225
+ * Dutch
226
+ * English
227
+ * Estonian
228
+ * Finnish
229
+ * French
230
+ * Galician
231
+ * Georgian
232
+ * German
233
+ * Greek
234
+ * Gujarati
235
+ * Haitian
236
+ * Hebrew
237
+ * Hindi
238
+ * Hungarian
239
+ * Icelandic
240
+ * Ido
241
+ * Indonesian
242
+ * Irish
243
+ * Italian
244
+ * Japanese
245
+ * Javanese
246
+ * Kannada
247
+ * Kazakh
248
+ * Kirghiz
249
+ * Korean
250
+ * Latin
251
+ * Latvian
252
+ * Lithuanian
253
+ * Lombard
254
+ * Low Saxon
255
+ * Luxembourgish
256
+ * Macedonian
257
+ * Malagasy
258
+ * Malay
259
+ * Malayalam
260
+ * Marathi
261
+ * Minangkabau
262
+ * Nepali
263
+ * Newar
264
+ * Norwegian (Bokmal)
265
+ * Norwegian (Nynorsk)
266
+ * Occitan
267
+ * Persian (Farsi)
268
+ * Piedmontese
269
+ * Polish
270
+ * Portuguese
271
+ * Punjabi
272
+ * Romanian
273
+ * Russian
274
+ * Scots
275
+ * Serbian
276
+ * Serbo-Croatian
277
+ * Sicilian
278
+ * Slovak
279
+ * Slovenian
280
+ * South Azerbaijani
281
+ * Spanish
282
+ * Sundanese
283
+ * Swahili
284
+ * Swedish
285
+ * Tagalog
286
+ * Tajik
287
+ * Tamil
288
+ * Tatar
289
+ * Telugu
290
+ * Turkish
291
+ * Ukrainian
292
+ * Urdu
293
+ * Uzbek
294
+ * Vietnamese
295
+ * Volapük
296
+ * Waray-Waray
297
+ * Welsh
298
+ * West Frisian
299
+ * Western Punjabi
300
+ * Yoruba
301
+
302
+ The **Multilingual Cased (New)** release contains additionally **Thai** and
303
+ **Mongolian**, which were not included in the original release.
bert-master/bert-master/optimization.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Functions and classes related to optimization (weight updates)."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import re
22
+ import tensorflow as tf
23
+
24
+
25
+ def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
26
+ """Creates an optimizer training op."""
27
+ global_step = tf.train.get_or_create_global_step()
28
+
29
+ learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
30
+
31
+ # Implements linear decay of the learning rate.
32
+ learning_rate = tf.train.polynomial_decay(
33
+ learning_rate,
34
+ global_step,
35
+ num_train_steps,
36
+ end_learning_rate=0.0,
37
+ power=1.0,
38
+ cycle=False)
39
+
40
+ # Implements linear warmup. I.e., if global_step < num_warmup_steps, the
41
+ # learning rate will be `global_step/num_warmup_steps * init_lr`.
42
+ if num_warmup_steps:
43
+ global_steps_int = tf.cast(global_step, tf.int32)
44
+ warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32)
45
+
46
+ global_steps_float = tf.cast(global_steps_int, tf.float32)
47
+ warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)
48
+
49
+ warmup_percent_done = global_steps_float / warmup_steps_float
50
+ warmup_learning_rate = init_lr * warmup_percent_done
51
+
52
+ is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32)
53
+ learning_rate = (
54
+ (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate)
55
+
56
+ # It is recommended that you use this optimizer for fine tuning, since this
57
+ # is how the model was trained (note that the Adam m/v variables are NOT
58
+ # loaded from init_checkpoint.)
59
+ optimizer = AdamWeightDecayOptimizer(
60
+ learning_rate=learning_rate,
61
+ weight_decay_rate=0.01,
62
+ beta_1=0.9,
63
+ beta_2=0.999,
64
+ epsilon=1e-6,
65
+ exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"])
66
+
67
+ if use_tpu:
68
+ optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
69
+
70
+ tvars = tf.trainable_variables()
71
+ grads = tf.gradients(loss, tvars)
72
+
73
+ # This is how the model was pre-trained.
74
+ (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)
75
+
76
+ train_op = optimizer.apply_gradients(
77
+ zip(grads, tvars), global_step=global_step)
78
+
79
+ # Normally the global step update is done inside of `apply_gradients`.
80
+ # However, `AdamWeightDecayOptimizer` doesn't do this. But if you use
81
+ # a different optimizer, you should probably take this line out.
82
+ new_global_step = global_step + 1
83
+ train_op = tf.group(train_op, [global_step.assign(new_global_step)])
84
+ return train_op
85
+
86
+
87
+ class AdamWeightDecayOptimizer(tf.train.Optimizer):
88
+ """A basic Adam optimizer that includes "correct" L2 weight decay."""
89
+
90
+ def __init__(self,
91
+ learning_rate,
92
+ weight_decay_rate=0.0,
93
+ beta_1=0.9,
94
+ beta_2=0.999,
95
+ epsilon=1e-6,
96
+ exclude_from_weight_decay=None,
97
+ name="AdamWeightDecayOptimizer"):
98
+ """Constructs a AdamWeightDecayOptimizer."""
99
+ super(AdamWeightDecayOptimizer, self).__init__(False, name)
100
+
101
+ self.learning_rate = learning_rate
102
+ self.weight_decay_rate = weight_decay_rate
103
+ self.beta_1 = beta_1
104
+ self.beta_2 = beta_2
105
+ self.epsilon = epsilon
106
+ self.exclude_from_weight_decay = exclude_from_weight_decay
107
+
108
+ def apply_gradients(self, grads_and_vars, global_step=None, name=None):
109
+ """See base class."""
110
+ assignments = []
111
+ for (grad, param) in grads_and_vars:
112
+ if grad is None or param is None:
113
+ continue
114
+
115
+ param_name = self._get_variable_name(param.name)
116
+
117
+ m = tf.get_variable(
118
+ name=param_name + "/adam_m",
119
+ shape=param.shape.as_list(),
120
+ dtype=tf.float32,
121
+ trainable=False,
122
+ initializer=tf.zeros_initializer())
123
+ v = tf.get_variable(
124
+ name=param_name + "/adam_v",
125
+ shape=param.shape.as_list(),
126
+ dtype=tf.float32,
127
+ trainable=False,
128
+ initializer=tf.zeros_initializer())
129
+
130
+ # Standard Adam update.
131
+ next_m = (
132
+ tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
133
+ next_v = (
134
+ tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
135
+ tf.square(grad)))
136
+
137
+ update = next_m / (tf.sqrt(next_v) + self.epsilon)
138
+
139
+ # Just adding the square of the weights to the loss function is *not*
140
+ # the correct way of using L2 regularization/weight decay with Adam,
141
+ # since that will interact with the m and v parameters in strange ways.
142
+ #
143
+ # Instead we want ot decay the weights in a manner that doesn't interact
144
+ # with the m/v parameters. This is equivalent to adding the square
145
+ # of the weights to the loss with plain (non-momentum) SGD.
146
+ if self._do_use_weight_decay(param_name):
147
+ update += self.weight_decay_rate * param
148
+
149
+ update_with_lr = self.learning_rate * update
150
+
151
+ next_param = param - update_with_lr
152
+
153
+ assignments.extend(
154
+ [param.assign(next_param),
155
+ m.assign(next_m),
156
+ v.assign(next_v)])
157
+ return tf.group(*assignments, name=name)
158
+
159
+ def _do_use_weight_decay(self, param_name):
160
+ """Whether to use L2 weight decay for `param_name`."""
161
+ if not self.weight_decay_rate:
162
+ return False
163
+ if self.exclude_from_weight_decay:
164
+ for r in self.exclude_from_weight_decay:
165
+ if re.search(r, param_name) is not None:
166
+ return False
167
+ return True
168
+
169
+ def _get_variable_name(self, param_name):
170
+ """Get the variable name from the tensor name."""
171
+ m = re.match("^(.*):\\d+$", param_name)
172
+ if m is not None:
173
+ param_name = m.group(1)
174
+ return param_name
bert-master/bert-master/optimization_test.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import optimization
20
+ import tensorflow as tf
21
+
22
+
23
+ class OptimizationTest(tf.test.TestCase):
24
+
25
+ def test_adam(self):
26
+ with self.test_session() as sess:
27
+ w = tf.get_variable(
28
+ "w",
29
+ shape=[3],
30
+ initializer=tf.constant_initializer([0.1, -0.2, -0.1]))
31
+ x = tf.constant([0.4, 0.2, -0.5])
32
+ loss = tf.reduce_mean(tf.square(x - w))
33
+ tvars = tf.trainable_variables()
34
+ grads = tf.gradients(loss, tvars)
35
+ global_step = tf.train.get_or_create_global_step()
36
+ optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)
37
+ train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)
38
+ init_op = tf.group(tf.global_variables_initializer(),
39
+ tf.local_variables_initializer())
40
+ sess.run(init_op)
41
+ for _ in range(100):
42
+ sess.run(train_op)
43
+ w_np = sess.run(w)
44
+ self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ tf.test.main()
bert-master/bert-master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb ADDED
@@ -0,0 +1,1231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "Predicting Movie Reviews with BERT on TF Hub.ipynb",
7
+ "version": "0.3.2",
8
+ "provenance": [],
9
+ "collapsed_sections": []
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "accelerator": "GPU"
16
+ },
17
+ "cells": [
18
+ {
19
+ "metadata": {
20
+ "id": "j0a4mTk9o1Qg",
21
+ "colab_type": "code",
22
+ "colab": {}
23
+ },
24
+ "cell_type": "code",
25
+ "source": [
26
+ "# Copyright 2019 Google Inc.\n",
27
+ "\n",
28
+ "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
29
+ "# you may not use this file except in compliance with the License.\n",
30
+ "# You may obtain a copy of the License at\n",
31
+ "\n",
32
+ "# http://www.apache.org/licenses/LICENSE-2.0\n",
33
+ "\n",
34
+ "# Unless required by applicable law or agreed to in writing, software\n",
35
+ "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
36
+ "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
37
+ "# See the License for the specific language governing permissions and\n",
38
+ "# limitations under the License."
39
+ ],
40
+ "execution_count": 0,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "metadata": {
45
+ "id": "dCpvgG0vwXAZ",
46
+ "colab_type": "text"
47
+ },
48
+ "cell_type": "markdown",
49
+ "source": [
50
+ "#Predicting Movie Review Sentiment with BERT on TF Hub"
51
+ ]
52
+ },
53
+ {
54
+ "metadata": {
55
+ "id": "xiYrZKaHwV81",
56
+ "colab_type": "text"
57
+ },
58
+ "cell_type": "markdown",
59
+ "source": [
60
+ "If you’ve been following Natural Language Processing over the past year, you’ve probably heard of BERT: Bidirectional Encoder Representations from Transformers. It’s a neural network architecture designed by Google researchers that’s totally transformed what’s state-of-the-art for NLP tasks, like text classification, translation, summarization, and question answering.\n",
61
+ "\n",
62
+ "Now that BERT's been added to [TF Hub](https://www.tensorflow.org/hub) as a loadable module, it's easy(ish) to add into existing Tensorflow text pipelines. In an existing pipeline, BERT can replace text embedding layers like ELMO and GloVE. Alternatively, [finetuning](http://wiki.fast.ai/index.php/Fine_tuning) BERT can provide both an accuracy boost and faster training time in many cases.\n",
63
+ "\n",
64
+ "Here, we'll train a model to predict whether an IMDB movie review is positive or negative using BERT in Tensorflow with tf hub. Some code was adapted from [this colab notebook](https://colab.sandbox.google.com/github/tensorflow/tpu/blob/master/tools/colab/bert_finetuning_with_cloud_tpus.ipynb). Let's get started!"
65
+ ]
66
+ },
67
+ {
68
+ "metadata": {
69
+ "id": "hsZvic2YxnTz",
70
+ "colab_type": "code",
71
+ "colab": {}
72
+ },
73
+ "cell_type": "code",
74
+ "source": [
75
+ "from sklearn.model_selection import train_test_split\n",
76
+ "import pandas as pd\n",
77
+ "import tensorflow as tf\n",
78
+ "import tensorflow_hub as hub\n",
79
+ "from datetime import datetime"
80
+ ],
81
+ "execution_count": 0,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "metadata": {
86
+ "id": "cp5wfXDx5SPH",
87
+ "colab_type": "text"
88
+ },
89
+ "cell_type": "markdown",
90
+ "source": [
91
+ "In addition to the standard libraries we imported above, we'll need to install BERT's python package."
92
+ ]
93
+ },
94
+ {
95
+ "metadata": {
96
+ "id": "jviywGyWyKsA",
97
+ "colab_type": "code",
98
+ "outputId": "166f3005-d219-404f-b201-2a0b75480360",
99
+ "colab": {
100
+ "base_uri": "https://localhost:8080/",
101
+ "height": 51
102
+ }
103
+ },
104
+ "cell_type": "code",
105
+ "source": [
106
+ "!pip install bert-tensorflow"
107
+ ],
108
+ "execution_count": 38,
109
+ "outputs": [
110
+ {
111
+ "output_type": "stream",
112
+ "text": [
113
+ "Requirement already satisfied: bert-tensorflow in /usr/local/lib/python3.6/dist-packages (1.0.1)\n",
114
+ "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from bert-tensorflow) (1.11.0)\n"
115
+ ],
116
+ "name": "stdout"
117
+ }
118
+ ]
119
+ },
120
+ {
121
+ "metadata": {
122
+ "id": "hhbGEfwgdEtw",
123
+ "colab_type": "code",
124
+ "colab": {}
125
+ },
126
+ "cell_type": "code",
127
+ "source": [
128
+ "import bert\n",
129
+ "from bert import run_classifier\n",
130
+ "from bert import optimization\n",
131
+ "from bert import tokenization"
132
+ ],
133
+ "execution_count": 0,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "metadata": {
138
+ "id": "KVB3eOcjxxm1",
139
+ "colab_type": "text"
140
+ },
141
+ "cell_type": "markdown",
142
+ "source": [
143
+ "Below, we'll set an output directory location to store our model output and checkpoints. This can be a local directory, in which case you'd set OUTPUT_DIR to the name of the directory you'd like to create. If you're running this code in Google's hosted Colab, the directory won't persist after the Colab session ends.\n",
144
+ "\n",
145
+ "Alternatively, if you're a GCP user, you can store output in a GCP bucket. To do that, set a directory name in OUTPUT_DIR and the name of the GCP bucket in the BUCKET field.\n",
146
+ "\n",
147
+ "Set DO_DELETE to rewrite the OUTPUT_DIR if it exists. Otherwise, Tensorflow will load existing model checkpoints from that directory (if they exist)."
148
+ ]
149
+ },
150
+ {
151
+ "metadata": {
152
+ "id": "US_EAnICvP7f",
153
+ "colab_type": "code",
154
+ "outputId": "7780a032-31d4-4794-e6aa-664a5d2ae7dd",
155
+ "cellView": "form",
156
+ "colab": {
157
+ "base_uri": "https://localhost:8080/",
158
+ "height": 34
159
+ }
160
+ },
161
+ "cell_type": "code",
162
+ "source": [
163
+ "# Set the output directory for saving model file\n",
164
+ "# Optionally, set a GCP bucket location\n",
165
+ "\n",
166
+ "OUTPUT_DIR = 'OUTPUT_DIR_NAME'#@param {type:\"string\"}\n",
167
+ "#@markdown Whether or not to clear/delete the directory and create a new one\n",
168
+ "DO_DELETE = False #@param {type:\"boolean\"}\n",
169
+ "#@markdown Set USE_BUCKET and BUCKET if you want to (optionally) store model output on GCP bucket.\n",
170
+ "USE_BUCKET = True #@param {type:\"boolean\"}\n",
171
+ "BUCKET = 'BUCKET_NAME' #@param {type:\"string\"}\n",
172
+ "\n",
173
+ "if USE_BUCKET:\n",
174
+ " OUTPUT_DIR = 'gs://{}/{}'.format(BUCKET, OUTPUT_DIR)\n",
175
+ " from google.colab import auth\n",
176
+ " auth.authenticate_user()\n",
177
+ "\n",
178
+ "if DO_DELETE:\n",
179
+ " try:\n",
180
+ " tf.gfile.DeleteRecursively(OUTPUT_DIR)\n",
181
+ " except:\n",
182
+ " # Doesn't matter if the directory didn't exist\n",
183
+ " pass\n",
184
+ "tf.gfile.MakeDirs(OUTPUT_DIR)\n",
185
+ "print('***** Model output directory: {} *****'.format(OUTPUT_DIR))\n"
186
+ ],
187
+ "execution_count": 40,
188
+ "outputs": [
189
+ {
190
+ "output_type": "stream",
191
+ "text": [
192
+ "***** Model output directory: gs://bert-tfhub/aclImdb_v1 *****\n"
193
+ ],
194
+ "name": "stdout"
195
+ }
196
+ ]
197
+ },
198
+ {
199
+ "metadata": {
200
+ "id": "pmFYvkylMwXn",
201
+ "colab_type": "text"
202
+ },
203
+ "cell_type": "markdown",
204
+ "source": [
205
+ "#Data"
206
+ ]
207
+ },
208
+ {
209
+ "metadata": {
210
+ "id": "MC_w8SRqN0fr",
211
+ "colab_type": "text"
212
+ },
213
+ "cell_type": "markdown",
214
+ "source": [
215
+ "First, let's download the dataset, hosted by Stanford. The code below, which downloads, extracts, and imports the IMDB Large Movie Review Dataset, is borrowed from [this Tensorflow tutorial](https://www.tensorflow.org/hub/tutorials/text_classification_with_tf_hub)."
216
+ ]
217
+ },
218
+ {
219
+ "metadata": {
220
+ "id": "fom_ff20gyy6",
221
+ "colab_type": "code",
222
+ "colab": {}
223
+ },
224
+ "cell_type": "code",
225
+ "source": [
226
+ "from tensorflow import keras\n",
227
+ "import os\n",
228
+ "import re\n",
229
+ "\n",
230
+ "# Load all files from a directory in a DataFrame.\n",
231
+ "def load_directory_data(directory):\n",
232
+ " data = {}\n",
233
+ " data[\"sentence\"] = []\n",
234
+ " data[\"sentiment\"] = []\n",
235
+ " for file_path in os.listdir(directory):\n",
236
+ " with tf.gfile.GFile(os.path.join(directory, file_path), \"r\") as f:\n",
237
+ " data[\"sentence\"].append(f.read())\n",
238
+ " data[\"sentiment\"].append(re.match(\"\\d+_(\\d+)\\.txt\", file_path).group(1))\n",
239
+ " return pd.DataFrame.from_dict(data)\n",
240
+ "\n",
241
+ "# Merge positive and negative examples, add a polarity column and shuffle.\n",
242
+ "def load_dataset(directory):\n",
243
+ " pos_df = load_directory_data(os.path.join(directory, \"pos\"))\n",
244
+ " neg_df = load_directory_data(os.path.join(directory, \"neg\"))\n",
245
+ " pos_df[\"polarity\"] = 1\n",
246
+ " neg_df[\"polarity\"] = 0\n",
247
+ " return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)\n",
248
+ "\n",
249
+ "# Download and process the dataset files.\n",
250
+ "def download_and_load_datasets(force_download=False):\n",
251
+ " dataset = tf.keras.utils.get_file(\n",
252
+ " fname=\"aclImdb.tar.gz\", \n",
253
+ " origin=\"http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\", \n",
254
+ " extract=True)\n",
255
+ " \n",
256
+ " train_df = load_dataset(os.path.join(os.path.dirname(dataset), \n",
257
+ " \"aclImdb\", \"train\"))\n",
258
+ " test_df = load_dataset(os.path.join(os.path.dirname(dataset), \n",
259
+ " \"aclImdb\", \"test\"))\n",
260
+ " \n",
261
+ " return train_df, test_df\n"
262
+ ],
263
+ "execution_count": 0,
264
+ "outputs": []
265
+ },
266
+ {
267
+ "metadata": {
268
+ "id": "2abfwdn-g135",
269
+ "colab_type": "code",
270
+ "colab": {}
271
+ },
272
+ "cell_type": "code",
273
+ "source": [
274
+ "train, test = download_and_load_datasets()"
275
+ ],
276
+ "execution_count": 0,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "metadata": {
281
+ "id": "XA8WHJgzhIZf",
282
+ "colab_type": "text"
283
+ },
284
+ "cell_type": "markdown",
285
+ "source": [
286
+ "To keep training fast, we'll take a sample of 5000 train and test examples, respectively."
287
+ ]
288
+ },
289
+ {
290
+ "metadata": {
291
+ "id": "lw_F488eixTV",
292
+ "colab_type": "code",
293
+ "colab": {}
294
+ },
295
+ "cell_type": "code",
296
+ "source": [
297
+ "train = train.sample(5000)\n",
298
+ "test = test.sample(5000)"
299
+ ],
300
+ "execution_count": 0,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "metadata": {
305
+ "id": "prRQM8pDi8xI",
306
+ "colab_type": "code",
307
+ "outputId": "34445cb8-2be0-4379-fdbc-7794091f6049",
308
+ "colab": {
309
+ "base_uri": "https://localhost:8080/",
310
+ "height": 34
311
+ }
312
+ },
313
+ "cell_type": "code",
314
+ "source": [
315
+ "train.columns"
316
+ ],
317
+ "execution_count": 44,
318
+ "outputs": [
319
+ {
320
+ "output_type": "execute_result",
321
+ "data": {
322
+ "text/plain": [
323
+ "Index(['sentence', 'sentiment', 'polarity'], dtype='object')"
324
+ ]
325
+ },
326
+ "metadata": {
327
+ "tags": []
328
+ },
329
+ "execution_count": 44
330
+ }
331
+ ]
332
+ },
333
+ {
334
+ "metadata": {
335
+ "id": "sfRnHSz3iSXz",
336
+ "colab_type": "text"
337
+ },
338
+ "cell_type": "markdown",
339
+ "source": [
340
+ "For us, our input data is the 'sentence' column and our label is the 'polarity' column (0, 1 for negative and positive, respecitvely)"
341
+ ]
342
+ },
343
+ {
344
+ "metadata": {
345
+ "id": "IuMOGwFui4it",
346
+ "colab_type": "code",
347
+ "colab": {}
348
+ },
349
+ "cell_type": "code",
350
+ "source": [
351
+ "DATA_COLUMN = 'sentence'\n",
352
+ "LABEL_COLUMN = 'polarity'\n",
353
+ "# label_list is the list of labels, i.e. True, False or 0, 1 or 'dog', 'cat'\n",
354
+ "label_list = [0, 1]"
355
+ ],
356
+ "execution_count": 0,
357
+ "outputs": []
358
+ },
359
+ {
360
+ "metadata": {
361
+ "id": "V399W0rqNJ-Z",
362
+ "colab_type": "text"
363
+ },
364
+ "cell_type": "markdown",
365
+ "source": [
366
+ "#Data Preprocessing\n",
367
+ "We'll need to transform our data into a format BERT understands. This involves two steps. First, we create `InputExample`'s using the constructor provided in the BERT library.\n",
368
+ "\n",
369
+ "- `text_a` is the text we want to classify, which in this case, is the `Request` field in our Dataframe. \n",
370
+ "- `text_b` is used if we're training a model to understand the relationship between sentences (i.e. is `text_b` a translation of `text_a`? Is `text_b` an answer to the question asked by `text_a`?). This doesn't apply to our task, so we can leave `text_b` blank.\n",
371
+ "- `label` is the label for our example, i.e. True, False"
372
+ ]
373
+ },
374
+ {
375
+ "metadata": {
376
+ "id": "p9gEt5SmM6i6",
377
+ "colab_type": "code",
378
+ "colab": {}
379
+ },
380
+ "cell_type": "code",
381
+ "source": [
382
+ "# Use the InputExample class from BERT's run_classifier code to create examples from the data\n",
383
+ "train_InputExamples = train.apply(lambda x: bert.run_classifier.InputExample(guid=None, # Globally unique ID for bookkeeping, unused in this example\n",
384
+ " text_a = x[DATA_COLUMN], \n",
385
+ " text_b = None, \n",
386
+ " label = x[LABEL_COLUMN]), axis = 1)\n",
387
+ "\n",
388
+ "test_InputExamples = test.apply(lambda x: bert.run_classifier.InputExample(guid=None, \n",
389
+ " text_a = x[DATA_COLUMN], \n",
390
+ " text_b = None, \n",
391
+ " label = x[LABEL_COLUMN]), axis = 1)"
392
+ ],
393
+ "execution_count": 0,
394
+ "outputs": []
395
+ },
396
+ {
397
+ "metadata": {
398
+ "id": "SCZWZtKxObjh",
399
+ "colab_type": "text"
400
+ },
401
+ "cell_type": "markdown",
402
+ "source": [
403
+ "Next, we need to preprocess our data so that it matches the data BERT was trained on. For this, we'll need to do a couple of things (but don't worry--this is also included in the Python library):\n",
404
+ "\n",
405
+ "\n",
406
+ "1. Lowercase our text (if we're using a BERT lowercase model)\n",
407
+ "2. Tokenize it (i.e. \"sally says hi\" -> [\"sally\", \"says\", \"hi\"])\n",
408
+ "3. Break words into WordPieces (i.e. \"calling\" -> [\"call\", \"##ing\"])\n",
409
+ "4. Map our words to indexes using a vocab file that BERT provides\n",
410
+ "5. Add special \"CLS\" and \"SEP\" tokens (see the [readme](https://github.com/google-research/bert))\n",
411
+ "6. Append \"index\" and \"segment\" tokens to each input (see the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf))\n",
412
+ "\n",
413
+ "Happily, we don't have to worry about most of these details.\n",
414
+ "\n",
415
+ "\n"
416
+ ]
417
+ },
418
+ {
419
+ "metadata": {
420
+ "id": "qMWiDtpyQSoU",
421
+ "colab_type": "text"
422
+ },
423
+ "cell_type": "markdown",
424
+ "source": [
425
+ "To start, we'll need to load a vocabulary file and lowercasing information directly from the BERT tf hub module:"
426
+ ]
427
+ },
428
+ {
429
+ "metadata": {
430
+ "id": "IhJSe0QHNG7U",
431
+ "colab_type": "code",
432
+ "outputId": "20b28cc7-3cb3-4ce6-bfff-a7847ce3bbaa",
433
+ "colab": {
434
+ "base_uri": "https://localhost:8080/",
435
+ "height": 34
436
+ }
437
+ },
438
+ "cell_type": "code",
439
+ "source": [
440
+ "# This is a path to an uncased (all lowercase) version of BERT\n",
441
+ "BERT_MODEL_HUB = \"https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1\"\n",
442
+ "\n",
443
+ "def create_tokenizer_from_hub_module():\n",
444
+ " \"\"\"Get the vocab file and casing info from the Hub module.\"\"\"\n",
445
+ " with tf.Graph().as_default():\n",
446
+ " bert_module = hub.Module(BERT_MODEL_HUB)\n",
447
+ " tokenization_info = bert_module(signature=\"tokenization_info\", as_dict=True)\n",
448
+ " with tf.Session() as sess:\n",
449
+ " vocab_file, do_lower_case = sess.run([tokenization_info[\"vocab_file\"],\n",
450
+ " tokenization_info[\"do_lower_case\"]])\n",
451
+ " \n",
452
+ " return bert.tokenization.FullTokenizer(\n",
453
+ " vocab_file=vocab_file, do_lower_case=do_lower_case)\n",
454
+ "\n",
455
+ "tokenizer = create_tokenizer_from_hub_module()"
456
+ ],
457
+ "execution_count": 47,
458
+ "outputs": [
459
+ {
460
+ "output_type": "stream",
461
+ "text": [
462
+ "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n"
463
+ ],
464
+ "name": "stdout"
465
+ }
466
+ ]
467
+ },
468
+ {
469
+ "metadata": {
470
+ "id": "z4oFkhpZBDKm",
471
+ "colab_type": "text"
472
+ },
473
+ "cell_type": "markdown",
474
+ "source": [
475
+ "Great--we just learned that the BERT model we're using expects lowercase data (that's what stored in tokenization_info[\"do_lower_case\"]) and we also loaded BERT's vocab file. We also created a tokenizer, which breaks words into word pieces:"
476
+ ]
477
+ },
478
+ {
479
+ "metadata": {
480
+ "id": "dsBo6RCtQmwx",
481
+ "colab_type": "code",
482
+ "outputId": "9af8c917-90ec-4fe9-897b-79dc89ca88e1",
483
+ "colab": {
484
+ "base_uri": "https://localhost:8080/",
485
+ "height": 221
486
+ }
487
+ },
488
+ "cell_type": "code",
489
+ "source": [
490
+ "tokenizer.tokenize(\"This here's an example of using the BERT tokenizer\")"
491
+ ],
492
+ "execution_count": 48,
493
+ "outputs": [
494
+ {
495
+ "output_type": "execute_result",
496
+ "data": {
497
+ "text/plain": [
498
+ "['this',\n",
499
+ " 'here',\n",
500
+ " \"'\",\n",
501
+ " 's',\n",
502
+ " 'an',\n",
503
+ " 'example',\n",
504
+ " 'of',\n",
505
+ " 'using',\n",
506
+ " 'the',\n",
507
+ " 'bert',\n",
508
+ " 'token',\n",
509
+ " '##izer']"
510
+ ]
511
+ },
512
+ "metadata": {
513
+ "tags": []
514
+ },
515
+ "execution_count": 48
516
+ }
517
+ ]
518
+ },
519
+ {
520
+ "metadata": {
521
+ "id": "0OEzfFIt6GIc",
522
+ "colab_type": "text"
523
+ },
524
+ "cell_type": "markdown",
525
+ "source": [
526
+ "Using our tokenizer, we'll call `run_classifier.convert_examples_to_features` on our InputExamples to convert them into features BERT understands."
527
+ ]
528
+ },
529
+ {
530
+ "metadata": {
531
+ "id": "LL5W8gEGRTAf",
532
+ "colab_type": "code",
533
+ "outputId": "65001dda-155b-48fc-b5fc-1e4cabc8dfbf",
534
+ "colab": {
535
+ "base_uri": "https://localhost:8080/",
536
+ "height": 1261
537
+ }
538
+ },
539
+ "cell_type": "code",
540
+ "source": [
541
+ "# We'll set sequences to be at most 128 tokens long.\n",
542
+ "MAX_SEQ_LENGTH = 128\n",
543
+ "# Convert our train and test features to InputFeatures that BERT understands.\n",
544
+ "train_features = bert.run_classifier.convert_examples_to_features(train_InputExamples, label_list, MAX_SEQ_LENGTH, tokenizer)\n",
545
+ "test_features = bert.run_classifier.convert_examples_to_features(test_InputExamples, label_list, MAX_SEQ_LENGTH, tokenizer)"
546
+ ],
547
+ "execution_count": 49,
548
+ "outputs": [
549
+ {
550
+ "output_type": "stream",
551
+ "text": [
552
+ "INFO:tensorflow:Writing example 0 of 5000\n",
553
+ "INFO:tensorflow:*** Example ***\n",
554
+ "INFO:tensorflow:guid: None\n",
555
+ "INFO:tensorflow:tokens: [CLS] i ' m watching this on the sci - fi channel right now . it ' s so horrible i can ' t stop watching it ! i ' m a video ##grapher and this movie makes me sad . i feel bad for anyone associated with this movie . some of the camera work is good . most is very questionable . there are a few decent actors in the flick . too bad they ' re surrounded by what must have been the director ' s relatives . that ' s the only way they could have been qualified to be in a movie ! music was a little better than the acting . if you get around to watching this i hope it [SEP]\n",
556
+ "INFO:tensorflow:input_ids: 101 1045 1005 1049 3666 2023 2006 1996 16596 1011 10882 3149 2157 2085 1012 2009 1005 1055 2061 9202 1045 2064 1005 1056 2644 3666 2009 999 1045 1005 1049 1037 2678 18657 1998 2023 3185 3084 2033 6517 1012 1045 2514 2919 2005 3087 3378 2007 2023 3185 1012 2070 1997 1996 4950 2147 2003 2204 1012 2087 2003 2200 21068 1012 2045 2024 1037 2261 11519 5889 1999 1996 17312 1012 2205 2919 2027 1005 2128 5129 2011 2054 2442 2031 2042 1996 2472 1005 1055 9064 1012 2008 1005 1055 1996 2069 2126 2027 2071 2031 2042 4591 2000 2022 1999 1037 3185 999 2189 2001 1037 2210 2488 2084 1996 3772 1012 2065 2017 2131 2105 2000 3666 2023 1045 3246 2009 102\n",
557
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
558
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
559
+ "INFO:tensorflow:label: 0 (id = 0)\n",
560
+ "INFO:tensorflow:*** Example ***\n",
561
+ "INFO:tensorflow:guid: None\n",
562
+ "INFO:tensorflow:tokens: [CLS] i have been a fan of pushing dai ##sies since the very beginning . it is wonderful ##ly thought up , and bryan fuller has the most remarkable ideas for this show . < br / > < br / > it is unbelievable on how much tv has been needing a creative , original show like pushing dai ##sies . it is a huge relief to see a show , that is unlike the rest , where as , if you compared it to some of the newer shows , such as scrub ##s and house , you would see the similarities , and it does get ted ##ious at moments to see shows so close in identity . < br / > < br [SEP]\n",
563
+ "INFO:tensorflow:input_ids: 101 1045 2031 2042 1037 5470 1997 6183 18765 14625 2144 1996 2200 2927 1012 2009 2003 6919 2135 2245 2039 1010 1998 8527 12548 2038 1996 2087 9487 4784 2005 2023 2265 1012 1026 7987 1013 1028 1026 7987 1013 1028 2009 2003 23653 2006 2129 2172 2694 2038 2042 11303 1037 5541 1010 2434 2265 2066 6183 18765 14625 1012 2009 2003 1037 4121 4335 2000 2156 1037 2265 1010 2008 2003 4406 1996 2717 1010 2073 2004 1010 2065 2017 4102 2009 2000 2070 1997 1996 10947 3065 1010 2107 2004 18157 2015 1998 2160 1010 2017 2052 2156 1996 12319 1010 1998 2009 2515 2131 6945 6313 2012 5312 2000 2156 3065 2061 2485 1999 4767 1012 1026 7987 1013 1028 1026 7987 102\n",
564
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
565
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
566
+ "INFO:tensorflow:label: 1 (id = 1)\n",
567
+ "INFO:tensorflow:*** Example ***\n",
568
+ "INFO:tensorflow:guid: None\n",
569
+ "INFO:tensorflow:tokens: [CLS] this movie starts out promising ##ly , with an early scene in which frank morgan advises against gary cooper ' s marriage to his daughter , anita louise . frank morgan , playing an una ##bas ##hed gold - digger , loudly complain ##s to cooper about his perceived pen ##ury at the hands of his family - including his daughter , anita louise . i am a fan of all 3 actors . frank morgan is ( to my mind ) a hollywood treasure , cooper a legend , and louise a very lovely , versatile and under - appreciated actress seldom seen in the leading role . i also have nothing against teresa wright , and while not blessed with great range , she [SEP]\n",
570
+ "INFO:tensorflow:input_ids: 101 2023 3185 4627 2041 10015 2135 1010 2007 2019 2220 3496 1999 2029 3581 5253 25453 2114 5639 6201 1005 1055 3510 2000 2010 2684 1010 12918 8227 1012 3581 5253 1010 2652 2019 14477 22083 9072 2751 1011 28661 1010 9928 17612 2015 2000 6201 2055 2010 8690 7279 13098 2012 1996 2398 1997 2010 2155 1011 2164 2010 2684 1010 12918 8227 1012 1045 2572 1037 5470 1997 2035 1017 5889 1012 3581 5253 2003 1006 2000 2026 2568 1007 1037 5365 8813 1010 6201 1037 5722 1010 1998 8227 1037 2200 8403 1010 22979 1998 2104 1011 12315 3883 15839 2464 1999 1996 2877 2535 1012 1045 2036 2031 2498 2114 12409 6119 1010 1998 2096 2025 10190 2007 2307 2846 1010 2016 102\n",
571
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
572
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
573
+ "INFO:tensorflow:label: 0 (id = 0)\n",
574
+ "INFO:tensorflow:*** Example ***\n",
575
+ "INFO:tensorflow:guid: None\n",
576
+ "INFO:tensorflow:tokens: [CLS] i was over ##taken by the emotion . un ##for ##get ##table rendering of a wartime story which is unknown to most people . the performances were fault ##less and outstanding . [SEP]\n",
577
+ "INFO:tensorflow:input_ids: 101 1045 2001 2058 25310 2011 1996 7603 1012 4895 29278 18150 10880 14259 1997 1037 12498 2466 2029 2003 4242 2000 2087 2111 1012 1996 4616 2020 6346 3238 1998 5151 1012 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
578
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
579
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
580
+ "INFO:tensorflow:label: 1 (id = 1)\n",
581
+ "INFO:tensorflow:*** Example ***\n",
582
+ "INFO:tensorflow:guid: None\n",
583
+ "INFO:tensorflow:tokens: [CLS] soldier blue is a movie with pre ##tension ##s : pre ##tension ##s to be some sort of profound statement on man ' s inhuman ##ity to man , on the white man ' s exploitation of and brutality towards indigenous peoples ; a biting , un ##fl ##in ##ching and sar ##don ##ic commentary on the horrors of vietnam . well , sorry , but it fails mis ##era ##bly to be any of those things . what soldier blue actually is is per ##nic ##ious , tri ##te , badly made , dish ##ones ##t rubbish . < br / > < br / > another reviewer here hit the nail on the head in saying that it appears to be a hybrid of [SEP]\n",
584
+ "INFO:tensorflow:input_ids: 101 5268 2630 2003 1037 3185 2007 3653 29048 2015 1024 3653 29048 2015 2000 2022 2070 4066 1997 13769 4861 2006 2158 1005 1055 29582 3012 2000 2158 1010 2006 1996 2317 2158 1005 1055 14427 1997 1998 24083 2875 6284 7243 1025 1037 12344 1010 4895 10258 2378 8450 1998 18906 5280 2594 8570 2006 1996 22812 1997 5148 1012 2092 1010 3374 1010 2021 2009 11896 28616 6906 6321 2000 2022 2151 1997 2216 2477 1012 2054 5268 2630 2941 2003 2003 2566 8713 6313 1010 13012 2618 1010 6649 2081 1010 9841 21821 2102 29132 1012 1026 7987 1013 1028 1026 7987 1013 1028 2178 12027 2182 2718 1996 13774 2006 1996 2132 1999 3038 2008 2009 3544 2000 2022 1037 8893 1997 102\n",
585
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
586
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
587
+ "INFO:tensorflow:label: 0 (id = 0)\n",
588
+ "INFO:tensorflow:Writing example 0 of 5000\n",
589
+ "INFO:tensorflow:*** Example ***\n",
590
+ "INFO:tensorflow:guid: None\n",
591
+ "INFO:tensorflow:tokens: [CLS] i just watched this today on tv . it was on abc ' s sunday afternoon movie . < br / > < br / > this wasn ' t a very good movie , but for a low budget independent film like this , it was okay . there is some suspense in it , but there are so many bad qualities that really bring the movie down . the script is pretty lame , and the plot elements aren ' t very realistic , such as the way a 911 operator would laugh and hang up when someone is reporting a murder . i don ' t know what the writer was thinking when they came up with that idea , but it isn [SEP]\n",
592
+ "INFO:tensorflow:input_ids: 101 1045 2074 3427 2023 2651 2006 2694 1012 2009 2001 2006 5925 1005 1055 4465 5027 3185 1012 1026 7987 1013 1028 1026 7987 1013 1028 2023 2347 1005 1056 1037 2200 2204 3185 1010 2021 2005 1037 2659 5166 2981 2143 2066 2023 1010 2009 2001 3100 1012 2045 2003 2070 23873 1999 2009 1010 2021 2045 2024 2061 2116 2919 11647 2008 2428 3288 1996 3185 2091 1012 1996 5896 2003 3492 20342 1010 1998 1996 5436 3787 4995 1005 1056 2200 12689 1010 2107 2004 1996 2126 1037 19989 6872 2052 4756 1998 6865 2039 2043 2619 2003 7316 1037 4028 1012 1045 2123 1005 1056 2113 2054 1996 3213 2001 3241 2043 2027 2234 2039 2007 2008 2801 1010 2021 2009 3475 102\n",
593
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
594
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
595
+ "INFO:tensorflow:label: 0 (id = 0)\n",
596
+ "INFO:tensorflow:*** Example ***\n",
597
+ "INFO:tensorflow:guid: None\n",
598
+ "INFO:tensorflow:tokens: [CLS] from hardly alien sounding lasers , to an elementary school style shuttle crash , \" night ##be ##ast \" is better classified as a far ##cic ##al mix of fake blood and bare chest . the almost pornographic style of the film seems to be a failed attempt to recover from a lack of co ##hesive or effective story . the acting however is not nearly as beast ##ly , many of the young , aspiring , actors ad ##mir ##ably showcase a hidden talent . particularly don lei ##fer ##t and jamie ze ##mare ##l , who shed a well needed sha ##rd of light on this otherwise terrible film . night ##be ##ast would have never shown up on set had he known the [SEP]\n",
599
+ "INFO:tensorflow:input_ids: 101 2013 6684 7344 9391 23965 1010 2000 2019 4732 2082 2806 10382 5823 1010 1000 2305 4783 14083 1000 2003 2488 6219 2004 1037 2521 19053 2389 4666 1997 8275 2668 1998 6436 3108 1012 1996 2471 26932 2806 1997 1996 2143 3849 2000 2022 1037 3478 3535 2000 8980 2013 1037 3768 1997 2522 21579 2030 4621 2466 1012 1996 3772 2174 2003 2025 3053 2004 6841 2135 1010 2116 1997 1996 2402 1010 22344 1010 5889 4748 14503 8231 13398 1037 5023 5848 1012 3391 2123 26947 7512 2102 1998 6175 27838 24376 2140 1010 2040 8328 1037 2092 2734 21146 4103 1997 2422 2006 2023 4728 6659 2143 1012 2305 4783 14083 2052 2031 2196 3491 2039 2006 2275 2018 2002 2124 1996 102\n",
600
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
601
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
602
+ "INFO:tensorflow:label: 0 (id = 0)\n",
603
+ "INFO:tensorflow:*** Example ***\n",
604
+ "INFO:tensorflow:guid: None\n",
605
+ "INFO:tensorflow:tokens: [CLS] here we have the in ##imi ##table charlie chaplin for ##sa ##king his slap ##stick past to tackle the serious subject of anti - semi ##tism , and into ##ler ##ance in general . he portrays two characters - the sweet , innocent jewish barber - a war veteran , and the ravi ##ng and ruthless dictator , aden ##oid h ##yn ##kel . the jewish ghetto in this country is not safe for long , due to the w ##him ##s of h ##yn ##kel and his armed thugs , who routinely rough up its residents , or leave them alone , dependent upon his mood that day or week . the barber is among them , but is befriended by his former commanding officer [SEP]\n",
606
+ "INFO:tensorflow:input_ids: 101 2182 2057 2031 1996 1999 27605 10880 4918 23331 2005 3736 6834 2010 14308 21354 2627 2000 11147 1996 3809 3395 1997 3424 1011 4100 17456 1010 1998 2046 3917 6651 1999 2236 1012 2002 17509 2048 3494 1011 1996 4086 1010 7036 3644 13362 1011 1037 2162 8003 1010 1998 1996 16806 3070 1998 18101 21237 1010 16298 9314 1044 6038 11705 1012 1996 3644 17276 1999 2023 2406 2003 2025 3647 2005 2146 1010 2349 2000 1996 1059 14341 2015 1997 1044 6038 11705 1998 2010 4273 24106 1010 2040 19974 5931 2039 2049 3901 1010 2030 2681 2068 2894 1010 7790 2588 2010 6888 2008 2154 2030 2733 1012 1996 13362 2003 2426 2068 1010 2021 2003 23386 2011 2010 2280 7991 2961 102\n",
607
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
608
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
609
+ "INFO:tensorflow:label: 1 (id = 1)\n",
610
+ "INFO:tensorflow:*** Example ***\n",
611
+ "INFO:tensorflow:guid: None\n",
612
+ "INFO:tensorflow:tokens: [CLS] i really hated this movie and it ' s the first movie written by stephen king that i didn ' t finish . i was truly disappointed , it was the worst crap i ' ve ever seen . what were you thinking making three hours out of it ? it may have a quite good story , but actors ? no . suspense ? no . romance ? no . horror ? no . it didn ' t have anything . < br / > < br / > it ' s got this strange , crazy science man with einstein - hair , the classic thing . not real at all . and a man keep getting younger all the time . it seems [SEP]\n",
613
+ "INFO:tensorflow:input_ids: 101 1045 2428 6283 2023 3185 1998 2009 1005 1055 1996 2034 3185 2517 2011 4459 2332 2008 1045 2134 1005 1056 3926 1012 1045 2001 5621 9364 1010 2009 2001 1996 5409 10231 1045 1005 2310 2412 2464 1012 2054 2020 2017 3241 2437 2093 2847 2041 1997 2009 1029 2009 2089 2031 1037 3243 2204 2466 1010 2021 5889 1029 2053 1012 23873 1029 2053 1012 7472 1029 2053 1012 5469 1029 2053 1012 2009 2134 1005 1056 2031 2505 1012 1026 7987 1013 1028 1026 7987 1013 1028 2009 1005 1055 2288 2023 4326 1010 4689 2671 2158 2007 15313 1011 2606 1010 1996 4438 2518 1012 2025 2613 2012 2035 1012 1998 1037 2158 2562 2893 3920 2035 1996 2051 1012 2009 3849 102\n",
614
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
615
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
616
+ "INFO:tensorflow:label: 0 (id = 0)\n",
617
+ "INFO:tensorflow:*** Example ***\n",
618
+ "INFO:tensorflow:guid: None\n",
619
+ "INFO:tensorflow:tokens: [CLS] story chinese tall story tells the story of righteous monk trip ##ita ##ka , who , along with his guardians monkey , sandy and pigs ##y make their journey west on a quest to recover ancient sutra ##s , finally , they reach the final leg of their journey in sha ##che city but all is not as it seems when the city is attacked by evil tree demons . monkey tries his best to battle them but is overwhelmed , knowing his master is in grave danger , he uses his trust ##y golden staff to thrust trip ##ita ##ka to safety . < br / > < br / > the monk ends up being knocked out when he land and when he wakes [SEP]\n",
620
+ "INFO:tensorflow:input_ids: 101 2466 2822 4206 2466 4136 1996 2466 1997 19556 8284 4440 6590 2912 1010 2040 1010 2247 2007 2010 14240 10608 1010 7525 1998 14695 2100 2191 2037 4990 2225 2006 1037 8795 2000 8980 3418 26567 2015 1010 2633 1010 2027 3362 1996 2345 4190 1997 2037 4990 1999 21146 5403 2103 2021 2035 2003 2025 2004 2009 3849 2043 1996 2103 2003 4457 2011 4763 3392 7942 1012 10608 5363 2010 2190 2000 2645 2068 2021 2003 13394 1010 4209 2010 3040 2003 1999 6542 5473 1010 2002 3594 2010 3404 2100 3585 3095 2000 7400 4440 6590 2912 2000 3808 1012 1026 7987 1013 1028 1026 7987 1013 1028 1996 8284 4515 2039 2108 6573 2041 2043 2002 2455 1998 2043 2002 17507 102\n",
621
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
622
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
623
+ "INFO:tensorflow:label: 1 (id = 1)\n"
624
+ ],
625
+ "name": "stdout"
626
+ }
627
+ ]
628
+ },
629
+ {
630
+ "metadata": {
631
+ "id": "ccp5trMwRtmr",
632
+ "colab_type": "text"
633
+ },
634
+ "cell_type": "markdown",
635
+ "source": [
636
+ "#Creating a model\n",
637
+ "\n",
638
+ "Now that we've prepared our data, let's focus on building a model. `create_model` does just this below. First, it loads the BERT tf hub module again (this time to extract the computation graph). Next, it creates a single new layer that will be trained to adapt BERT to our sentiment task (i.e. classifying whether a movie review is positive or negative). This strategy of using a mostly trained model is called [fine-tuning](http://wiki.fast.ai/index.php/Fine_tuning)."
639
+ ]
640
+ },
641
+ {
642
+ "metadata": {
643
+ "id": "6o2a5ZIvRcJq",
644
+ "colab_type": "code",
645
+ "colab": {}
646
+ },
647
+ "cell_type": "code",
648
+ "source": [
649
+ "def create_model(is_predicting, input_ids, input_mask, segment_ids, labels,\n",
650
+ " num_labels):\n",
651
+ " \"\"\"Creates a classification model.\"\"\"\n",
652
+ "\n",
653
+ " bert_module = hub.Module(\n",
654
+ " BERT_MODEL_HUB,\n",
655
+ " trainable=True)\n",
656
+ " bert_inputs = dict(\n",
657
+ " input_ids=input_ids,\n",
658
+ " input_mask=input_mask,\n",
659
+ " segment_ids=segment_ids)\n",
660
+ " bert_outputs = bert_module(\n",
661
+ " inputs=bert_inputs,\n",
662
+ " signature=\"tokens\",\n",
663
+ " as_dict=True)\n",
664
+ "\n",
665
+ " # Use \"pooled_output\" for classification tasks on an entire sentence.\n",
666
+ " # Use \"sequence_outputs\" for token-level output.\n",
667
+ " output_layer = bert_outputs[\"pooled_output\"]\n",
668
+ "\n",
669
+ " hidden_size = output_layer.shape[-1].value\n",
670
+ "\n",
671
+ " # Create our own layer to tune for politeness data.\n",
672
+ " output_weights = tf.get_variable(\n",
673
+ " \"output_weights\", [num_labels, hidden_size],\n",
674
+ " initializer=tf.truncated_normal_initializer(stddev=0.02))\n",
675
+ "\n",
676
+ " output_bias = tf.get_variable(\n",
677
+ " \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n",
678
+ "\n",
679
+ " with tf.variable_scope(\"loss\"):\n",
680
+ "\n",
681
+ " # Dropout helps prevent overfitting\n",
682
+ " output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n",
683
+ "\n",
684
+ " logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n",
685
+ " logits = tf.nn.bias_add(logits, output_bias)\n",
686
+ " log_probs = tf.nn.log_softmax(logits, axis=-1)\n",
687
+ "\n",
688
+ " # Convert labels into one-hot encoding\n",
689
+ " one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n",
690
+ "\n",
691
+ " predicted_labels = tf.squeeze(tf.argmax(log_probs, axis=-1, output_type=tf.int32))\n",
692
+ " # If we're predicting, we want predicted labels and the probabiltiies.\n",
693
+ " if is_predicting:\n",
694
+ " return (predicted_labels, log_probs)\n",
695
+ "\n",
696
+ " # If we're train/eval, compute loss between predicted and actual label\n",
697
+ " per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n",
698
+ " loss = tf.reduce_mean(per_example_loss)\n",
699
+ " return (loss, predicted_labels, log_probs)\n"
700
+ ],
701
+ "execution_count": 0,
702
+ "outputs": []
703
+ },
704
+ {
705
+ "metadata": {
706
+ "id": "qpE0ZIDOCQzE",
707
+ "colab_type": "text"
708
+ },
709
+ "cell_type": "markdown",
710
+ "source": [
711
+ "Next we'll wrap our model function in a `model_fn_builder` function that adapts our model to work for training, evaluation, and prediction."
712
+ ]
713
+ },
714
+ {
715
+ "metadata": {
716
+ "id": "FnH-AnOQ9KKW",
717
+ "colab_type": "code",
718
+ "colab": {}
719
+ },
720
+ "cell_type": "code",
721
+ "source": [
722
+ "# model_fn_builder actually creates our model function\n",
723
+ "# using the passed parameters for num_labels, learning_rate, etc.\n",
724
+ "def model_fn_builder(num_labels, learning_rate, num_train_steps,\n",
725
+ " num_warmup_steps):\n",
726
+ " \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n",
727
+ " def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n",
728
+ " \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n",
729
+ "\n",
730
+ " input_ids = features[\"input_ids\"]\n",
731
+ " input_mask = features[\"input_mask\"]\n",
732
+ " segment_ids = features[\"segment_ids\"]\n",
733
+ " label_ids = features[\"label_ids\"]\n",
734
+ "\n",
735
+ " is_predicting = (mode == tf.estimator.ModeKeys.PREDICT)\n",
736
+ " \n",
737
+ " # TRAIN and EVAL\n",
738
+ " if not is_predicting:\n",
739
+ "\n",
740
+ " (loss, predicted_labels, log_probs) = create_model(\n",
741
+ " is_predicting, input_ids, input_mask, segment_ids, label_ids, num_labels)\n",
742
+ "\n",
743
+ " train_op = bert.optimization.create_optimizer(\n",
744
+ " loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu=False)\n",
745
+ "\n",
746
+ " # Calculate evaluation metrics. \n",
747
+ " def metric_fn(label_ids, predicted_labels):\n",
748
+ " accuracy = tf.metrics.accuracy(label_ids, predicted_labels)\n",
749
+ " f1_score = tf.contrib.metrics.f1_score(\n",
750
+ " label_ids,\n",
751
+ " predicted_labels)\n",
752
+ " auc = tf.metrics.auc(\n",
753
+ " label_ids,\n",
754
+ " predicted_labels)\n",
755
+ " recall = tf.metrics.recall(\n",
756
+ " label_ids,\n",
757
+ " predicted_labels)\n",
758
+ " precision = tf.metrics.precision(\n",
759
+ " label_ids,\n",
760
+ " predicted_labels) \n",
761
+ " true_pos = tf.metrics.true_positives(\n",
762
+ " label_ids,\n",
763
+ " predicted_labels)\n",
764
+ " true_neg = tf.metrics.true_negatives(\n",
765
+ " label_ids,\n",
766
+ " predicted_labels) \n",
767
+ " false_pos = tf.metrics.false_positives(\n",
768
+ " label_ids,\n",
769
+ " predicted_labels) \n",
770
+ " false_neg = tf.metrics.false_negatives(\n",
771
+ " label_ids,\n",
772
+ " predicted_labels)\n",
773
+ " return {\n",
774
+ " \"eval_accuracy\": accuracy,\n",
775
+ " \"f1_score\": f1_score,\n",
776
+ " \"auc\": auc,\n",
777
+ " \"precision\": precision,\n",
778
+ " \"recall\": recall,\n",
779
+ " \"true_positives\": true_pos,\n",
780
+ " \"true_negatives\": true_neg,\n",
781
+ " \"false_positives\": false_pos,\n",
782
+ " \"false_negatives\": false_neg\n",
783
+ " }\n",
784
+ "\n",
785
+ " eval_metrics = metric_fn(label_ids, predicted_labels)\n",
786
+ "\n",
787
+ " if mode == tf.estimator.ModeKeys.TRAIN:\n",
788
+ " return tf.estimator.EstimatorSpec(mode=mode,\n",
789
+ " loss=loss,\n",
790
+ " train_op=train_op)\n",
791
+ " else:\n",
792
+ " return tf.estimator.EstimatorSpec(mode=mode,\n",
793
+ " loss=loss,\n",
794
+ " eval_metric_ops=eval_metrics)\n",
795
+ " else:\n",
796
+ " (predicted_labels, log_probs) = create_model(\n",
797
+ " is_predicting, input_ids, input_mask, segment_ids, label_ids, num_labels)\n",
798
+ "\n",
799
+ " predictions = {\n",
800
+ " 'probabilities': log_probs,\n",
801
+ " 'labels': predicted_labels\n",
802
+ " }\n",
803
+ " return tf.estimator.EstimatorSpec(mode, predictions=predictions)\n",
804
+ "\n",
805
+ " # Return the actual model function in the closure\n",
806
+ " return model_fn\n"
807
+ ],
808
+ "execution_count": 0,
809
+ "outputs": []
810
+ },
811
+ {
812
+ "metadata": {
813
+ "id": "OjwJ4bTeWXD8",
814
+ "colab_type": "code",
815
+ "colab": {}
816
+ },
817
+ "cell_type": "code",
818
+ "source": [
819
+ "# Compute train and warmup steps from batch size\n",
820
+ "# These hyperparameters are copied from this colab notebook (https://colab.sandbox.google.com/github/tensorflow/tpu/blob/master/tools/colab/bert_finetuning_with_cloud_tpus.ipynb)\n",
821
+ "BATCH_SIZE = 32\n",
822
+ "LEARNING_RATE = 2e-5\n",
823
+ "NUM_TRAIN_EPOCHS = 3.0\n",
824
+ "# Warmup is a period of time where hte learning rate \n",
825
+ "# is small and gradually increases--usually helps training.\n",
826
+ "WARMUP_PROPORTION = 0.1\n",
827
+ "# Model configs\n",
828
+ "SAVE_CHECKPOINTS_STEPS = 500\n",
829
+ "SAVE_SUMMARY_STEPS = 100"
830
+ ],
831
+ "execution_count": 0,
832
+ "outputs": []
833
+ },
834
+ {
835
+ "metadata": {
836
+ "id": "emHf9GhfWBZ_",
837
+ "colab_type": "code",
838
+ "colab": {}
839
+ },
840
+ "cell_type": "code",
841
+ "source": [
842
+ "# Compute # train and warmup steps from batch size\n",
843
+ "num_train_steps = int(len(train_features) / BATCH_SIZE * NUM_TRAIN_EPOCHS)\n",
844
+ "num_warmup_steps = int(num_train_steps * WARMUP_PROPORTION)"
845
+ ],
846
+ "execution_count": 0,
847
+ "outputs": []
848
+ },
849
+ {
850
+ "metadata": {
851
+ "id": "oEJldMr3WYZa",
852
+ "colab_type": "code",
853
+ "colab": {}
854
+ },
855
+ "cell_type": "code",
856
+ "source": [
857
+ "# Specify outpit directory and number of checkpoint steps to save\n",
858
+ "run_config = tf.estimator.RunConfig(\n",
859
+ " model_dir=OUTPUT_DIR,\n",
860
+ " save_summary_steps=SAVE_SUMMARY_STEPS,\n",
861
+ " save_checkpoints_steps=SAVE_CHECKPOINTS_STEPS)"
862
+ ],
863
+ "execution_count": 0,
864
+ "outputs": []
865
+ },
866
+ {
867
+ "metadata": {
868
+ "id": "q_WebpS1X97v",
869
+ "colab_type": "code",
870
+ "outputId": "1648932a-7391-49d3-8af7-52d514e226e8",
871
+ "colab": {
872
+ "base_uri": "https://localhost:8080/",
873
+ "height": 156
874
+ }
875
+ },
876
+ "cell_type": "code",
877
+ "source": [
878
+ "model_fn = model_fn_builder(\n",
879
+ " num_labels=len(label_list),\n",
880
+ " learning_rate=LEARNING_RATE,\n",
881
+ " num_train_steps=num_train_steps,\n",
882
+ " num_warmup_steps=num_warmup_steps)\n",
883
+ "\n",
884
+ "estimator = tf.estimator.Estimator(\n",
885
+ " model_fn=model_fn,\n",
886
+ " config=run_config,\n",
887
+ " params={\"batch_size\": BATCH_SIZE})\n"
888
+ ],
889
+ "execution_count": 55,
890
+ "outputs": [
891
+ {
892
+ "output_type": "stream",
893
+ "text": [
894
+ "INFO:tensorflow:Using config: {'_model_dir': 'gs://bert-tfhub/aclImdb_v1', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 500, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n",
895
+ "graph_options {\n",
896
+ " rewrite_options {\n",
897
+ " meta_optimizer_iterations: ONE\n",
898
+ " }\n",
899
+ "}\n",
900
+ ", '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fcedb507be0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\n"
901
+ ],
902
+ "name": "stdout"
903
+ }
904
+ ]
905
+ },
906
+ {
907
+ "metadata": {
908
+ "id": "NOO3RfG1DYLo",
909
+ "colab_type": "text"
910
+ },
911
+ "cell_type": "markdown",
912
+ "source": [
913
+ "Next we create an input builder function that takes our training feature set (`train_features`) and produces a generator. This is a pretty standard design pattern for working with Tensorflow [Estimators](https://www.tensorflow.org/guide/estimators)."
914
+ ]
915
+ },
916
+ {
917
+ "metadata": {
918
+ "id": "1Pv2bAlOX_-K",
919
+ "colab_type": "code",
920
+ "colab": {}
921
+ },
922
+ "cell_type": "code",
923
+ "source": [
924
+ "# Create an input function for training. drop_remainder = True for using TPUs.\n",
925
+ "train_input_fn = bert.run_classifier.input_fn_builder(\n",
926
+ " features=train_features,\n",
927
+ " seq_length=MAX_SEQ_LENGTH,\n",
928
+ " is_training=True,\n",
929
+ " drop_remainder=False)"
930
+ ],
931
+ "execution_count": 0,
932
+ "outputs": []
933
+ },
934
+ {
935
+ "metadata": {
936
+ "id": "t6Nukby2EB6-",
937
+ "colab_type": "text"
938
+ },
939
+ "cell_type": "markdown",
940
+ "source": [
941
+ "Now we train our model! For me, using a Colab notebook running on Google's GPUs, my training time was about 14 minutes."
942
+ ]
943
+ },
944
+ {
945
+ "metadata": {
946
+ "id": "nucD4gluYJmK",
947
+ "colab_type": "code",
948
+ "outputId": "5d728e72-4631-42bf-c48d-3f51d4b968ce",
949
+ "colab": {
950
+ "base_uri": "https://localhost:8080/",
951
+ "height": 68
952
+ }
953
+ },
954
+ "cell_type": "code",
955
+ "source": [
956
+ "print(f'Beginning Training!')\n",
957
+ "current_time = datetime.now()\n",
958
+ "estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n",
959
+ "print(\"Training took time \", datetime.now() - current_time)"
960
+ ],
961
+ "execution_count": 57,
962
+ "outputs": [
963
+ {
964
+ "output_type": "stream",
965
+ "text": [
966
+ "Beginning Training!\n",
967
+ "INFO:tensorflow:Skipping training since max_steps has already saved.\n",
968
+ "Training took time 0:00:00.759709\n"
969
+ ],
970
+ "name": "stdout"
971
+ }
972
+ ]
973
+ },
974
+ {
975
+ "metadata": {
976
+ "id": "CmbLTVniARy3",
977
+ "colab_type": "text"
978
+ },
979
+ "cell_type": "markdown",
980
+ "source": [
981
+ "Now let's use our test data to see how well our model did:"
982
+ ]
983
+ },
984
+ {
985
+ "metadata": {
986
+ "id": "JIhejfpyJ8Bx",
987
+ "colab_type": "code",
988
+ "colab": {}
989
+ },
990
+ "cell_type": "code",
991
+ "source": [
992
+ "test_input_fn = run_classifier.input_fn_builder(\n",
993
+ " features=test_features,\n",
994
+ " seq_length=MAX_SEQ_LENGTH,\n",
995
+ " is_training=False,\n",
996
+ " drop_remainder=False)"
997
+ ],
998
+ "execution_count": 0,
999
+ "outputs": []
1000
+ },
1001
+ {
1002
+ "metadata": {
1003
+ "id": "PPVEXhNjYXC-",
1004
+ "colab_type": "code",
1005
+ "outputId": "dd5482cd-c558-465f-c854-ec11a0175316",
1006
+ "colab": {
1007
+ "base_uri": "https://localhost:8080/",
1008
+ "height": 445
1009
+ }
1010
+ },
1011
+ "cell_type": "code",
1012
+ "source": [
1013
+ "estimator.evaluate(input_fn=test_input_fn, steps=None)"
1014
+ ],
1015
+ "execution_count": 59,
1016
+ "outputs": [
1017
+ {
1018
+ "output_type": "stream",
1019
+ "text": [
1020
+ "INFO:tensorflow:Calling model_fn.\n",
1021
+ "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n"
1022
+ ],
1023
+ "name": "stdout"
1024
+ },
1025
+ {
1026
+ "output_type": "stream",
1027
+ "text": [
1028
+ "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gradients_impl.py:110: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n",
1029
+ " \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n"
1030
+ ],
1031
+ "name": "stderr"
1032
+ },
1033
+ {
1034
+ "output_type": "stream",
1035
+ "text": [
1036
+ "INFO:tensorflow:Done calling model_fn.\n",
1037
+ "INFO:tensorflow:Starting evaluation at 2019-02-12T21:04:20Z\n",
1038
+ "INFO:tensorflow:Graph was finalized.\n",
1039
+ "INFO:tensorflow:Restoring parameters from gs://bert-tfhub/aclImdb_v1/model.ckpt-468\n",
1040
+ "INFO:tensorflow:Running local_init_op.\n",
1041
+ "INFO:tensorflow:Done running local_init_op.\n",
1042
+ "INFO:tensorflow:Finished evaluation at 2019-02-12-21:06:05\n",
1043
+ "INFO:tensorflow:Saving dict for global step 468: auc = 0.86659324, eval_accuracy = 0.8664, f1_score = 0.8659711, false_negatives = 375.0, false_positives = 293.0, global_step = 468, loss = 0.51870537, precision = 0.880457, recall = 0.8519542, true_negatives = 2174.0, true_positives = 2158.0\n",
1044
+ "INFO:tensorflow:Saving 'checkpoint_path' summary for global step 468: gs://bert-tfhub/aclImdb_v1/model.ckpt-468\n"
1045
+ ],
1046
+ "name": "stdout"
1047
+ },
1048
+ {
1049
+ "output_type": "execute_result",
1050
+ "data": {
1051
+ "text/plain": [
1052
+ "{'auc': 0.86659324,\n",
1053
+ " 'eval_accuracy': 0.8664,\n",
1054
+ " 'f1_score': 0.8659711,\n",
1055
+ " 'false_negatives': 375.0,\n",
1056
+ " 'false_positives': 293.0,\n",
1057
+ " 'global_step': 468,\n",
1058
+ " 'loss': 0.51870537,\n",
1059
+ " 'precision': 0.880457,\n",
1060
+ " 'recall': 0.8519542,\n",
1061
+ " 'true_negatives': 2174.0,\n",
1062
+ " 'true_positives': 2158.0}"
1063
+ ]
1064
+ },
1065
+ "metadata": {
1066
+ "tags": []
1067
+ },
1068
+ "execution_count": 59
1069
+ }
1070
+ ]
1071
+ },
1072
+ {
1073
+ "metadata": {
1074
+ "id": "ueKsULteiz1B",
1075
+ "colab_type": "text"
1076
+ },
1077
+ "cell_type": "markdown",
1078
+ "source": [
1079
+ "Now let's write code to make predictions on new sentences:"
1080
+ ]
1081
+ },
1082
+ {
1083
+ "metadata": {
1084
+ "id": "OsrbTD2EJTVl",
1085
+ "colab_type": "code",
1086
+ "colab": {}
1087
+ },
1088
+ "cell_type": "code",
1089
+ "source": [
1090
+ "def getPrediction(in_sentences):\n",
1091
+ " labels = [\"Negative\", \"Positive\"]\n",
1092
+ " input_examples = [run_classifier.InputExample(guid=\"\", text_a = x, text_b = None, label = 0) for x in in_sentences] # here, \"\" is just a dummy label\n",
1093
+ " input_features = run_classifier.convert_examples_to_features(input_examples, label_list, MAX_SEQ_LENGTH, tokenizer)\n",
1094
+ " predict_input_fn = run_classifier.input_fn_builder(features=input_features, seq_length=MAX_SEQ_LENGTH, is_training=False, drop_remainder=False)\n",
1095
+ " predictions = estimator.predict(predict_input_fn)\n",
1096
+ " return [(sentence, prediction['probabilities'], labels[prediction['labels']]) for sentence, prediction in zip(in_sentences, predictions)]"
1097
+ ],
1098
+ "execution_count": 0,
1099
+ "outputs": []
1100
+ },
1101
+ {
1102
+ "metadata": {
1103
+ "id": "-thbodgih_VJ",
1104
+ "colab_type": "code",
1105
+ "colab": {}
1106
+ },
1107
+ "cell_type": "code",
1108
+ "source": [
1109
+ "pred_sentences = [\n",
1110
+ " \"That movie was absolutely awful\",\n",
1111
+ " \"The acting was a bit lacking\",\n",
1112
+ " \"The film was creative and surprising\",\n",
1113
+ " \"Absolutely fantastic!\"\n",
1114
+ "]"
1115
+ ],
1116
+ "execution_count": 0,
1117
+ "outputs": []
1118
+ },
1119
+ {
1120
+ "metadata": {
1121
+ "id": "QrZmvZySKQTm",
1122
+ "colab_type": "code",
1123
+ "colab": {
1124
+ "base_uri": "https://localhost:8080/",
1125
+ "height": 649
1126
+ },
1127
+ "outputId": "3891fafb-a460-4eb8-fa6c-335a5bbc10e5"
1128
+ },
1129
+ "cell_type": "code",
1130
+ "source": [
1131
+ "predictions = getPrediction(pred_sentences)"
1132
+ ],
1133
+ "execution_count": 72,
1134
+ "outputs": [
1135
+ {
1136
+ "output_type": "stream",
1137
+ "text": [
1138
+ "INFO:tensorflow:Writing example 0 of 4\n",
1139
+ "INFO:tensorflow:*** Example ***\n",
1140
+ "INFO:tensorflow:guid: \n",
1141
+ "INFO:tensorflow:tokens: [CLS] that movie was absolutely awful [SEP]\n",
1142
+ "INFO:tensorflow:input_ids: 101 2008 3185 2001 7078 9643 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1143
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1144
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1145
+ "INFO:tensorflow:label: 0 (id = 0)\n",
1146
+ "INFO:tensorflow:*** Example ***\n",
1147
+ "INFO:tensorflow:guid: \n",
1148
+ "INFO:tensorflow:tokens: [CLS] the acting was a bit lacking [SEP]\n",
1149
+ "INFO:tensorflow:input_ids: 101 1996 3772 2001 1037 2978 11158 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1150
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1151
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1152
+ "INFO:tensorflow:label: 0 (id = 0)\n",
1153
+ "INFO:tensorflow:*** Example ***\n",
1154
+ "INFO:tensorflow:guid: \n",
1155
+ "INFO:tensorflow:tokens: [CLS] the film was creative and surprising [SEP]\n",
1156
+ "INFO:tensorflow:input_ids: 101 1996 2143 2001 5541 1998 11341 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1157
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1158
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1159
+ "INFO:tensorflow:label: 0 (id = 0)\n",
1160
+ "INFO:tensorflow:*** Example ***\n",
1161
+ "INFO:tensorflow:guid: \n",
1162
+ "INFO:tensorflow:tokens: [CLS] absolutely fantastic ! [SEP]\n",
1163
+ "INFO:tensorflow:input_ids: 101 7078 10392 999 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1164
+ "INFO:tensorflow:input_mask: 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1165
+ "INFO:tensorflow:segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
1166
+ "INFO:tensorflow:label: 0 (id = 0)\n",
1167
+ "INFO:tensorflow:Calling model_fn.\n",
1168
+ "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n",
1169
+ "INFO:tensorflow:Done calling model_fn.\n",
1170
+ "INFO:tensorflow:Graph was finalized.\n",
1171
+ "INFO:tensorflow:Restoring parameters from gs://bert-tfhub/aclImdb_v1/model.ckpt-468\n",
1172
+ "INFO:tensorflow:Running local_init_op.\n",
1173
+ "INFO:tensorflow:Done running local_init_op.\n"
1174
+ ],
1175
+ "name": "stdout"
1176
+ }
1177
+ ]
1178
+ },
1179
+ {
1180
+ "metadata": {
1181
+ "id": "MXkRiEBUqN3n",
1182
+ "colab_type": "text"
1183
+ },
1184
+ "cell_type": "markdown",
1185
+ "source": [
1186
+ "Voila! We have a sentiment classifier!"
1187
+ ]
1188
+ },
1189
+ {
1190
+ "metadata": {
1191
+ "id": "ERkTE8-7oQLZ",
1192
+ "colab_type": "code",
1193
+ "colab": {
1194
+ "base_uri": "https://localhost:8080/",
1195
+ "height": 221
1196
+ },
1197
+ "outputId": "26c33224-dc2c-4b3d-f7b4-ac3ef0a58b27"
1198
+ },
1199
+ "cell_type": "code",
1200
+ "source": [
1201
+ "predictions"
1202
+ ],
1203
+ "execution_count": 73,
1204
+ "outputs": [
1205
+ {
1206
+ "output_type": "execute_result",
1207
+ "data": {
1208
+ "text/plain": [
1209
+ "[('That movie was absolutely awful',\n",
1210
+ " array([-4.9142293e-03, -5.3180690e+00], dtype=float32),\n",
1211
+ " 'Negative'),\n",
1212
+ " ('The acting was a bit lacking',\n",
1213
+ " array([-0.03325794, -3.4200459 ], dtype=float32),\n",
1214
+ " 'Negative'),\n",
1215
+ " ('The film was creative and surprising',\n",
1216
+ " array([-5.3589125e+00, -4.7171740e-03], dtype=float32),\n",
1217
+ " 'Positive'),\n",
1218
+ " ('Absolutely fantastic!',\n",
1219
+ " array([-5.0434084 , -0.00647258], dtype=float32),\n",
1220
+ " 'Positive')]"
1221
+ ]
1222
+ },
1223
+ "metadata": {
1224
+ "tags": []
1225
+ },
1226
+ "execution_count": 73
1227
+ }
1228
+ ]
1229
+ }
1230
+ ]
1231
+ }
bert-master/bert-master/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ tensorflow >= 1.11.0 # CPU Version of TensorFlow.
2
+ # tensorflow-gpu >= 1.11.0 # GPU version of TensorFlow.
bert-master/bert-master/run_classifier.py ADDED
@@ -0,0 +1,981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BERT finetuning runner."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import collections
22
+ import csv
23
+ import os
24
+ import modeling
25
+ import optimization
26
+ import tokenization
27
+ import tensorflow as tf
28
+
29
+ flags = tf.flags
30
+
31
+ FLAGS = flags.FLAGS
32
+
33
+ ## Required parameters
34
+ flags.DEFINE_string(
35
+ "data_dir", None,
36
+ "The input data dir. Should contain the .tsv files (or other data files) "
37
+ "for the task.")
38
+
39
+ flags.DEFINE_string(
40
+ "bert_config_file", None,
41
+ "The config json file corresponding to the pre-trained BERT model. "
42
+ "This specifies the model architecture.")
43
+
44
+ flags.DEFINE_string("task_name", None, "The name of the task to train.")
45
+
46
+ flags.DEFINE_string("vocab_file", None,
47
+ "The vocabulary file that the BERT model was trained on.")
48
+
49
+ flags.DEFINE_string(
50
+ "output_dir", None,
51
+ "The output directory where the model checkpoints will be written.")
52
+
53
+ ## Other parameters
54
+
55
+ flags.DEFINE_string(
56
+ "init_checkpoint", None,
57
+ "Initial checkpoint (usually from a pre-trained BERT model).")
58
+
59
+ flags.DEFINE_bool(
60
+ "do_lower_case", True,
61
+ "Whether to lower case the input text. Should be True for uncased "
62
+ "models and False for cased models.")
63
+
64
+ flags.DEFINE_integer(
65
+ "max_seq_length", 128,
66
+ "The maximum total input sequence length after WordPiece tokenization. "
67
+ "Sequences longer than this will be truncated, and sequences shorter "
68
+ "than this will be padded.")
69
+
70
+ flags.DEFINE_bool("do_train", False, "Whether to run training.")
71
+
72
+ flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
73
+
74
+ flags.DEFINE_bool(
75
+ "do_predict", False,
76
+ "Whether to run the model in inference mode on the test set.")
77
+
78
+ flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
79
+
80
+ flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
81
+
82
+ flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
83
+
84
+ flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
85
+
86
+ flags.DEFINE_float("num_train_epochs", 3.0,
87
+ "Total number of training epochs to perform.")
88
+
89
+ flags.DEFINE_float(
90
+ "warmup_proportion", 0.1,
91
+ "Proportion of training to perform linear learning rate warmup for. "
92
+ "E.g., 0.1 = 10% of training.")
93
+
94
+ flags.DEFINE_integer("save_checkpoints_steps", 1000,
95
+ "How often to save the model checkpoint.")
96
+
97
+ flags.DEFINE_integer("iterations_per_loop", 1000,
98
+ "How many steps to make in each estimator call.")
99
+
100
+ flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
101
+
102
+ tf.flags.DEFINE_string(
103
+ "tpu_name", None,
104
+ "The Cloud TPU to use for training. This should be either the name "
105
+ "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
106
+ "url.")
107
+
108
+ tf.flags.DEFINE_string(
109
+ "tpu_zone", None,
110
+ "[Optional] GCE zone where the Cloud TPU is located in. If not "
111
+ "specified, we will attempt to automatically detect the GCE project from "
112
+ "metadata.")
113
+
114
+ tf.flags.DEFINE_string(
115
+ "gcp_project", None,
116
+ "[Optional] Project name for the Cloud TPU-enabled project. If not "
117
+ "specified, we will attempt to automatically detect the GCE project from "
118
+ "metadata.")
119
+
120
+ tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
121
+
122
+ flags.DEFINE_integer(
123
+ "num_tpu_cores", 8,
124
+ "Only used if `use_tpu` is True. Total number of TPU cores to use.")
125
+
126
+
127
+ class InputExample(object):
128
+ """A single training/test example for simple sequence classification."""
129
+
130
+ def __init__(self, guid, text_a, text_b=None, label=None):
131
+ """Constructs a InputExample.
132
+
133
+ Args:
134
+ guid: Unique id for the example.
135
+ text_a: string. The untokenized text of the first sequence. For single
136
+ sequence tasks, only this sequence must be specified.
137
+ text_b: (Optional) string. The untokenized text of the second sequence.
138
+ Only must be specified for sequence pair tasks.
139
+ label: (Optional) string. The label of the example. This should be
140
+ specified for train and dev examples, but not for test examples.
141
+ """
142
+ self.guid = guid
143
+ self.text_a = text_a
144
+ self.text_b = text_b
145
+ self.label = label
146
+
147
+
148
+ class PaddingInputExample(object):
149
+ """Fake example so the num input examples is a multiple of the batch size.
150
+
151
+ When running eval/predict on the TPU, we need to pad the number of examples
152
+ to be a multiple of the batch size, because the TPU requires a fixed batch
153
+ size. The alternative is to drop the last batch, which is bad because it means
154
+ the entire output data won't be generated.
155
+
156
+ We use this class instead of `None` because treating `None` as padding
157
+ battches could cause silent errors.
158
+ """
159
+
160
+
161
+ class InputFeatures(object):
162
+ """A single set of features of data."""
163
+
164
+ def __init__(self,
165
+ input_ids,
166
+ input_mask,
167
+ segment_ids,
168
+ label_id,
169
+ is_real_example=True):
170
+ self.input_ids = input_ids
171
+ self.input_mask = input_mask
172
+ self.segment_ids = segment_ids
173
+ self.label_id = label_id
174
+ self.is_real_example = is_real_example
175
+
176
+
177
+ class DataProcessor(object):
178
+ """Base class for data converters for sequence classification data sets."""
179
+
180
+ def get_train_examples(self, data_dir):
181
+ """Gets a collection of `InputExample`s for the train set."""
182
+ raise NotImplementedError()
183
+
184
+ def get_dev_examples(self, data_dir):
185
+ """Gets a collection of `InputExample`s for the dev set."""
186
+ raise NotImplementedError()
187
+
188
+ def get_test_examples(self, data_dir):
189
+ """Gets a collection of `InputExample`s for prediction."""
190
+ raise NotImplementedError()
191
+
192
+ def get_labels(self):
193
+ """Gets the list of labels for this data set."""
194
+ raise NotImplementedError()
195
+
196
+ @classmethod
197
+ def _read_tsv(cls, input_file, quotechar=None):
198
+ """Reads a tab separated value file."""
199
+ with tf.gfile.Open(input_file, "r") as f:
200
+ reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
201
+ lines = []
202
+ for line in reader:
203
+ lines.append(line)
204
+ return lines
205
+
206
+
207
+ class XnliProcessor(DataProcessor):
208
+ """Processor for the XNLI data set."""
209
+
210
+ def __init__(self):
211
+ self.language = "zh"
212
+
213
+ def get_train_examples(self, data_dir):
214
+ """See base class."""
215
+ lines = self._read_tsv(
216
+ os.path.join(data_dir, "multinli",
217
+ "multinli.train.%s.tsv" % self.language))
218
+ examples = []
219
+ for (i, line) in enumerate(lines):
220
+ if i == 0:
221
+ continue
222
+ guid = "train-%d" % (i)
223
+ text_a = tokenization.convert_to_unicode(line[0])
224
+ text_b = tokenization.convert_to_unicode(line[1])
225
+ label = tokenization.convert_to_unicode(line[2])
226
+ if label == tokenization.convert_to_unicode("contradictory"):
227
+ label = tokenization.convert_to_unicode("contradiction")
228
+ examples.append(
229
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
230
+ return examples
231
+
232
+ def get_dev_examples(self, data_dir):
233
+ """See base class."""
234
+ lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv"))
235
+ examples = []
236
+ for (i, line) in enumerate(lines):
237
+ if i == 0:
238
+ continue
239
+ guid = "dev-%d" % (i)
240
+ language = tokenization.convert_to_unicode(line[0])
241
+ if language != tokenization.convert_to_unicode(self.language):
242
+ continue
243
+ text_a = tokenization.convert_to_unicode(line[6])
244
+ text_b = tokenization.convert_to_unicode(line[7])
245
+ label = tokenization.convert_to_unicode(line[1])
246
+ examples.append(
247
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
248
+ return examples
249
+
250
+ def get_labels(self):
251
+ """See base class."""
252
+ return ["contradiction", "entailment", "neutral"]
253
+
254
+
255
+ class MnliProcessor(DataProcessor):
256
+ """Processor for the MultiNLI data set (GLUE version)."""
257
+
258
+ def get_train_examples(self, data_dir):
259
+ """See base class."""
260
+ return self._create_examples(
261
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
262
+
263
+ def get_dev_examples(self, data_dir):
264
+ """See base class."""
265
+ return self._create_examples(
266
+ self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")),
267
+ "dev_matched")
268
+
269
+ def get_test_examples(self, data_dir):
270
+ """See base class."""
271
+ return self._create_examples(
272
+ self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test")
273
+
274
+ def get_labels(self):
275
+ """See base class."""
276
+ return ["contradiction", "entailment", "neutral"]
277
+
278
+ def _create_examples(self, lines, set_type):
279
+ """Creates examples for the training and dev sets."""
280
+ examples = []
281
+ for (i, line) in enumerate(lines):
282
+ if i == 0:
283
+ continue
284
+ guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0]))
285
+ text_a = tokenization.convert_to_unicode(line[8])
286
+ text_b = tokenization.convert_to_unicode(line[9])
287
+ if set_type == "test":
288
+ label = "contradiction"
289
+ else:
290
+ label = tokenization.convert_to_unicode(line[-1])
291
+ examples.append(
292
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
293
+ return examples
294
+
295
+
296
+ class MrpcProcessor(DataProcessor):
297
+ """Processor for the MRPC data set (GLUE version)."""
298
+
299
+ def get_train_examples(self, data_dir):
300
+ """See base class."""
301
+ return self._create_examples(
302
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
303
+
304
+ def get_dev_examples(self, data_dir):
305
+ """See base class."""
306
+ return self._create_examples(
307
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
308
+
309
+ def get_test_examples(self, data_dir):
310
+ """See base class."""
311
+ return self._create_examples(
312
+ self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
313
+
314
+ def get_labels(self):
315
+ """See base class."""
316
+ return ["0", "1"]
317
+
318
+ def _create_examples(self, lines, set_type):
319
+ """Creates examples for the training and dev sets."""
320
+ examples = []
321
+ for (i, line) in enumerate(lines):
322
+ if i == 0:
323
+ continue
324
+ guid = "%s-%s" % (set_type, i)
325
+ text_a = tokenization.convert_to_unicode(line[3])
326
+ text_b = tokenization.convert_to_unicode(line[4])
327
+ if set_type == "test":
328
+ label = "0"
329
+ else:
330
+ label = tokenization.convert_to_unicode(line[0])
331
+ examples.append(
332
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
333
+ return examples
334
+
335
+
336
+ class ColaProcessor(DataProcessor):
337
+ """Processor for the CoLA data set (GLUE version)."""
338
+
339
+ def get_train_examples(self, data_dir):
340
+ """See base class."""
341
+ return self._create_examples(
342
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
343
+
344
+ def get_dev_examples(self, data_dir):
345
+ """See base class."""
346
+ return self._create_examples(
347
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
348
+
349
+ def get_test_examples(self, data_dir):
350
+ """See base class."""
351
+ return self._create_examples(
352
+ self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
353
+
354
+ def get_labels(self):
355
+ """See base class."""
356
+ return ["0", "1"]
357
+
358
+ def _create_examples(self, lines, set_type):
359
+ """Creates examples for the training and dev sets."""
360
+ examples = []
361
+ for (i, line) in enumerate(lines):
362
+ # Only the test set has a header
363
+ if set_type == "test" and i == 0:
364
+ continue
365
+ guid = "%s-%s" % (set_type, i)
366
+ if set_type == "test":
367
+ text_a = tokenization.convert_to_unicode(line[1])
368
+ label = "0"
369
+ else:
370
+ text_a = tokenization.convert_to_unicode(line[3])
371
+ label = tokenization.convert_to_unicode(line[1])
372
+ examples.append(
373
+ InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
374
+ return examples
375
+
376
+
377
+ def convert_single_example(ex_index, example, label_list, max_seq_length,
378
+ tokenizer):
379
+ """Converts a single `InputExample` into a single `InputFeatures`."""
380
+
381
+ if isinstance(example, PaddingInputExample):
382
+ return InputFeatures(
383
+ input_ids=[0] * max_seq_length,
384
+ input_mask=[0] * max_seq_length,
385
+ segment_ids=[0] * max_seq_length,
386
+ label_id=0,
387
+ is_real_example=False)
388
+
389
+ label_map = {}
390
+ for (i, label) in enumerate(label_list):
391
+ label_map[label] = i
392
+
393
+ tokens_a = tokenizer.tokenize(example.text_a)
394
+ tokens_b = None
395
+ if example.text_b:
396
+ tokens_b = tokenizer.tokenize(example.text_b)
397
+
398
+ if tokens_b:
399
+ # Modifies `tokens_a` and `tokens_b` in place so that the total
400
+ # length is less than the specified length.
401
+ # Account for [CLS], [SEP], [SEP] with "- 3"
402
+ _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
403
+ else:
404
+ # Account for [CLS] and [SEP] with "- 2"
405
+ if len(tokens_a) > max_seq_length - 2:
406
+ tokens_a = tokens_a[0:(max_seq_length - 2)]
407
+
408
+ # The convention in BERT is:
409
+ # (a) For sequence pairs:
410
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
411
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
412
+ # (b) For single sequences:
413
+ # tokens: [CLS] the dog is hairy . [SEP]
414
+ # type_ids: 0 0 0 0 0 0 0
415
+ #
416
+ # Where "type_ids" are used to indicate whether this is the first
417
+ # sequence or the second sequence. The embedding vectors for `type=0` and
418
+ # `type=1` were learned during pre-training and are added to the wordpiece
419
+ # embedding vector (and position vector). This is not *strictly* necessary
420
+ # since the [SEP] token unambiguously separates the sequences, but it makes
421
+ # it easier for the model to learn the concept of sequences.
422
+ #
423
+ # For classification tasks, the first vector (corresponding to [CLS]) is
424
+ # used as the "sentence vector". Note that this only makes sense because
425
+ # the entire model is fine-tuned.
426
+ tokens = []
427
+ segment_ids = []
428
+ tokens.append("[CLS]")
429
+ segment_ids.append(0)
430
+ for token in tokens_a:
431
+ tokens.append(token)
432
+ segment_ids.append(0)
433
+ tokens.append("[SEP]")
434
+ segment_ids.append(0)
435
+
436
+ if tokens_b:
437
+ for token in tokens_b:
438
+ tokens.append(token)
439
+ segment_ids.append(1)
440
+ tokens.append("[SEP]")
441
+ segment_ids.append(1)
442
+
443
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
444
+
445
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
446
+ # tokens are attended to.
447
+ input_mask = [1] * len(input_ids)
448
+
449
+ # Zero-pad up to the sequence length.
450
+ while len(input_ids) < max_seq_length:
451
+ input_ids.append(0)
452
+ input_mask.append(0)
453
+ segment_ids.append(0)
454
+
455
+ assert len(input_ids) == max_seq_length
456
+ assert len(input_mask) == max_seq_length
457
+ assert len(segment_ids) == max_seq_length
458
+
459
+ label_id = label_map[example.label]
460
+ if ex_index < 5:
461
+ tf.logging.info("*** Example ***")
462
+ tf.logging.info("guid: %s" % (example.guid))
463
+ tf.logging.info("tokens: %s" % " ".join(
464
+ [tokenization.printable_text(x) for x in tokens]))
465
+ tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
466
+ tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
467
+ tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
468
+ tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
469
+
470
+ feature = InputFeatures(
471
+ input_ids=input_ids,
472
+ input_mask=input_mask,
473
+ segment_ids=segment_ids,
474
+ label_id=label_id,
475
+ is_real_example=True)
476
+ return feature
477
+
478
+
479
+ def file_based_convert_examples_to_features(
480
+ examples, label_list, max_seq_length, tokenizer, output_file):
481
+ """Convert a set of `InputExample`s to a TFRecord file."""
482
+
483
+ writer = tf.python_io.TFRecordWriter(output_file)
484
+
485
+ for (ex_index, example) in enumerate(examples):
486
+ if ex_index % 10000 == 0:
487
+ tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
488
+
489
+ feature = convert_single_example(ex_index, example, label_list,
490
+ max_seq_length, tokenizer)
491
+
492
+ def create_int_feature(values):
493
+ f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
494
+ return f
495
+
496
+ features = collections.OrderedDict()
497
+ features["input_ids"] = create_int_feature(feature.input_ids)
498
+ features["input_mask"] = create_int_feature(feature.input_mask)
499
+ features["segment_ids"] = create_int_feature(feature.segment_ids)
500
+ features["label_ids"] = create_int_feature([feature.label_id])
501
+ features["is_real_example"] = create_int_feature(
502
+ [int(feature.is_real_example)])
503
+
504
+ tf_example = tf.train.Example(features=tf.train.Features(feature=features))
505
+ writer.write(tf_example.SerializeToString())
506
+ writer.close()
507
+
508
+
509
+ def file_based_input_fn_builder(input_file, seq_length, is_training,
510
+ drop_remainder):
511
+ """Creates an `input_fn` closure to be passed to TPUEstimator."""
512
+
513
+ name_to_features = {
514
+ "input_ids": tf.FixedLenFeature([seq_length], tf.int64),
515
+ "input_mask": tf.FixedLenFeature([seq_length], tf.int64),
516
+ "segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
517
+ "label_ids": tf.FixedLenFeature([], tf.int64),
518
+ "is_real_example": tf.FixedLenFeature([], tf.int64),
519
+ }
520
+
521
+ def _decode_record(record, name_to_features):
522
+ """Decodes a record to a TensorFlow example."""
523
+ example = tf.parse_single_example(record, name_to_features)
524
+
525
+ # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
526
+ # So cast all int64 to int32.
527
+ for name in list(example.keys()):
528
+ t = example[name]
529
+ if t.dtype == tf.int64:
530
+ t = tf.to_int32(t)
531
+ example[name] = t
532
+
533
+ return example
534
+
535
+ def input_fn(params):
536
+ """The actual input function."""
537
+ batch_size = params["batch_size"]
538
+
539
+ # For training, we want a lot of parallel reading and shuffling.
540
+ # For eval, we want no shuffling and parallel reading doesn't matter.
541
+ d = tf.data.TFRecordDataset(input_file)
542
+ if is_training:
543
+ d = d.repeat()
544
+ d = d.shuffle(buffer_size=100)
545
+
546
+ d = d.apply(
547
+ tf.contrib.data.map_and_batch(
548
+ lambda record: _decode_record(record, name_to_features),
549
+ batch_size=batch_size,
550
+ drop_remainder=drop_remainder))
551
+
552
+ return d
553
+
554
+ return input_fn
555
+
556
+
557
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
558
+ """Truncates a sequence pair in place to the maximum length."""
559
+
560
+ # This is a simple heuristic which will always truncate the longer sequence
561
+ # one token at a time. This makes more sense than truncating an equal percent
562
+ # of tokens from each, since if one sequence is very short then each token
563
+ # that's truncated likely contains more information than a longer sequence.
564
+ while True:
565
+ total_length = len(tokens_a) + len(tokens_b)
566
+ if total_length <= max_length:
567
+ break
568
+ if len(tokens_a) > len(tokens_b):
569
+ tokens_a.pop()
570
+ else:
571
+ tokens_b.pop()
572
+
573
+
574
+ def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
575
+ labels, num_labels, use_one_hot_embeddings):
576
+ """Creates a classification model."""
577
+ model = modeling.BertModel(
578
+ config=bert_config,
579
+ is_training=is_training,
580
+ input_ids=input_ids,
581
+ input_mask=input_mask,
582
+ token_type_ids=segment_ids,
583
+ use_one_hot_embeddings=use_one_hot_embeddings)
584
+
585
+ # In the demo, we are doing a simple classification task on the entire
586
+ # segment.
587
+ #
588
+ # If you want to use the token-level output, use model.get_sequence_output()
589
+ # instead.
590
+ output_layer = model.get_pooled_output()
591
+
592
+ hidden_size = output_layer.shape[-1].value
593
+
594
+ output_weights = tf.get_variable(
595
+ "output_weights", [num_labels, hidden_size],
596
+ initializer=tf.truncated_normal_initializer(stddev=0.02))
597
+
598
+ output_bias = tf.get_variable(
599
+ "output_bias", [num_labels], initializer=tf.zeros_initializer())
600
+
601
+ with tf.variable_scope("loss"):
602
+ if is_training:
603
+ # I.e., 0.1 dropout
604
+ output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
605
+
606
+ logits = tf.matmul(output_layer, output_weights, transpose_b=True)
607
+ logits = tf.nn.bias_add(logits, output_bias)
608
+ probabilities = tf.nn.softmax(logits, axis=-1)
609
+ log_probs = tf.nn.log_softmax(logits, axis=-1)
610
+
611
+ one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
612
+
613
+ per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
614
+ loss = tf.reduce_mean(per_example_loss)
615
+
616
+ return (loss, per_example_loss, logits, probabilities)
617
+
618
+
619
+ def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
620
+ num_train_steps, num_warmup_steps, use_tpu,
621
+ use_one_hot_embeddings):
622
+ """Returns `model_fn` closure for TPUEstimator."""
623
+
624
+ def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
625
+ """The `model_fn` for TPUEstimator."""
626
+
627
+ tf.logging.info("*** Features ***")
628
+ for name in sorted(features.keys()):
629
+ tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
630
+
631
+ input_ids = features["input_ids"]
632
+ input_mask = features["input_mask"]
633
+ segment_ids = features["segment_ids"]
634
+ label_ids = features["label_ids"]
635
+ is_real_example = None
636
+ if "is_real_example" in features:
637
+ is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
638
+ else:
639
+ is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
640
+
641
+ is_training = (mode == tf.estimator.ModeKeys.TRAIN)
642
+
643
+ (total_loss, per_example_loss, logits, probabilities) = create_model(
644
+ bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
645
+ num_labels, use_one_hot_embeddings)
646
+
647
+ tvars = tf.trainable_variables()
648
+ initialized_variable_names = {}
649
+ scaffold_fn = None
650
+ if init_checkpoint:
651
+ (assignment_map, initialized_variable_names
652
+ ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
653
+ if use_tpu:
654
+
655
+ def tpu_scaffold():
656
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
657
+ return tf.train.Scaffold()
658
+
659
+ scaffold_fn = tpu_scaffold
660
+ else:
661
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
662
+
663
+ tf.logging.info("**** Trainable Variables ****")
664
+ for var in tvars:
665
+ init_string = ""
666
+ if var.name in initialized_variable_names:
667
+ init_string = ", *INIT_FROM_CKPT*"
668
+ tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
669
+ init_string)
670
+
671
+ output_spec = None
672
+ if mode == tf.estimator.ModeKeys.TRAIN:
673
+
674
+ train_op = optimization.create_optimizer(
675
+ total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
676
+
677
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
678
+ mode=mode,
679
+ loss=total_loss,
680
+ train_op=train_op,
681
+ scaffold_fn=scaffold_fn)
682
+ elif mode == tf.estimator.ModeKeys.EVAL:
683
+
684
+ def metric_fn(per_example_loss, label_ids, logits, is_real_example):
685
+ predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
686
+ accuracy = tf.metrics.accuracy(
687
+ labels=label_ids, predictions=predictions, weights=is_real_example)
688
+ loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
689
+ return {
690
+ "eval_accuracy": accuracy,
691
+ "eval_loss": loss,
692
+ }
693
+
694
+ eval_metrics = (metric_fn,
695
+ [per_example_loss, label_ids, logits, is_real_example])
696
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
697
+ mode=mode,
698
+ loss=total_loss,
699
+ eval_metrics=eval_metrics,
700
+ scaffold_fn=scaffold_fn)
701
+ else:
702
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
703
+ mode=mode,
704
+ predictions={"probabilities": probabilities},
705
+ scaffold_fn=scaffold_fn)
706
+ return output_spec
707
+
708
+ return model_fn
709
+
710
+
711
+ # This function is not used by this file but is still used by the Colab and
712
+ # people who depend on it.
713
+ def input_fn_builder(features, seq_length, is_training, drop_remainder):
714
+ """Creates an `input_fn` closure to be passed to TPUEstimator."""
715
+
716
+ all_input_ids = []
717
+ all_input_mask = []
718
+ all_segment_ids = []
719
+ all_label_ids = []
720
+
721
+ for feature in features:
722
+ all_input_ids.append(feature.input_ids)
723
+ all_input_mask.append(feature.input_mask)
724
+ all_segment_ids.append(feature.segment_ids)
725
+ all_label_ids.append(feature.label_id)
726
+
727
+ def input_fn(params):
728
+ """The actual input function."""
729
+ batch_size = params["batch_size"]
730
+
731
+ num_examples = len(features)
732
+
733
+ # This is for demo purposes and does NOT scale to large data sets. We do
734
+ # not use Dataset.from_generator() because that uses tf.py_func which is
735
+ # not TPU compatible. The right way to load data is with TFRecordReader.
736
+ d = tf.data.Dataset.from_tensor_slices({
737
+ "input_ids":
738
+ tf.constant(
739
+ all_input_ids, shape=[num_examples, seq_length],
740
+ dtype=tf.int32),
741
+ "input_mask":
742
+ tf.constant(
743
+ all_input_mask,
744
+ shape=[num_examples, seq_length],
745
+ dtype=tf.int32),
746
+ "segment_ids":
747
+ tf.constant(
748
+ all_segment_ids,
749
+ shape=[num_examples, seq_length],
750
+ dtype=tf.int32),
751
+ "label_ids":
752
+ tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
753
+ })
754
+
755
+ if is_training:
756
+ d = d.repeat()
757
+ d = d.shuffle(buffer_size=100)
758
+
759
+ d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
760
+ return d
761
+
762
+ return input_fn
763
+
764
+
765
+ # This function is not used by this file but is still used by the Colab and
766
+ # people who depend on it.
767
+ def convert_examples_to_features(examples, label_list, max_seq_length,
768
+ tokenizer):
769
+ """Convert a set of `InputExample`s to a list of `InputFeatures`."""
770
+
771
+ features = []
772
+ for (ex_index, example) in enumerate(examples):
773
+ if ex_index % 10000 == 0:
774
+ tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
775
+
776
+ feature = convert_single_example(ex_index, example, label_list,
777
+ max_seq_length, tokenizer)
778
+
779
+ features.append(feature)
780
+ return features
781
+
782
+
783
+ def main(_):
784
+ tf.logging.set_verbosity(tf.logging.INFO)
785
+
786
+ processors = {
787
+ "cola": ColaProcessor,
788
+ "mnli": MnliProcessor,
789
+ "mrpc": MrpcProcessor,
790
+ "xnli": XnliProcessor,
791
+ }
792
+
793
+ tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
794
+ FLAGS.init_checkpoint)
795
+
796
+ if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
797
+ raise ValueError(
798
+ "At least one of `do_train`, `do_eval` or `do_predict' must be True.")
799
+
800
+ bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
801
+
802
+ if FLAGS.max_seq_length > bert_config.max_position_embeddings:
803
+ raise ValueError(
804
+ "Cannot use sequence length %d because the BERT model "
805
+ "was only trained up to sequence length %d" %
806
+ (FLAGS.max_seq_length, bert_config.max_position_embeddings))
807
+
808
+ tf.gfile.MakeDirs(FLAGS.output_dir)
809
+
810
+ task_name = FLAGS.task_name.lower()
811
+
812
+ if task_name not in processors:
813
+ raise ValueError("Task not found: %s" % (task_name))
814
+
815
+ processor = processors[task_name]()
816
+
817
+ label_list = processor.get_labels()
818
+
819
+ tokenizer = tokenization.FullTokenizer(
820
+ vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
821
+
822
+ tpu_cluster_resolver = None
823
+ if FLAGS.use_tpu and FLAGS.tpu_name:
824
+ tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
825
+ FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
826
+
827
+ is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
828
+ run_config = tf.contrib.tpu.RunConfig(
829
+ cluster=tpu_cluster_resolver,
830
+ master=FLAGS.master,
831
+ model_dir=FLAGS.output_dir,
832
+ save_checkpoints_steps=FLAGS.save_checkpoints_steps,
833
+ tpu_config=tf.contrib.tpu.TPUConfig(
834
+ iterations_per_loop=FLAGS.iterations_per_loop,
835
+ num_shards=FLAGS.num_tpu_cores,
836
+ per_host_input_for_training=is_per_host))
837
+
838
+ train_examples = None
839
+ num_train_steps = None
840
+ num_warmup_steps = None
841
+ if FLAGS.do_train:
842
+ train_examples = processor.get_train_examples(FLAGS.data_dir)
843
+ num_train_steps = int(
844
+ len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
845
+ num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
846
+
847
+ model_fn = model_fn_builder(
848
+ bert_config=bert_config,
849
+ num_labels=len(label_list),
850
+ init_checkpoint=FLAGS.init_checkpoint,
851
+ learning_rate=FLAGS.learning_rate,
852
+ num_train_steps=num_train_steps,
853
+ num_warmup_steps=num_warmup_steps,
854
+ use_tpu=FLAGS.use_tpu,
855
+ use_one_hot_embeddings=FLAGS.use_tpu)
856
+
857
+ # If TPU is not available, this will fall back to normal Estimator on CPU
858
+ # or GPU.
859
+ estimator = tf.contrib.tpu.TPUEstimator(
860
+ use_tpu=FLAGS.use_tpu,
861
+ model_fn=model_fn,
862
+ config=run_config,
863
+ train_batch_size=FLAGS.train_batch_size,
864
+ eval_batch_size=FLAGS.eval_batch_size,
865
+ predict_batch_size=FLAGS.predict_batch_size)
866
+
867
+ if FLAGS.do_train:
868
+ train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
869
+ file_based_convert_examples_to_features(
870
+ train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
871
+ tf.logging.info("***** Running training *****")
872
+ tf.logging.info(" Num examples = %d", len(train_examples))
873
+ tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
874
+ tf.logging.info(" Num steps = %d", num_train_steps)
875
+ train_input_fn = file_based_input_fn_builder(
876
+ input_file=train_file,
877
+ seq_length=FLAGS.max_seq_length,
878
+ is_training=True,
879
+ drop_remainder=True)
880
+ estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
881
+
882
+ if FLAGS.do_eval:
883
+ eval_examples = processor.get_dev_examples(FLAGS.data_dir)
884
+ num_actual_eval_examples = len(eval_examples)
885
+ if FLAGS.use_tpu:
886
+ # TPU requires a fixed batch size for all batches, therefore the number
887
+ # of examples must be a multiple of the batch size, or else examples
888
+ # will get dropped. So we pad with fake examples which are ignored
889
+ # later on. These do NOT count towards the metric (all tf.metrics
890
+ # support a per-instance weight, and these get a weight of 0.0).
891
+ while len(eval_examples) % FLAGS.eval_batch_size != 0:
892
+ eval_examples.append(PaddingInputExample())
893
+
894
+ eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
895
+ file_based_convert_examples_to_features(
896
+ eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
897
+
898
+ tf.logging.info("***** Running evaluation *****")
899
+ tf.logging.info(" Num examples = %d (%d actual, %d padding)",
900
+ len(eval_examples), num_actual_eval_examples,
901
+ len(eval_examples) - num_actual_eval_examples)
902
+ tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
903
+
904
+ # This tells the estimator to run through the entire set.
905
+ eval_steps = None
906
+ # However, if running eval on the TPU, you will need to specify the
907
+ # number of steps.
908
+ if FLAGS.use_tpu:
909
+ assert len(eval_examples) % FLAGS.eval_batch_size == 0
910
+ eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
911
+
912
+ eval_drop_remainder = True if FLAGS.use_tpu else False
913
+ eval_input_fn = file_based_input_fn_builder(
914
+ input_file=eval_file,
915
+ seq_length=FLAGS.max_seq_length,
916
+ is_training=False,
917
+ drop_remainder=eval_drop_remainder)
918
+
919
+ result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
920
+
921
+ output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
922
+ with tf.gfile.GFile(output_eval_file, "w") as writer:
923
+ tf.logging.info("***** Eval results *****")
924
+ for key in sorted(result.keys()):
925
+ tf.logging.info(" %s = %s", key, str(result[key]))
926
+ writer.write("%s = %s\n" % (key, str(result[key])))
927
+
928
+ if FLAGS.do_predict:
929
+ predict_examples = processor.get_test_examples(FLAGS.data_dir)
930
+ num_actual_predict_examples = len(predict_examples)
931
+ if FLAGS.use_tpu:
932
+ # TPU requires a fixed batch size for all batches, therefore the number
933
+ # of examples must be a multiple of the batch size, or else examples
934
+ # will get dropped. So we pad with fake examples which are ignored
935
+ # later on.
936
+ while len(predict_examples) % FLAGS.predict_batch_size != 0:
937
+ predict_examples.append(PaddingInputExample())
938
+
939
+ predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
940
+ file_based_convert_examples_to_features(predict_examples, label_list,
941
+ FLAGS.max_seq_length, tokenizer,
942
+ predict_file)
943
+
944
+ tf.logging.info("***** Running prediction*****")
945
+ tf.logging.info(" Num examples = %d (%d actual, %d padding)",
946
+ len(predict_examples), num_actual_predict_examples,
947
+ len(predict_examples) - num_actual_predict_examples)
948
+ tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
949
+
950
+ predict_drop_remainder = True if FLAGS.use_tpu else False
951
+ predict_input_fn = file_based_input_fn_builder(
952
+ input_file=predict_file,
953
+ seq_length=FLAGS.max_seq_length,
954
+ is_training=False,
955
+ drop_remainder=predict_drop_remainder)
956
+
957
+ result = estimator.predict(input_fn=predict_input_fn)
958
+
959
+ output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
960
+ with tf.gfile.GFile(output_predict_file, "w") as writer:
961
+ num_written_lines = 0
962
+ tf.logging.info("***** Predict results *****")
963
+ for (i, prediction) in enumerate(result):
964
+ probabilities = prediction["probabilities"]
965
+ if i >= num_actual_predict_examples:
966
+ break
967
+ output_line = "\t".join(
968
+ str(class_probability)
969
+ for class_probability in probabilities) + "\n"
970
+ writer.write(output_line)
971
+ num_written_lines += 1
972
+ assert num_written_lines == num_actual_predict_examples
973
+
974
+
975
+ if __name__ == "__main__":
976
+ flags.mark_flag_as_required("data_dir")
977
+ flags.mark_flag_as_required("task_name")
978
+ flags.mark_flag_as_required("vocab_file")
979
+ flags.mark_flag_as_required("bert_config_file")
980
+ flags.mark_flag_as_required("output_dir")
981
+ tf.app.run()
bert-master/bert-master/run_classifier_with_tfhub.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BERT finetuning runner with TF-Hub."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import os
22
+ import optimization
23
+ import run_classifier
24
+ import tokenization
25
+ import tensorflow as tf
26
+ import tensorflow_hub as hub
27
+
28
+ flags = tf.flags
29
+
30
+ FLAGS = flags.FLAGS
31
+
32
+ flags.DEFINE_string(
33
+ "bert_hub_module_handle", None,
34
+ "Handle for the BERT TF-Hub module.")
35
+
36
+
37
+ def create_model(is_training, input_ids, input_mask, segment_ids, labels,
38
+ num_labels, bert_hub_module_handle):
39
+ """Creates a classification model."""
40
+ tags = set()
41
+ if is_training:
42
+ tags.add("train")
43
+ bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True)
44
+ bert_inputs = dict(
45
+ input_ids=input_ids,
46
+ input_mask=input_mask,
47
+ segment_ids=segment_ids)
48
+ bert_outputs = bert_module(
49
+ inputs=bert_inputs,
50
+ signature="tokens",
51
+ as_dict=True)
52
+
53
+ # In the demo, we are doing a simple classification task on the entire
54
+ # segment.
55
+ #
56
+ # If you want to use the token-level output, use
57
+ # bert_outputs["sequence_output"] instead.
58
+ output_layer = bert_outputs["pooled_output"]
59
+
60
+ hidden_size = output_layer.shape[-1].value
61
+
62
+ output_weights = tf.get_variable(
63
+ "output_weights", [num_labels, hidden_size],
64
+ initializer=tf.truncated_normal_initializer(stddev=0.02))
65
+
66
+ output_bias = tf.get_variable(
67
+ "output_bias", [num_labels], initializer=tf.zeros_initializer())
68
+
69
+ with tf.variable_scope("loss"):
70
+ if is_training:
71
+ # I.e., 0.1 dropout
72
+ output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
73
+
74
+ logits = tf.matmul(output_layer, output_weights, transpose_b=True)
75
+ logits = tf.nn.bias_add(logits, output_bias)
76
+ probabilities = tf.nn.softmax(logits, axis=-1)
77
+ log_probs = tf.nn.log_softmax(logits, axis=-1)
78
+
79
+ one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
80
+
81
+ per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
82
+ loss = tf.reduce_mean(per_example_loss)
83
+
84
+ return (loss, per_example_loss, logits, probabilities)
85
+
86
+
87
+ def model_fn_builder(num_labels, learning_rate, num_train_steps,
88
+ num_warmup_steps, use_tpu, bert_hub_module_handle):
89
+ """Returns `model_fn` closure for TPUEstimator."""
90
+
91
+ def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
92
+ """The `model_fn` for TPUEstimator."""
93
+
94
+ tf.logging.info("*** Features ***")
95
+ for name in sorted(features.keys()):
96
+ tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
97
+
98
+ input_ids = features["input_ids"]
99
+ input_mask = features["input_mask"]
100
+ segment_ids = features["segment_ids"]
101
+ label_ids = features["label_ids"]
102
+
103
+ is_training = (mode == tf.estimator.ModeKeys.TRAIN)
104
+
105
+ (total_loss, per_example_loss, logits, probabilities) = create_model(
106
+ is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,
107
+ bert_hub_module_handle)
108
+
109
+ output_spec = None
110
+ if mode == tf.estimator.ModeKeys.TRAIN:
111
+ train_op = optimization.create_optimizer(
112
+ total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
113
+
114
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
115
+ mode=mode,
116
+ loss=total_loss,
117
+ train_op=train_op)
118
+ elif mode == tf.estimator.ModeKeys.EVAL:
119
+
120
+ def metric_fn(per_example_loss, label_ids, logits):
121
+ predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
122
+ accuracy = tf.metrics.accuracy(label_ids, predictions)
123
+ loss = tf.metrics.mean(per_example_loss)
124
+ return {
125
+ "eval_accuracy": accuracy,
126
+ "eval_loss": loss,
127
+ }
128
+
129
+ eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
130
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
131
+ mode=mode,
132
+ loss=total_loss,
133
+ eval_metrics=eval_metrics)
134
+ elif mode == tf.estimator.ModeKeys.PREDICT:
135
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
136
+ mode=mode, predictions={"probabilities": probabilities})
137
+ else:
138
+ raise ValueError(
139
+ "Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode))
140
+
141
+ return output_spec
142
+
143
+ return model_fn
144
+
145
+
146
+ def create_tokenizer_from_hub_module(bert_hub_module_handle):
147
+ """Get the vocab file and casing info from the Hub module."""
148
+ with tf.Graph().as_default():
149
+ bert_module = hub.Module(bert_hub_module_handle)
150
+ tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
151
+ with tf.Session() as sess:
152
+ vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"],
153
+ tokenization_info["do_lower_case"]])
154
+ return tokenization.FullTokenizer(
155
+ vocab_file=vocab_file, do_lower_case=do_lower_case)
156
+
157
+
158
+ def main(_):
159
+ tf.logging.set_verbosity(tf.logging.INFO)
160
+
161
+ processors = {
162
+ "cola": run_classifier.ColaProcessor,
163
+ "mnli": run_classifier.MnliProcessor,
164
+ "mrpc": run_classifier.MrpcProcessor,
165
+ }
166
+
167
+ if not FLAGS.do_train and not FLAGS.do_eval:
168
+ raise ValueError("At least one of `do_train` or `do_eval` must be True.")
169
+
170
+ tf.gfile.MakeDirs(FLAGS.output_dir)
171
+
172
+ task_name = FLAGS.task_name.lower()
173
+
174
+ if task_name not in processors:
175
+ raise ValueError("Task not found: %s" % (task_name))
176
+
177
+ processor = processors[task_name]()
178
+
179
+ label_list = processor.get_labels()
180
+
181
+ tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle)
182
+
183
+ tpu_cluster_resolver = None
184
+ if FLAGS.use_tpu and FLAGS.tpu_name:
185
+ tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
186
+ FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
187
+
188
+ is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
189
+ run_config = tf.contrib.tpu.RunConfig(
190
+ cluster=tpu_cluster_resolver,
191
+ master=FLAGS.master,
192
+ model_dir=FLAGS.output_dir,
193
+ save_checkpoints_steps=FLAGS.save_checkpoints_steps,
194
+ tpu_config=tf.contrib.tpu.TPUConfig(
195
+ iterations_per_loop=FLAGS.iterations_per_loop,
196
+ num_shards=FLAGS.num_tpu_cores,
197
+ per_host_input_for_training=is_per_host))
198
+
199
+ train_examples = None
200
+ num_train_steps = None
201
+ num_warmup_steps = None
202
+ if FLAGS.do_train:
203
+ train_examples = processor.get_train_examples(FLAGS.data_dir)
204
+ num_train_steps = int(
205
+ len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
206
+ num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
207
+
208
+ model_fn = model_fn_builder(
209
+ num_labels=len(label_list),
210
+ learning_rate=FLAGS.learning_rate,
211
+ num_train_steps=num_train_steps,
212
+ num_warmup_steps=num_warmup_steps,
213
+ use_tpu=FLAGS.use_tpu,
214
+ bert_hub_module_handle=FLAGS.bert_hub_module_handle)
215
+
216
+ # If TPU is not available, this will fall back to normal Estimator on CPU
217
+ # or GPU.
218
+ estimator = tf.contrib.tpu.TPUEstimator(
219
+ use_tpu=FLAGS.use_tpu,
220
+ model_fn=model_fn,
221
+ config=run_config,
222
+ train_batch_size=FLAGS.train_batch_size,
223
+ eval_batch_size=FLAGS.eval_batch_size,
224
+ predict_batch_size=FLAGS.predict_batch_size)
225
+
226
+ if FLAGS.do_train:
227
+ train_features = run_classifier.convert_examples_to_features(
228
+ train_examples, label_list, FLAGS.max_seq_length, tokenizer)
229
+ tf.logging.info("***** Running training *****")
230
+ tf.logging.info(" Num examples = %d", len(train_examples))
231
+ tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
232
+ tf.logging.info(" Num steps = %d", num_train_steps)
233
+ train_input_fn = run_classifier.input_fn_builder(
234
+ features=train_features,
235
+ seq_length=FLAGS.max_seq_length,
236
+ is_training=True,
237
+ drop_remainder=True)
238
+ estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
239
+
240
+ if FLAGS.do_eval:
241
+ eval_examples = processor.get_dev_examples(FLAGS.data_dir)
242
+ eval_features = run_classifier.convert_examples_to_features(
243
+ eval_examples, label_list, FLAGS.max_seq_length, tokenizer)
244
+
245
+ tf.logging.info("***** Running evaluation *****")
246
+ tf.logging.info(" Num examples = %d", len(eval_examples))
247
+ tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
248
+
249
+ # This tells the estimator to run through the entire set.
250
+ eval_steps = None
251
+ # However, if running eval on the TPU, you will need to specify the
252
+ # number of steps.
253
+ if FLAGS.use_tpu:
254
+ # Eval will be slightly WRONG on the TPU because it will truncate
255
+ # the last batch.
256
+ eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
257
+
258
+ eval_drop_remainder = True if FLAGS.use_tpu else False
259
+ eval_input_fn = run_classifier.input_fn_builder(
260
+ features=eval_features,
261
+ seq_length=FLAGS.max_seq_length,
262
+ is_training=False,
263
+ drop_remainder=eval_drop_remainder)
264
+
265
+ result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
266
+
267
+ output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
268
+ with tf.gfile.GFile(output_eval_file, "w") as writer:
269
+ tf.logging.info("***** Eval results *****")
270
+ for key in sorted(result.keys()):
271
+ tf.logging.info(" %s = %s", key, str(result[key]))
272
+ writer.write("%s = %s\n" % (key, str(result[key])))
273
+
274
+ if FLAGS.do_predict:
275
+ predict_examples = processor.get_test_examples(FLAGS.data_dir)
276
+ if FLAGS.use_tpu:
277
+ # Discard batch remainder if running on TPU
278
+ n = len(predict_examples)
279
+ predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)]
280
+
281
+ predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
282
+ run_classifier.file_based_convert_examples_to_features(
283
+ predict_examples, label_list, FLAGS.max_seq_length, tokenizer,
284
+ predict_file)
285
+
286
+ tf.logging.info("***** Running prediction*****")
287
+ tf.logging.info(" Num examples = %d", len(predict_examples))
288
+ tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
289
+
290
+ predict_input_fn = run_classifier.file_based_input_fn_builder(
291
+ input_file=predict_file,
292
+ seq_length=FLAGS.max_seq_length,
293
+ is_training=False,
294
+ drop_remainder=FLAGS.use_tpu)
295
+
296
+ result = estimator.predict(input_fn=predict_input_fn)
297
+
298
+ output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
299
+ with tf.gfile.GFile(output_predict_file, "w") as writer:
300
+ tf.logging.info("***** Predict results *****")
301
+ for prediction in result:
302
+ probabilities = prediction["probabilities"]
303
+ output_line = "\t".join(
304
+ str(class_probability)
305
+ for class_probability in probabilities) + "\n"
306
+ writer.write(output_line)
307
+
308
+
309
+ if __name__ == "__main__":
310
+ flags.mark_flag_as_required("data_dir")
311
+ flags.mark_flag_as_required("task_name")
312
+ flags.mark_flag_as_required("bert_hub_module_handle")
313
+ flags.mark_flag_as_required("output_dir")
314
+ tf.app.run()
bert-master/bert-master/run_pretraining.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Run masked LM/next sentence masked_lm pre-training for BERT."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import os
22
+ import modeling
23
+ import optimization
24
+ import tensorflow as tf
25
+
26
+ flags = tf.flags
27
+
28
+ FLAGS = flags.FLAGS
29
+
30
+ ## Required parameters
31
+ flags.DEFINE_string(
32
+ "bert_config_file", None,
33
+ "The config json file corresponding to the pre-trained BERT model. "
34
+ "This specifies the model architecture.")
35
+
36
+ flags.DEFINE_string(
37
+ "input_file", None,
38
+ "Input TF example files (can be a glob or comma separated).")
39
+
40
+ flags.DEFINE_string(
41
+ "output_dir", None,
42
+ "The output directory where the model checkpoints will be written.")
43
+
44
+ ## Other parameters
45
+ flags.DEFINE_string(
46
+ "init_checkpoint", None,
47
+ "Initial checkpoint (usually from a pre-trained BERT model).")
48
+
49
+ flags.DEFINE_integer(
50
+ "max_seq_length", 128,
51
+ "The maximum total input sequence length after WordPiece tokenization. "
52
+ "Sequences longer than this will be truncated, and sequences shorter "
53
+ "than this will be padded. Must match data generation.")
54
+
55
+ flags.DEFINE_integer(
56
+ "max_predictions_per_seq", 20,
57
+ "Maximum number of masked LM predictions per sequence. "
58
+ "Must match data generation.")
59
+
60
+ flags.DEFINE_bool("do_train", False, "Whether to run training.")
61
+
62
+ flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
63
+
64
+ flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
65
+
66
+ flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
67
+
68
+ flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
69
+
70
+ flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.")
71
+
72
+ flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.")
73
+
74
+ flags.DEFINE_integer("save_checkpoints_steps", 1000,
75
+ "How often to save the model checkpoint.")
76
+
77
+ flags.DEFINE_integer("iterations_per_loop", 1000,
78
+ "How many steps to make in each estimator call.")
79
+
80
+ flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
81
+
82
+ flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
83
+
84
+ tf.flags.DEFINE_string(
85
+ "tpu_name", None,
86
+ "The Cloud TPU to use for training. This should be either the name "
87
+ "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
88
+ "url.")
89
+
90
+ tf.flags.DEFINE_string(
91
+ "tpu_zone", None,
92
+ "[Optional] GCE zone where the Cloud TPU is located in. If not "
93
+ "specified, we will attempt to automatically detect the GCE project from "
94
+ "metadata.")
95
+
96
+ tf.flags.DEFINE_string(
97
+ "gcp_project", None,
98
+ "[Optional] Project name for the Cloud TPU-enabled project. If not "
99
+ "specified, we will attempt to automatically detect the GCE project from "
100
+ "metadata.")
101
+
102
+ tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
103
+
104
+ flags.DEFINE_integer(
105
+ "num_tpu_cores", 8,
106
+ "Only used if `use_tpu` is True. Total number of TPU cores to use.")
107
+
108
+
109
+ def model_fn_builder(bert_config, init_checkpoint, learning_rate,
110
+ num_train_steps, num_warmup_steps, use_tpu,
111
+ use_one_hot_embeddings):
112
+ """Returns `model_fn` closure for TPUEstimator."""
113
+
114
+ def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
115
+ """The `model_fn` for TPUEstimator."""
116
+
117
+ tf.logging.info("*** Features ***")
118
+ for name in sorted(features.keys()):
119
+ tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
120
+
121
+ input_ids = features["input_ids"]
122
+ input_mask = features["input_mask"]
123
+ segment_ids = features["segment_ids"]
124
+ masked_lm_positions = features["masked_lm_positions"]
125
+ masked_lm_ids = features["masked_lm_ids"]
126
+ masked_lm_weights = features["masked_lm_weights"]
127
+ next_sentence_labels = features["next_sentence_labels"]
128
+
129
+ is_training = (mode == tf.estimator.ModeKeys.TRAIN)
130
+
131
+ model = modeling.BertModel(
132
+ config=bert_config,
133
+ is_training=is_training,
134
+ input_ids=input_ids,
135
+ input_mask=input_mask,
136
+ token_type_ids=segment_ids,
137
+ use_one_hot_embeddings=use_one_hot_embeddings)
138
+
139
+ (masked_lm_loss,
140
+ masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
141
+ bert_config, model.get_sequence_output(), model.get_embedding_table(),
142
+ masked_lm_positions, masked_lm_ids, masked_lm_weights)
143
+
144
+ (next_sentence_loss, next_sentence_example_loss,
145
+ next_sentence_log_probs) = get_next_sentence_output(
146
+ bert_config, model.get_pooled_output(), next_sentence_labels)
147
+
148
+ total_loss = masked_lm_loss + next_sentence_loss
149
+
150
+ tvars = tf.trainable_variables()
151
+
152
+ initialized_variable_names = {}
153
+ scaffold_fn = None
154
+ if init_checkpoint:
155
+ (assignment_map, initialized_variable_names
156
+ ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
157
+ if use_tpu:
158
+
159
+ def tpu_scaffold():
160
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
161
+ return tf.train.Scaffold()
162
+
163
+ scaffold_fn = tpu_scaffold
164
+ else:
165
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
166
+
167
+ tf.logging.info("**** Trainable Variables ****")
168
+ for var in tvars:
169
+ init_string = ""
170
+ if var.name in initialized_variable_names:
171
+ init_string = ", *INIT_FROM_CKPT*"
172
+ tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
173
+ init_string)
174
+
175
+ output_spec = None
176
+ if mode == tf.estimator.ModeKeys.TRAIN:
177
+ train_op = optimization.create_optimizer(
178
+ total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
179
+
180
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
181
+ mode=mode,
182
+ loss=total_loss,
183
+ train_op=train_op,
184
+ scaffold_fn=scaffold_fn)
185
+ elif mode == tf.estimator.ModeKeys.EVAL:
186
+
187
+ def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
188
+ masked_lm_weights, next_sentence_example_loss,
189
+ next_sentence_log_probs, next_sentence_labels):
190
+ """Computes the loss and accuracy of the model."""
191
+ masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
192
+ [-1, masked_lm_log_probs.shape[-1]])
193
+ masked_lm_predictions = tf.argmax(
194
+ masked_lm_log_probs, axis=-1, output_type=tf.int32)
195
+ masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
196
+ masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
197
+ masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
198
+ masked_lm_accuracy = tf.metrics.accuracy(
199
+ labels=masked_lm_ids,
200
+ predictions=masked_lm_predictions,
201
+ weights=masked_lm_weights)
202
+ masked_lm_mean_loss = tf.metrics.mean(
203
+ values=masked_lm_example_loss, weights=masked_lm_weights)
204
+
205
+ next_sentence_log_probs = tf.reshape(
206
+ next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
207
+ next_sentence_predictions = tf.argmax(
208
+ next_sentence_log_probs, axis=-1, output_type=tf.int32)
209
+ next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
210
+ next_sentence_accuracy = tf.metrics.accuracy(
211
+ labels=next_sentence_labels, predictions=next_sentence_predictions)
212
+ next_sentence_mean_loss = tf.metrics.mean(
213
+ values=next_sentence_example_loss)
214
+
215
+ return {
216
+ "masked_lm_accuracy": masked_lm_accuracy,
217
+ "masked_lm_loss": masked_lm_mean_loss,
218
+ "next_sentence_accuracy": next_sentence_accuracy,
219
+ "next_sentence_loss": next_sentence_mean_loss,
220
+ }
221
+
222
+ eval_metrics = (metric_fn, [
223
+ masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
224
+ masked_lm_weights, next_sentence_example_loss,
225
+ next_sentence_log_probs, next_sentence_labels
226
+ ])
227
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
228
+ mode=mode,
229
+ loss=total_loss,
230
+ eval_metrics=eval_metrics,
231
+ scaffold_fn=scaffold_fn)
232
+ else:
233
+ raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
234
+
235
+ return output_spec
236
+
237
+ return model_fn
238
+
239
+
240
+ def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
241
+ label_ids, label_weights):
242
+ """Get loss and log probs for the masked LM."""
243
+ input_tensor = gather_indexes(input_tensor, positions)
244
+
245
+ with tf.variable_scope("cls/predictions"):
246
+ # We apply one more non-linear transformation before the output layer.
247
+ # This matrix is not used after pre-training.
248
+ with tf.variable_scope("transform"):
249
+ input_tensor = tf.layers.dense(
250
+ input_tensor,
251
+ units=bert_config.hidden_size,
252
+ activation=modeling.get_activation(bert_config.hidden_act),
253
+ kernel_initializer=modeling.create_initializer(
254
+ bert_config.initializer_range))
255
+ input_tensor = modeling.layer_norm(input_tensor)
256
+
257
+ # The output weights are the same as the input embeddings, but there is
258
+ # an output-only bias for each token.
259
+ output_bias = tf.get_variable(
260
+ "output_bias",
261
+ shape=[bert_config.vocab_size],
262
+ initializer=tf.zeros_initializer())
263
+ logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
264
+ logits = tf.nn.bias_add(logits, output_bias)
265
+ log_probs = tf.nn.log_softmax(logits, axis=-1)
266
+
267
+ label_ids = tf.reshape(label_ids, [-1])
268
+ label_weights = tf.reshape(label_weights, [-1])
269
+
270
+ one_hot_labels = tf.one_hot(
271
+ label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
272
+
273
+ # The `positions` tensor might be zero-padded (if the sequence is too
274
+ # short to have the maximum number of predictions). The `label_weights`
275
+ # tensor has a value of 1.0 for every real prediction and 0.0 for the
276
+ # padding predictions.
277
+ per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
278
+ numerator = tf.reduce_sum(label_weights * per_example_loss)
279
+ denominator = tf.reduce_sum(label_weights) + 1e-5
280
+ loss = numerator / denominator
281
+
282
+ return (loss, per_example_loss, log_probs)
283
+
284
+
285
+ def get_next_sentence_output(bert_config, input_tensor, labels):
286
+ """Get loss and log probs for the next sentence prediction."""
287
+
288
+ # Simple binary classification. Note that 0 is "next sentence" and 1 is
289
+ # "random sentence". This weight matrix is not used after pre-training.
290
+ with tf.variable_scope("cls/seq_relationship"):
291
+ output_weights = tf.get_variable(
292
+ "output_weights",
293
+ shape=[2, bert_config.hidden_size],
294
+ initializer=modeling.create_initializer(bert_config.initializer_range))
295
+ output_bias = tf.get_variable(
296
+ "output_bias", shape=[2], initializer=tf.zeros_initializer())
297
+
298
+ logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
299
+ logits = tf.nn.bias_add(logits, output_bias)
300
+ log_probs = tf.nn.log_softmax(logits, axis=-1)
301
+ labels = tf.reshape(labels, [-1])
302
+ one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
303
+ per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
304
+ loss = tf.reduce_mean(per_example_loss)
305
+ return (loss, per_example_loss, log_probs)
306
+
307
+
308
+ def gather_indexes(sequence_tensor, positions):
309
+ """Gathers the vectors at the specific positions over a minibatch."""
310
+ sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
311
+ batch_size = sequence_shape[0]
312
+ seq_length = sequence_shape[1]
313
+ width = sequence_shape[2]
314
+
315
+ flat_offsets = tf.reshape(
316
+ tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
317
+ flat_positions = tf.reshape(positions + flat_offsets, [-1])
318
+ flat_sequence_tensor = tf.reshape(sequence_tensor,
319
+ [batch_size * seq_length, width])
320
+ output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
321
+ return output_tensor
322
+
323
+
324
+ def input_fn_builder(input_files,
325
+ max_seq_length,
326
+ max_predictions_per_seq,
327
+ is_training,
328
+ num_cpu_threads=4):
329
+ """Creates an `input_fn` closure to be passed to TPUEstimator."""
330
+
331
+ def input_fn(params):
332
+ """The actual input function."""
333
+ batch_size = params["batch_size"]
334
+
335
+ name_to_features = {
336
+ "input_ids":
337
+ tf.FixedLenFeature([max_seq_length], tf.int64),
338
+ "input_mask":
339
+ tf.FixedLenFeature([max_seq_length], tf.int64),
340
+ "segment_ids":
341
+ tf.FixedLenFeature([max_seq_length], tf.int64),
342
+ "masked_lm_positions":
343
+ tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
344
+ "masked_lm_ids":
345
+ tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
346
+ "masked_lm_weights":
347
+ tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
348
+ "next_sentence_labels":
349
+ tf.FixedLenFeature([1], tf.int64),
350
+ }
351
+
352
+ # For training, we want a lot of parallel reading and shuffling.
353
+ # For eval, we want no shuffling and parallel reading doesn't matter.
354
+ if is_training:
355
+ d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
356
+ d = d.repeat()
357
+ d = d.shuffle(buffer_size=len(input_files))
358
+
359
+ # `cycle_length` is the number of parallel files that get read.
360
+ cycle_length = min(num_cpu_threads, len(input_files))
361
+
362
+ # `sloppy` mode means that the interleaving is not exact. This adds
363
+ # even more randomness to the training pipeline.
364
+ d = d.apply(
365
+ tf.contrib.data.parallel_interleave(
366
+ tf.data.TFRecordDataset,
367
+ sloppy=is_training,
368
+ cycle_length=cycle_length))
369
+ d = d.shuffle(buffer_size=100)
370
+ else:
371
+ d = tf.data.TFRecordDataset(input_files)
372
+ # Since we evaluate for a fixed number of steps we don't want to encounter
373
+ # out-of-range exceptions.
374
+ d = d.repeat()
375
+
376
+ # We must `drop_remainder` on training because the TPU requires fixed
377
+ # size dimensions. For eval, we assume we are evaluating on the CPU or GPU
378
+ # and we *don't* want to drop the remainder, otherwise we wont cover
379
+ # every sample.
380
+ d = d.apply(
381
+ tf.contrib.data.map_and_batch(
382
+ lambda record: _decode_record(record, name_to_features),
383
+ batch_size=batch_size,
384
+ num_parallel_batches=num_cpu_threads,
385
+ drop_remainder=True))
386
+ return d
387
+
388
+ return input_fn
389
+
390
+
391
+ def _decode_record(record, name_to_features):
392
+ """Decodes a record to a TensorFlow example."""
393
+ example = tf.parse_single_example(record, name_to_features)
394
+
395
+ # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
396
+ # So cast all int64 to int32.
397
+ for name in list(example.keys()):
398
+ t = example[name]
399
+ if t.dtype == tf.int64:
400
+ t = tf.to_int32(t)
401
+ example[name] = t
402
+
403
+ return example
404
+
405
+
406
+ def main(_):
407
+ tf.logging.set_verbosity(tf.logging.INFO)
408
+
409
+ if not FLAGS.do_train and not FLAGS.do_eval:
410
+ raise ValueError("At least one of `do_train` or `do_eval` must be True.")
411
+
412
+ bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
413
+
414
+ tf.gfile.MakeDirs(FLAGS.output_dir)
415
+
416
+ input_files = []
417
+ for input_pattern in FLAGS.input_file.split(","):
418
+ input_files.extend(tf.gfile.Glob(input_pattern))
419
+
420
+ tf.logging.info("*** Input Files ***")
421
+ for input_file in input_files:
422
+ tf.logging.info(" %s" % input_file)
423
+
424
+ tpu_cluster_resolver = None
425
+ if FLAGS.use_tpu and FLAGS.tpu_name:
426
+ tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
427
+ FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
428
+
429
+ is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
430
+ run_config = tf.contrib.tpu.RunConfig(
431
+ cluster=tpu_cluster_resolver,
432
+ master=FLAGS.master,
433
+ model_dir=FLAGS.output_dir,
434
+ save_checkpoints_steps=FLAGS.save_checkpoints_steps,
435
+ tpu_config=tf.contrib.tpu.TPUConfig(
436
+ iterations_per_loop=FLAGS.iterations_per_loop,
437
+ num_shards=FLAGS.num_tpu_cores,
438
+ per_host_input_for_training=is_per_host))
439
+
440
+ model_fn = model_fn_builder(
441
+ bert_config=bert_config,
442
+ init_checkpoint=FLAGS.init_checkpoint,
443
+ learning_rate=FLAGS.learning_rate,
444
+ num_train_steps=FLAGS.num_train_steps,
445
+ num_warmup_steps=FLAGS.num_warmup_steps,
446
+ use_tpu=FLAGS.use_tpu,
447
+ use_one_hot_embeddings=FLAGS.use_tpu)
448
+
449
+ # If TPU is not available, this will fall back to normal Estimator on CPU
450
+ # or GPU.
451
+ estimator = tf.contrib.tpu.TPUEstimator(
452
+ use_tpu=FLAGS.use_tpu,
453
+ model_fn=model_fn,
454
+ config=run_config,
455
+ train_batch_size=FLAGS.train_batch_size,
456
+ eval_batch_size=FLAGS.eval_batch_size)
457
+
458
+ if FLAGS.do_train:
459
+ tf.logging.info("***** Running training *****")
460
+ tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
461
+ train_input_fn = input_fn_builder(
462
+ input_files=input_files,
463
+ max_seq_length=FLAGS.max_seq_length,
464
+ max_predictions_per_seq=FLAGS.max_predictions_per_seq,
465
+ is_training=True)
466
+ estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps)
467
+
468
+ if FLAGS.do_eval:
469
+ tf.logging.info("***** Running evaluation *****")
470
+ tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
471
+
472
+ eval_input_fn = input_fn_builder(
473
+ input_files=input_files,
474
+ max_seq_length=FLAGS.max_seq_length,
475
+ max_predictions_per_seq=FLAGS.max_predictions_per_seq,
476
+ is_training=False)
477
+
478
+ result = estimator.evaluate(
479
+ input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
480
+
481
+ output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
482
+ with tf.gfile.GFile(output_eval_file, "w") as writer:
483
+ tf.logging.info("***** Eval results *****")
484
+ for key in sorted(result.keys()):
485
+ tf.logging.info(" %s = %s", key, str(result[key]))
486
+ writer.write("%s = %s\n" % (key, str(result[key])))
487
+
488
+
489
+ if __name__ == "__main__":
490
+ flags.mark_flag_as_required("input_file")
491
+ flags.mark_flag_as_required("bert_config_file")
492
+ flags.mark_flag_as_required("output_dir")
493
+ tf.app.run()
bert-master/bert-master/run_squad.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Run BERT on SQuAD 1.1 and SQuAD 2.0."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import collections
22
+ import json
23
+ import math
24
+ import os
25
+ import random
26
+ import modeling
27
+ import optimization
28
+ import tokenization
29
+ import six
30
+ import tensorflow as tf
31
+
32
+ flags = tf.flags
33
+
34
+ FLAGS = flags.FLAGS
35
+
36
+ ## Required parameters
37
+ flags.DEFINE_string(
38
+ "bert_config_file", None,
39
+ "The config json file corresponding to the pre-trained BERT model. "
40
+ "This specifies the model architecture.")
41
+
42
+ flags.DEFINE_string("vocab_file", None,
43
+ "The vocabulary file that the BERT model was trained on.")
44
+
45
+ flags.DEFINE_string(
46
+ "output_dir", None,
47
+ "The output directory where the model checkpoints will be written.")
48
+
49
+ ## Other parameters
50
+ flags.DEFINE_string("train_file", None,
51
+ "SQuAD json for training. E.g., train-v1.1.json")
52
+
53
+ flags.DEFINE_string(
54
+ "predict_file", None,
55
+ "SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
56
+
57
+ flags.DEFINE_string(
58
+ "init_checkpoint", None,
59
+ "Initial checkpoint (usually from a pre-trained BERT model).")
60
+
61
+ flags.DEFINE_bool(
62
+ "do_lower_case", True,
63
+ "Whether to lower case the input text. Should be True for uncased "
64
+ "models and False for cased models.")
65
+
66
+ flags.DEFINE_integer(
67
+ "max_seq_length", 384,
68
+ "The maximum total input sequence length after WordPiece tokenization. "
69
+ "Sequences longer than this will be truncated, and sequences shorter "
70
+ "than this will be padded.")
71
+
72
+ flags.DEFINE_integer(
73
+ "doc_stride", 128,
74
+ "When splitting up a long document into chunks, how much stride to "
75
+ "take between chunks.")
76
+
77
+ flags.DEFINE_integer(
78
+ "max_query_length", 64,
79
+ "The maximum number of tokens for the question. Questions longer than "
80
+ "this will be truncated to this length.")
81
+
82
+ flags.DEFINE_bool("do_train", False, "Whether to run training.")
83
+
84
+ flags.DEFINE_bool("do_predict", False, "Whether to run eval on the dev set.")
85
+
86
+ flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
87
+
88
+ flags.DEFINE_integer("predict_batch_size", 8,
89
+ "Total batch size for predictions.")
90
+
91
+ flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
92
+
93
+ flags.DEFINE_float("num_train_epochs", 3.0,
94
+ "Total number of training epochs to perform.")
95
+
96
+ flags.DEFINE_float(
97
+ "warmup_proportion", 0.1,
98
+ "Proportion of training to perform linear learning rate warmup for. "
99
+ "E.g., 0.1 = 10% of training.")
100
+
101
+ flags.DEFINE_integer("save_checkpoints_steps", 1000,
102
+ "How often to save the model checkpoint.")
103
+
104
+ flags.DEFINE_integer("iterations_per_loop", 1000,
105
+ "How many steps to make in each estimator call.")
106
+
107
+ flags.DEFINE_integer(
108
+ "n_best_size", 20,
109
+ "The total number of n-best predictions to generate in the "
110
+ "nbest_predictions.json output file.")
111
+
112
+ flags.DEFINE_integer(
113
+ "max_answer_length", 30,
114
+ "The maximum length of an answer that can be generated. This is needed "
115
+ "because the start and end predictions are not conditioned on one another.")
116
+
117
+ flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
118
+
119
+ tf.flags.DEFINE_string(
120
+ "tpu_name", None,
121
+ "The Cloud TPU to use for training. This should be either the name "
122
+ "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
123
+ "url.")
124
+
125
+ tf.flags.DEFINE_string(
126
+ "tpu_zone", None,
127
+ "[Optional] GCE zone where the Cloud TPU is located in. If not "
128
+ "specified, we will attempt to automatically detect the GCE project from "
129
+ "metadata.")
130
+
131
+ tf.flags.DEFINE_string(
132
+ "gcp_project", None,
133
+ "[Optional] Project name for the Cloud TPU-enabled project. If not "
134
+ "specified, we will attempt to automatically detect the GCE project from "
135
+ "metadata.")
136
+
137
+ tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
138
+
139
+ flags.DEFINE_integer(
140
+ "num_tpu_cores", 8,
141
+ "Only used if `use_tpu` is True. Total number of TPU cores to use.")
142
+
143
+ flags.DEFINE_bool(
144
+ "verbose_logging", False,
145
+ "If true, all of the warnings related to data processing will be printed. "
146
+ "A number of warnings are expected for a normal SQuAD evaluation.")
147
+
148
+ flags.DEFINE_bool(
149
+ "version_2_with_negative", False,
150
+ "If true, the SQuAD examples contain some that do not have an answer.")
151
+
152
+ flags.DEFINE_float(
153
+ "null_score_diff_threshold", 0.0,
154
+ "If null_score - best_non_null is greater than the threshold predict null.")
155
+
156
+
157
+ class SquadExample(object):
158
+ """A single training/test example for simple sequence classification.
159
+
160
+ For examples without an answer, the start and end position are -1.
161
+ """
162
+
163
+ def __init__(self,
164
+ qas_id,
165
+ question_text,
166
+ doc_tokens,
167
+ orig_answer_text=None,
168
+ start_position=None,
169
+ end_position=None,
170
+ is_impossible=False):
171
+ self.qas_id = qas_id
172
+ self.question_text = question_text
173
+ self.doc_tokens = doc_tokens
174
+ self.orig_answer_text = orig_answer_text
175
+ self.start_position = start_position
176
+ self.end_position = end_position
177
+ self.is_impossible = is_impossible
178
+
179
+ def __str__(self):
180
+ return self.__repr__()
181
+
182
+ def __repr__(self):
183
+ s = ""
184
+ s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
185
+ s += ", question_text: %s" % (
186
+ tokenization.printable_text(self.question_text))
187
+ s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
188
+ if self.start_position:
189
+ s += ", start_position: %d" % (self.start_position)
190
+ if self.start_position:
191
+ s += ", end_position: %d" % (self.end_position)
192
+ if self.start_position:
193
+ s += ", is_impossible: %r" % (self.is_impossible)
194
+ return s
195
+
196
+
197
+ class InputFeatures(object):
198
+ """A single set of features of data."""
199
+
200
+ def __init__(self,
201
+ unique_id,
202
+ example_index,
203
+ doc_span_index,
204
+ tokens,
205
+ token_to_orig_map,
206
+ token_is_max_context,
207
+ input_ids,
208
+ input_mask,
209
+ segment_ids,
210
+ start_position=None,
211
+ end_position=None,
212
+ is_impossible=None):
213
+ self.unique_id = unique_id
214
+ self.example_index = example_index
215
+ self.doc_span_index = doc_span_index
216
+ self.tokens = tokens
217
+ self.token_to_orig_map = token_to_orig_map
218
+ self.token_is_max_context = token_is_max_context
219
+ self.input_ids = input_ids
220
+ self.input_mask = input_mask
221
+ self.segment_ids = segment_ids
222
+ self.start_position = start_position
223
+ self.end_position = end_position
224
+ self.is_impossible = is_impossible
225
+
226
+
227
+ def read_squad_examples(input_file, is_training):
228
+ """Read a SQuAD json file into a list of SquadExample."""
229
+ with tf.gfile.Open(input_file, "r") as reader:
230
+ input_data = json.load(reader)["data"]
231
+
232
+ def is_whitespace(c):
233
+ if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
234
+ return True
235
+ return False
236
+
237
+ examples = []
238
+ for entry in input_data:
239
+ for paragraph in entry["paragraphs"]:
240
+ paragraph_text = paragraph["context"]
241
+ doc_tokens = []
242
+ char_to_word_offset = []
243
+ prev_is_whitespace = True
244
+ for c in paragraph_text:
245
+ if is_whitespace(c):
246
+ prev_is_whitespace = True
247
+ else:
248
+ if prev_is_whitespace:
249
+ doc_tokens.append(c)
250
+ else:
251
+ doc_tokens[-1] += c
252
+ prev_is_whitespace = False
253
+ char_to_word_offset.append(len(doc_tokens) - 1)
254
+
255
+ for qa in paragraph["qas"]:
256
+ qas_id = qa["id"]
257
+ question_text = qa["question"]
258
+ start_position = None
259
+ end_position = None
260
+ orig_answer_text = None
261
+ is_impossible = False
262
+ if is_training:
263
+
264
+ if FLAGS.version_2_with_negative:
265
+ is_impossible = qa["is_impossible"]
266
+ if (len(qa["answers"]) != 1) and (not is_impossible):
267
+ raise ValueError(
268
+ "For training, each question should have exactly 1 answer.")
269
+ if not is_impossible:
270
+ answer = qa["answers"][0]
271
+ orig_answer_text = answer["text"]
272
+ answer_offset = answer["answer_start"]
273
+ answer_length = len(orig_answer_text)
274
+ start_position = char_to_word_offset[answer_offset]
275
+ end_position = char_to_word_offset[answer_offset + answer_length -
276
+ 1]
277
+ # Only add answers where the text can be exactly recovered from the
278
+ # document. If this CAN'T happen it's likely due to weird Unicode
279
+ # stuff so we will just skip the example.
280
+ #
281
+ # Note that this means for training mode, every example is NOT
282
+ # guaranteed to be preserved.
283
+ actual_text = " ".join(
284
+ doc_tokens[start_position:(end_position + 1)])
285
+ cleaned_answer_text = " ".join(
286
+ tokenization.whitespace_tokenize(orig_answer_text))
287
+ if actual_text.find(cleaned_answer_text) == -1:
288
+ tf.logging.warning("Could not find answer: '%s' vs. '%s'",
289
+ actual_text, cleaned_answer_text)
290
+ continue
291
+ else:
292
+ start_position = -1
293
+ end_position = -1
294
+ orig_answer_text = ""
295
+
296
+ example = SquadExample(
297
+ qas_id=qas_id,
298
+ question_text=question_text,
299
+ doc_tokens=doc_tokens,
300
+ orig_answer_text=orig_answer_text,
301
+ start_position=start_position,
302
+ end_position=end_position,
303
+ is_impossible=is_impossible)
304
+ examples.append(example)
305
+
306
+ return examples
307
+
308
+
309
+ def convert_examples_to_features(examples, tokenizer, max_seq_length,
310
+ doc_stride, max_query_length, is_training,
311
+ output_fn):
312
+ """Loads a data file into a list of `InputBatch`s."""
313
+
314
+ unique_id = 1000000000
315
+
316
+ for (example_index, example) in enumerate(examples):
317
+ query_tokens = tokenizer.tokenize(example.question_text)
318
+
319
+ if len(query_tokens) > max_query_length:
320
+ query_tokens = query_tokens[0:max_query_length]
321
+
322
+ tok_to_orig_index = []
323
+ orig_to_tok_index = []
324
+ all_doc_tokens = []
325
+ for (i, token) in enumerate(example.doc_tokens):
326
+ orig_to_tok_index.append(len(all_doc_tokens))
327
+ sub_tokens = tokenizer.tokenize(token)
328
+ for sub_token in sub_tokens:
329
+ tok_to_orig_index.append(i)
330
+ all_doc_tokens.append(sub_token)
331
+
332
+ tok_start_position = None
333
+ tok_end_position = None
334
+ if is_training and example.is_impossible:
335
+ tok_start_position = -1
336
+ tok_end_position = -1
337
+ if is_training and not example.is_impossible:
338
+ tok_start_position = orig_to_tok_index[example.start_position]
339
+ if example.end_position < len(example.doc_tokens) - 1:
340
+ tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
341
+ else:
342
+ tok_end_position = len(all_doc_tokens) - 1
343
+ (tok_start_position, tok_end_position) = _improve_answer_span(
344
+ all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
345
+ example.orig_answer_text)
346
+
347
+ # The -3 accounts for [CLS], [SEP] and [SEP]
348
+ max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
349
+
350
+ # We can have documents that are longer than the maximum sequence length.
351
+ # To deal with this we do a sliding window approach, where we take chunks
352
+ # of the up to our max length with a stride of `doc_stride`.
353
+ _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
354
+ "DocSpan", ["start", "length"])
355
+ doc_spans = []
356
+ start_offset = 0
357
+ while start_offset < len(all_doc_tokens):
358
+ length = len(all_doc_tokens) - start_offset
359
+ if length > max_tokens_for_doc:
360
+ length = max_tokens_for_doc
361
+ doc_spans.append(_DocSpan(start=start_offset, length=length))
362
+ if start_offset + length == len(all_doc_tokens):
363
+ break
364
+ start_offset += min(length, doc_stride)
365
+
366
+ for (doc_span_index, doc_span) in enumerate(doc_spans):
367
+ tokens = []
368
+ token_to_orig_map = {}
369
+ token_is_max_context = {}
370
+ segment_ids = []
371
+ tokens.append("[CLS]")
372
+ segment_ids.append(0)
373
+ for token in query_tokens:
374
+ tokens.append(token)
375
+ segment_ids.append(0)
376
+ tokens.append("[SEP]")
377
+ segment_ids.append(0)
378
+
379
+ for i in range(doc_span.length):
380
+ split_token_index = doc_span.start + i
381
+ token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
382
+
383
+ is_max_context = _check_is_max_context(doc_spans, doc_span_index,
384
+ split_token_index)
385
+ token_is_max_context[len(tokens)] = is_max_context
386
+ tokens.append(all_doc_tokens[split_token_index])
387
+ segment_ids.append(1)
388
+ tokens.append("[SEP]")
389
+ segment_ids.append(1)
390
+
391
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
392
+
393
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
394
+ # tokens are attended to.
395
+ input_mask = [1] * len(input_ids)
396
+
397
+ # Zero-pad up to the sequence length.
398
+ while len(input_ids) < max_seq_length:
399
+ input_ids.append(0)
400
+ input_mask.append(0)
401
+ segment_ids.append(0)
402
+
403
+ assert len(input_ids) == max_seq_length
404
+ assert len(input_mask) == max_seq_length
405
+ assert len(segment_ids) == max_seq_length
406
+
407
+ start_position = None
408
+ end_position = None
409
+ if is_training and not example.is_impossible:
410
+ # For training, if our document chunk does not contain an annotation
411
+ # we throw it out, since there is nothing to predict.
412
+ doc_start = doc_span.start
413
+ doc_end = doc_span.start + doc_span.length - 1
414
+ out_of_span = False
415
+ if not (tok_start_position >= doc_start and
416
+ tok_end_position <= doc_end):
417
+ out_of_span = True
418
+ if out_of_span:
419
+ start_position = 0
420
+ end_position = 0
421
+ else:
422
+ doc_offset = len(query_tokens) + 2
423
+ start_position = tok_start_position - doc_start + doc_offset
424
+ end_position = tok_end_position - doc_start + doc_offset
425
+
426
+ if is_training and example.is_impossible:
427
+ start_position = 0
428
+ end_position = 0
429
+
430
+ if example_index < 20:
431
+ tf.logging.info("*** Example ***")
432
+ tf.logging.info("unique_id: %s" % (unique_id))
433
+ tf.logging.info("example_index: %s" % (example_index))
434
+ tf.logging.info("doc_span_index: %s" % (doc_span_index))
435
+ tf.logging.info("tokens: %s" % " ".join(
436
+ [tokenization.printable_text(x) for x in tokens]))
437
+ tf.logging.info("token_to_orig_map: %s" % " ".join(
438
+ ["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
439
+ tf.logging.info("token_is_max_context: %s" % " ".join([
440
+ "%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
441
+ ]))
442
+ tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
443
+ tf.logging.info(
444
+ "input_mask: %s" % " ".join([str(x) for x in input_mask]))
445
+ tf.logging.info(
446
+ "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
447
+ if is_training and example.is_impossible:
448
+ tf.logging.info("impossible example")
449
+ if is_training and not example.is_impossible:
450
+ answer_text = " ".join(tokens[start_position:(end_position + 1)])
451
+ tf.logging.info("start_position: %d" % (start_position))
452
+ tf.logging.info("end_position: %d" % (end_position))
453
+ tf.logging.info(
454
+ "answer: %s" % (tokenization.printable_text(answer_text)))
455
+
456
+ feature = InputFeatures(
457
+ unique_id=unique_id,
458
+ example_index=example_index,
459
+ doc_span_index=doc_span_index,
460
+ tokens=tokens,
461
+ token_to_orig_map=token_to_orig_map,
462
+ token_is_max_context=token_is_max_context,
463
+ input_ids=input_ids,
464
+ input_mask=input_mask,
465
+ segment_ids=segment_ids,
466
+ start_position=start_position,
467
+ end_position=end_position,
468
+ is_impossible=example.is_impossible)
469
+
470
+ # Run callback
471
+ output_fn(feature)
472
+
473
+ unique_id += 1
474
+
475
+
476
+ def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
477
+ orig_answer_text):
478
+ """Returns tokenized answer spans that better match the annotated answer."""
479
+
480
+ # The SQuAD annotations are character based. We first project them to
481
+ # whitespace-tokenized words. But then after WordPiece tokenization, we can
482
+ # often find a "better match". For example:
483
+ #
484
+ # Question: What year was John Smith born?
485
+ # Context: The leader was John Smith (1895-1943).
486
+ # Answer: 1895
487
+ #
488
+ # The original whitespace-tokenized answer will be "(1895-1943).". However
489
+ # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
490
+ # the exact answer, 1895.
491
+ #
492
+ # However, this is not always possible. Consider the following:
493
+ #
494
+ # Question: What country is the top exporter of electornics?
495
+ # Context: The Japanese electronics industry is the lagest in the world.
496
+ # Answer: Japan
497
+ #
498
+ # In this case, the annotator chose "Japan" as a character sub-span of
499
+ # the word "Japanese". Since our WordPiece tokenizer does not split
500
+ # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
501
+ # in SQuAD, but does happen.
502
+ tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
503
+
504
+ for new_start in range(input_start, input_end + 1):
505
+ for new_end in range(input_end, new_start - 1, -1):
506
+ text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
507
+ if text_span == tok_answer_text:
508
+ return (new_start, new_end)
509
+
510
+ return (input_start, input_end)
511
+
512
+
513
+ def _check_is_max_context(doc_spans, cur_span_index, position):
514
+ """Check if this is the 'max context' doc span for the token."""
515
+
516
+ # Because of the sliding window approach taken to scoring documents, a single
517
+ # token can appear in multiple documents. E.g.
518
+ # Doc: the man went to the store and bought a gallon of milk
519
+ # Span A: the man went to the
520
+ # Span B: to the store and bought
521
+ # Span C: and bought a gallon of
522
+ # ...
523
+ #
524
+ # Now the word 'bought' will have two scores from spans B and C. We only
525
+ # want to consider the score with "maximum context", which we define as
526
+ # the *minimum* of its left and right context (the *sum* of left and
527
+ # right context will always be the same, of course).
528
+ #
529
+ # In the example the maximum context for 'bought' would be span C since
530
+ # it has 1 left context and 3 right context, while span B has 4 left context
531
+ # and 0 right context.
532
+ best_score = None
533
+ best_span_index = None
534
+ for (span_index, doc_span) in enumerate(doc_spans):
535
+ end = doc_span.start + doc_span.length - 1
536
+ if position < doc_span.start:
537
+ continue
538
+ if position > end:
539
+ continue
540
+ num_left_context = position - doc_span.start
541
+ num_right_context = end - position
542
+ score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
543
+ if best_score is None or score > best_score:
544
+ best_score = score
545
+ best_span_index = span_index
546
+
547
+ return cur_span_index == best_span_index
548
+
549
+
550
+ def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
551
+ use_one_hot_embeddings):
552
+ """Creates a classification model."""
553
+ model = modeling.BertModel(
554
+ config=bert_config,
555
+ is_training=is_training,
556
+ input_ids=input_ids,
557
+ input_mask=input_mask,
558
+ token_type_ids=segment_ids,
559
+ use_one_hot_embeddings=use_one_hot_embeddings)
560
+
561
+ final_hidden = model.get_sequence_output()
562
+
563
+ final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
564
+ batch_size = final_hidden_shape[0]
565
+ seq_length = final_hidden_shape[1]
566
+ hidden_size = final_hidden_shape[2]
567
+
568
+ output_weights = tf.get_variable(
569
+ "cls/squad/output_weights", [2, hidden_size],
570
+ initializer=tf.truncated_normal_initializer(stddev=0.02))
571
+
572
+ output_bias = tf.get_variable(
573
+ "cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
574
+
575
+ final_hidden_matrix = tf.reshape(final_hidden,
576
+ [batch_size * seq_length, hidden_size])
577
+ logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
578
+ logits = tf.nn.bias_add(logits, output_bias)
579
+
580
+ logits = tf.reshape(logits, [batch_size, seq_length, 2])
581
+ logits = tf.transpose(logits, [2, 0, 1])
582
+
583
+ unstacked_logits = tf.unstack(logits, axis=0)
584
+
585
+ (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
586
+
587
+ return (start_logits, end_logits)
588
+
589
+
590
+ def model_fn_builder(bert_config, init_checkpoint, learning_rate,
591
+ num_train_steps, num_warmup_steps, use_tpu,
592
+ use_one_hot_embeddings):
593
+ """Returns `model_fn` closure for TPUEstimator."""
594
+
595
+ def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
596
+ """The `model_fn` for TPUEstimator."""
597
+
598
+ tf.logging.info("*** Features ***")
599
+ for name in sorted(features.keys()):
600
+ tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
601
+
602
+ unique_ids = features["unique_ids"]
603
+ input_ids = features["input_ids"]
604
+ input_mask = features["input_mask"]
605
+ segment_ids = features["segment_ids"]
606
+
607
+ is_training = (mode == tf.estimator.ModeKeys.TRAIN)
608
+
609
+ (start_logits, end_logits) = create_model(
610
+ bert_config=bert_config,
611
+ is_training=is_training,
612
+ input_ids=input_ids,
613
+ input_mask=input_mask,
614
+ segment_ids=segment_ids,
615
+ use_one_hot_embeddings=use_one_hot_embeddings)
616
+
617
+ tvars = tf.trainable_variables()
618
+
619
+ initialized_variable_names = {}
620
+ scaffold_fn = None
621
+ if init_checkpoint:
622
+ (assignment_map, initialized_variable_names
623
+ ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
624
+ if use_tpu:
625
+
626
+ def tpu_scaffold():
627
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
628
+ return tf.train.Scaffold()
629
+
630
+ scaffold_fn = tpu_scaffold
631
+ else:
632
+ tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
633
+
634
+ tf.logging.info("**** Trainable Variables ****")
635
+ for var in tvars:
636
+ init_string = ""
637
+ if var.name in initialized_variable_names:
638
+ init_string = ", *INIT_FROM_CKPT*"
639
+ tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
640
+ init_string)
641
+
642
+ output_spec = None
643
+ if mode == tf.estimator.ModeKeys.TRAIN:
644
+ seq_length = modeling.get_shape_list(input_ids)[1]
645
+
646
+ def compute_loss(logits, positions):
647
+ one_hot_positions = tf.one_hot(
648
+ positions, depth=seq_length, dtype=tf.float32)
649
+ log_probs = tf.nn.log_softmax(logits, axis=-1)
650
+ loss = -tf.reduce_mean(
651
+ tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
652
+ return loss
653
+
654
+ start_positions = features["start_positions"]
655
+ end_positions = features["end_positions"]
656
+
657
+ start_loss = compute_loss(start_logits, start_positions)
658
+ end_loss = compute_loss(end_logits, end_positions)
659
+
660
+ total_loss = (start_loss + end_loss) / 2.0
661
+
662
+ train_op = optimization.create_optimizer(
663
+ total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
664
+
665
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
666
+ mode=mode,
667
+ loss=total_loss,
668
+ train_op=train_op,
669
+ scaffold_fn=scaffold_fn)
670
+ elif mode == tf.estimator.ModeKeys.PREDICT:
671
+ predictions = {
672
+ "unique_ids": unique_ids,
673
+ "start_logits": start_logits,
674
+ "end_logits": end_logits,
675
+ }
676
+ output_spec = tf.contrib.tpu.TPUEstimatorSpec(
677
+ mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
678
+ else:
679
+ raise ValueError(
680
+ "Only TRAIN and PREDICT modes are supported: %s" % (mode))
681
+
682
+ return output_spec
683
+
684
+ return model_fn
685
+
686
+
687
+ def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
688
+ """Creates an `input_fn` closure to be passed to TPUEstimator."""
689
+
690
+ name_to_features = {
691
+ "unique_ids": tf.FixedLenFeature([], tf.int64),
692
+ "input_ids": tf.FixedLenFeature([seq_length], tf.int64),
693
+ "input_mask": tf.FixedLenFeature([seq_length], tf.int64),
694
+ "segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
695
+ }
696
+
697
+ if is_training:
698
+ name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
699
+ name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
700
+
701
+ def _decode_record(record, name_to_features):
702
+ """Decodes a record to a TensorFlow example."""
703
+ example = tf.parse_single_example(record, name_to_features)
704
+
705
+ # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
706
+ # So cast all int64 to int32.
707
+ for name in list(example.keys()):
708
+ t = example[name]
709
+ if t.dtype == tf.int64:
710
+ t = tf.to_int32(t)
711
+ example[name] = t
712
+
713
+ return example
714
+
715
+ def input_fn(params):
716
+ """The actual input function."""
717
+ batch_size = params["batch_size"]
718
+
719
+ # For training, we want a lot of parallel reading and shuffling.
720
+ # For eval, we want no shuffling and parallel reading doesn't matter.
721
+ d = tf.data.TFRecordDataset(input_file)
722
+ if is_training:
723
+ d = d.repeat()
724
+ d = d.shuffle(buffer_size=100)
725
+
726
+ d = d.apply(
727
+ tf.contrib.data.map_and_batch(
728
+ lambda record: _decode_record(record, name_to_features),
729
+ batch_size=batch_size,
730
+ drop_remainder=drop_remainder))
731
+
732
+ return d
733
+
734
+ return input_fn
735
+
736
+
737
+ RawResult = collections.namedtuple("RawResult",
738
+ ["unique_id", "start_logits", "end_logits"])
739
+
740
+
741
+ def write_predictions(all_examples, all_features, all_results, n_best_size,
742
+ max_answer_length, do_lower_case, output_prediction_file,
743
+ output_nbest_file, output_null_log_odds_file):
744
+ """Write final predictions to the json file and log-odds of null if needed."""
745
+ tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
746
+ tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
747
+
748
+ example_index_to_features = collections.defaultdict(list)
749
+ for feature in all_features:
750
+ example_index_to_features[feature.example_index].append(feature)
751
+
752
+ unique_id_to_result = {}
753
+ for result in all_results:
754
+ unique_id_to_result[result.unique_id] = result
755
+
756
+ _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
757
+ "PrelimPrediction",
758
+ ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
759
+
760
+ all_predictions = collections.OrderedDict()
761
+ all_nbest_json = collections.OrderedDict()
762
+ scores_diff_json = collections.OrderedDict()
763
+
764
+ for (example_index, example) in enumerate(all_examples):
765
+ features = example_index_to_features[example_index]
766
+
767
+ prelim_predictions = []
768
+ # keep track of the minimum score of null start+end of position 0
769
+ score_null = 1000000 # large and positive
770
+ min_null_feature_index = 0 # the paragraph slice with min mull score
771
+ null_start_logit = 0 # the start logit at the slice with min null score
772
+ null_end_logit = 0 # the end logit at the slice with min null score
773
+ for (feature_index, feature) in enumerate(features):
774
+ result = unique_id_to_result[feature.unique_id]
775
+ start_indexes = _get_best_indexes(result.start_logits, n_best_size)
776
+ end_indexes = _get_best_indexes(result.end_logits, n_best_size)
777
+ # if we could have irrelevant answers, get the min score of irrelevant
778
+ if FLAGS.version_2_with_negative:
779
+ feature_null_score = result.start_logits[0] + result.end_logits[0]
780
+ if feature_null_score < score_null:
781
+ score_null = feature_null_score
782
+ min_null_feature_index = feature_index
783
+ null_start_logit = result.start_logits[0]
784
+ null_end_logit = result.end_logits[0]
785
+ for start_index in start_indexes:
786
+ for end_index in end_indexes:
787
+ # We could hypothetically create invalid predictions, e.g., predict
788
+ # that the start of the span is in the question. We throw out all
789
+ # invalid predictions.
790
+ if start_index >= len(feature.tokens):
791
+ continue
792
+ if end_index >= len(feature.tokens):
793
+ continue
794
+ if start_index not in feature.token_to_orig_map:
795
+ continue
796
+ if end_index not in feature.token_to_orig_map:
797
+ continue
798
+ if not feature.token_is_max_context.get(start_index, False):
799
+ continue
800
+ if end_index < start_index:
801
+ continue
802
+ length = end_index - start_index + 1
803
+ if length > max_answer_length:
804
+ continue
805
+ prelim_predictions.append(
806
+ _PrelimPrediction(
807
+ feature_index=feature_index,
808
+ start_index=start_index,
809
+ end_index=end_index,
810
+ start_logit=result.start_logits[start_index],
811
+ end_logit=result.end_logits[end_index]))
812
+
813
+ if FLAGS.version_2_with_negative:
814
+ prelim_predictions.append(
815
+ _PrelimPrediction(
816
+ feature_index=min_null_feature_index,
817
+ start_index=0,
818
+ end_index=0,
819
+ start_logit=null_start_logit,
820
+ end_logit=null_end_logit))
821
+ prelim_predictions = sorted(
822
+ prelim_predictions,
823
+ key=lambda x: (x.start_logit + x.end_logit),
824
+ reverse=True)
825
+
826
+ _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
827
+ "NbestPrediction", ["text", "start_logit", "end_logit"])
828
+
829
+ seen_predictions = {}
830
+ nbest = []
831
+ for pred in prelim_predictions:
832
+ if len(nbest) >= n_best_size:
833
+ break
834
+ feature = features[pred.feature_index]
835
+ if pred.start_index > 0: # this is a non-null prediction
836
+ tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
837
+ orig_doc_start = feature.token_to_orig_map[pred.start_index]
838
+ orig_doc_end = feature.token_to_orig_map[pred.end_index]
839
+ orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
840
+ tok_text = " ".join(tok_tokens)
841
+
842
+ # De-tokenize WordPieces that have been split off.
843
+ tok_text = tok_text.replace(" ##", "")
844
+ tok_text = tok_text.replace("##", "")
845
+
846
+ # Clean whitespace
847
+ tok_text = tok_text.strip()
848
+ tok_text = " ".join(tok_text.split())
849
+ orig_text = " ".join(orig_tokens)
850
+
851
+ final_text = get_final_text(tok_text, orig_text, do_lower_case)
852
+ if final_text in seen_predictions:
853
+ continue
854
+
855
+ seen_predictions[final_text] = True
856
+ else:
857
+ final_text = ""
858
+ seen_predictions[final_text] = True
859
+
860
+ nbest.append(
861
+ _NbestPrediction(
862
+ text=final_text,
863
+ start_logit=pred.start_logit,
864
+ end_logit=pred.end_logit))
865
+
866
+ # if we didn't inlude the empty option in the n-best, inlcude it
867
+ if FLAGS.version_2_with_negative:
868
+ if "" not in seen_predictions:
869
+ nbest.append(
870
+ _NbestPrediction(
871
+ text="", start_logit=null_start_logit,
872
+ end_logit=null_end_logit))
873
+ # In very rare edge cases we could have no valid predictions. So we
874
+ # just create a nonce prediction in this case to avoid failure.
875
+ if not nbest:
876
+ nbest.append(
877
+ _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
878
+
879
+ assert len(nbest) >= 1
880
+
881
+ total_scores = []
882
+ best_non_null_entry = None
883
+ for entry in nbest:
884
+ total_scores.append(entry.start_logit + entry.end_logit)
885
+ if not best_non_null_entry:
886
+ if entry.text:
887
+ best_non_null_entry = entry
888
+
889
+ probs = _compute_softmax(total_scores)
890
+
891
+ nbest_json = []
892
+ for (i, entry) in enumerate(nbest):
893
+ output = collections.OrderedDict()
894
+ output["text"] = entry.text
895
+ output["probability"] = probs[i]
896
+ output["start_logit"] = entry.start_logit
897
+ output["end_logit"] = entry.end_logit
898
+ nbest_json.append(output)
899
+
900
+ assert len(nbest_json) >= 1
901
+
902
+ if not FLAGS.version_2_with_negative:
903
+ all_predictions[example.qas_id] = nbest_json[0]["text"]
904
+ else:
905
+ # predict "" iff the null score - the score of best non-null > threshold
906
+ score_diff = score_null - best_non_null_entry.start_logit - (
907
+ best_non_null_entry.end_logit)
908
+ scores_diff_json[example.qas_id] = score_diff
909
+ if score_diff > FLAGS.null_score_diff_threshold:
910
+ all_predictions[example.qas_id] = ""
911
+ else:
912
+ all_predictions[example.qas_id] = best_non_null_entry.text
913
+
914
+ all_nbest_json[example.qas_id] = nbest_json
915
+
916
+ with tf.gfile.GFile(output_prediction_file, "w") as writer:
917
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
918
+
919
+ with tf.gfile.GFile(output_nbest_file, "w") as writer:
920
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
921
+
922
+ if FLAGS.version_2_with_negative:
923
+ with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
924
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
925
+
926
+
927
+ def get_final_text(pred_text, orig_text, do_lower_case):
928
+ """Project the tokenized prediction back to the original text."""
929
+
930
+ # When we created the data, we kept track of the alignment between original
931
+ # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
932
+ # now `orig_text` contains the span of our original text corresponding to the
933
+ # span that we predicted.
934
+ #
935
+ # However, `orig_text` may contain extra characters that we don't want in
936
+ # our prediction.
937
+ #
938
+ # For example, let's say:
939
+ # pred_text = steve smith
940
+ # orig_text = Steve Smith's
941
+ #
942
+ # We don't want to return `orig_text` because it contains the extra "'s".
943
+ #
944
+ # We don't want to return `pred_text` because it's already been normalized
945
+ # (the SQuAD eval script also does punctuation stripping/lower casing but
946
+ # our tokenizer does additional normalization like stripping accent
947
+ # characters).
948
+ #
949
+ # What we really want to return is "Steve Smith".
950
+ #
951
+ # Therefore, we have to apply a semi-complicated alignment heruistic between
952
+ # `pred_text` and `orig_text` to get a character-to-charcter alignment. This
953
+ # can fail in certain cases in which case we just return `orig_text`.
954
+
955
+ def _strip_spaces(text):
956
+ ns_chars = []
957
+ ns_to_s_map = collections.OrderedDict()
958
+ for (i, c) in enumerate(text):
959
+ if c == " ":
960
+ continue
961
+ ns_to_s_map[len(ns_chars)] = i
962
+ ns_chars.append(c)
963
+ ns_text = "".join(ns_chars)
964
+ return (ns_text, ns_to_s_map)
965
+
966
+ # We first tokenize `orig_text`, strip whitespace from the result
967
+ # and `pred_text`, and check if they are the same length. If they are
968
+ # NOT the same length, the heuristic has failed. If they are the same
969
+ # length, we assume the characters are one-to-one aligned.
970
+ tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
971
+
972
+ tok_text = " ".join(tokenizer.tokenize(orig_text))
973
+
974
+ start_position = tok_text.find(pred_text)
975
+ if start_position == -1:
976
+ if FLAGS.verbose_logging:
977
+ tf.logging.info(
978
+ "Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
979
+ return orig_text
980
+ end_position = start_position + len(pred_text) - 1
981
+
982
+ (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
983
+ (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
984
+
985
+ if len(orig_ns_text) != len(tok_ns_text):
986
+ if FLAGS.verbose_logging:
987
+ tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
988
+ orig_ns_text, tok_ns_text)
989
+ return orig_text
990
+
991
+ # We then project the characters in `pred_text` back to `orig_text` using
992
+ # the character-to-character alignment.
993
+ tok_s_to_ns_map = {}
994
+ for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
995
+ tok_s_to_ns_map[tok_index] = i
996
+
997
+ orig_start_position = None
998
+ if start_position in tok_s_to_ns_map:
999
+ ns_start_position = tok_s_to_ns_map[start_position]
1000
+ if ns_start_position in orig_ns_to_s_map:
1001
+ orig_start_position = orig_ns_to_s_map[ns_start_position]
1002
+
1003
+ if orig_start_position is None:
1004
+ if FLAGS.verbose_logging:
1005
+ tf.logging.info("Couldn't map start position")
1006
+ return orig_text
1007
+
1008
+ orig_end_position = None
1009
+ if end_position in tok_s_to_ns_map:
1010
+ ns_end_position = tok_s_to_ns_map[end_position]
1011
+ if ns_end_position in orig_ns_to_s_map:
1012
+ orig_end_position = orig_ns_to_s_map[ns_end_position]
1013
+
1014
+ if orig_end_position is None:
1015
+ if FLAGS.verbose_logging:
1016
+ tf.logging.info("Couldn't map end position")
1017
+ return orig_text
1018
+
1019
+ output_text = orig_text[orig_start_position:(orig_end_position + 1)]
1020
+ return output_text
1021
+
1022
+
1023
+ def _get_best_indexes(logits, n_best_size):
1024
+ """Get the n-best logits from a list."""
1025
+ index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
1026
+
1027
+ best_indexes = []
1028
+ for i in range(len(index_and_score)):
1029
+ if i >= n_best_size:
1030
+ break
1031
+ best_indexes.append(index_and_score[i][0])
1032
+ return best_indexes
1033
+
1034
+
1035
+ def _compute_softmax(scores):
1036
+ """Compute softmax probability over raw logits."""
1037
+ if not scores:
1038
+ return []
1039
+
1040
+ max_score = None
1041
+ for score in scores:
1042
+ if max_score is None or score > max_score:
1043
+ max_score = score
1044
+
1045
+ exp_scores = []
1046
+ total_sum = 0.0
1047
+ for score in scores:
1048
+ x = math.exp(score - max_score)
1049
+ exp_scores.append(x)
1050
+ total_sum += x
1051
+
1052
+ probs = []
1053
+ for score in exp_scores:
1054
+ probs.append(score / total_sum)
1055
+ return probs
1056
+
1057
+
1058
+ class FeatureWriter(object):
1059
+ """Writes InputFeature to TF example file."""
1060
+
1061
+ def __init__(self, filename, is_training):
1062
+ self.filename = filename
1063
+ self.is_training = is_training
1064
+ self.num_features = 0
1065
+ self._writer = tf.python_io.TFRecordWriter(filename)
1066
+
1067
+ def process_feature(self, feature):
1068
+ """Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
1069
+ self.num_features += 1
1070
+
1071
+ def create_int_feature(values):
1072
+ feature = tf.train.Feature(
1073
+ int64_list=tf.train.Int64List(value=list(values)))
1074
+ return feature
1075
+
1076
+ features = collections.OrderedDict()
1077
+ features["unique_ids"] = create_int_feature([feature.unique_id])
1078
+ features["input_ids"] = create_int_feature(feature.input_ids)
1079
+ features["input_mask"] = create_int_feature(feature.input_mask)
1080
+ features["segment_ids"] = create_int_feature(feature.segment_ids)
1081
+
1082
+ if self.is_training:
1083
+ features["start_positions"] = create_int_feature([feature.start_position])
1084
+ features["end_positions"] = create_int_feature([feature.end_position])
1085
+ impossible = 0
1086
+ if feature.is_impossible:
1087
+ impossible = 1
1088
+ features["is_impossible"] = create_int_feature([impossible])
1089
+
1090
+ tf_example = tf.train.Example(features=tf.train.Features(feature=features))
1091
+ self._writer.write(tf_example.SerializeToString())
1092
+
1093
+ def close(self):
1094
+ self._writer.close()
1095
+
1096
+
1097
+ def validate_flags_or_throw(bert_config):
1098
+ """Validate the input FLAGS or throw an exception."""
1099
+ tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
1100
+ FLAGS.init_checkpoint)
1101
+
1102
+ if not FLAGS.do_train and not FLAGS.do_predict:
1103
+ raise ValueError("At least one of `do_train` or `do_predict` must be True.")
1104
+
1105
+ if FLAGS.do_train:
1106
+ if not FLAGS.train_file:
1107
+ raise ValueError(
1108
+ "If `do_train` is True, then `train_file` must be specified.")
1109
+ if FLAGS.do_predict:
1110
+ if not FLAGS.predict_file:
1111
+ raise ValueError(
1112
+ "If `do_predict` is True, then `predict_file` must be specified.")
1113
+
1114
+ if FLAGS.max_seq_length > bert_config.max_position_embeddings:
1115
+ raise ValueError(
1116
+ "Cannot use sequence length %d because the BERT model "
1117
+ "was only trained up to sequence length %d" %
1118
+ (FLAGS.max_seq_length, bert_config.max_position_embeddings))
1119
+
1120
+ if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
1121
+ raise ValueError(
1122
+ "The max_seq_length (%d) must be greater than max_query_length "
1123
+ "(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
1124
+
1125
+
1126
+ def main(_):
1127
+ tf.logging.set_verbosity(tf.logging.INFO)
1128
+
1129
+ bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
1130
+
1131
+ validate_flags_or_throw(bert_config)
1132
+
1133
+ tf.gfile.MakeDirs(FLAGS.output_dir)
1134
+
1135
+ tokenizer = tokenization.FullTokenizer(
1136
+ vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
1137
+
1138
+ tpu_cluster_resolver = None
1139
+ if FLAGS.use_tpu and FLAGS.tpu_name:
1140
+ tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
1141
+ FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
1142
+
1143
+ is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
1144
+ run_config = tf.contrib.tpu.RunConfig(
1145
+ cluster=tpu_cluster_resolver,
1146
+ master=FLAGS.master,
1147
+ model_dir=FLAGS.output_dir,
1148
+ save_checkpoints_steps=FLAGS.save_checkpoints_steps,
1149
+ tpu_config=tf.contrib.tpu.TPUConfig(
1150
+ iterations_per_loop=FLAGS.iterations_per_loop,
1151
+ num_shards=FLAGS.num_tpu_cores,
1152
+ per_host_input_for_training=is_per_host))
1153
+
1154
+ train_examples = None
1155
+ num_train_steps = None
1156
+ num_warmup_steps = None
1157
+ if FLAGS.do_train:
1158
+ train_examples = read_squad_examples(
1159
+ input_file=FLAGS.train_file, is_training=True)
1160
+ num_train_steps = int(
1161
+ len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
1162
+ num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
1163
+
1164
+ # Pre-shuffle the input to avoid having to make a very large shuffle
1165
+ # buffer in in the `input_fn`.
1166
+ rng = random.Random(12345)
1167
+ rng.shuffle(train_examples)
1168
+
1169
+ model_fn = model_fn_builder(
1170
+ bert_config=bert_config,
1171
+ init_checkpoint=FLAGS.init_checkpoint,
1172
+ learning_rate=FLAGS.learning_rate,
1173
+ num_train_steps=num_train_steps,
1174
+ num_warmup_steps=num_warmup_steps,
1175
+ use_tpu=FLAGS.use_tpu,
1176
+ use_one_hot_embeddings=FLAGS.use_tpu)
1177
+
1178
+ # If TPU is not available, this will fall back to normal Estimator on CPU
1179
+ # or GPU.
1180
+ estimator = tf.contrib.tpu.TPUEstimator(
1181
+ use_tpu=FLAGS.use_tpu,
1182
+ model_fn=model_fn,
1183
+ config=run_config,
1184
+ train_batch_size=FLAGS.train_batch_size,
1185
+ predict_batch_size=FLAGS.predict_batch_size)
1186
+
1187
+ if FLAGS.do_train:
1188
+ # We write to a temporary file to avoid storing very large constant tensors
1189
+ # in memory.
1190
+ train_writer = FeatureWriter(
1191
+ filename=os.path.join(FLAGS.output_dir, "train.tf_record"),
1192
+ is_training=True)
1193
+ convert_examples_to_features(
1194
+ examples=train_examples,
1195
+ tokenizer=tokenizer,
1196
+ max_seq_length=FLAGS.max_seq_length,
1197
+ doc_stride=FLAGS.doc_stride,
1198
+ max_query_length=FLAGS.max_query_length,
1199
+ is_training=True,
1200
+ output_fn=train_writer.process_feature)
1201
+ train_writer.close()
1202
+
1203
+ tf.logging.info("***** Running training *****")
1204
+ tf.logging.info(" Num orig examples = %d", len(train_examples))
1205
+ tf.logging.info(" Num split examples = %d", train_writer.num_features)
1206
+ tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
1207
+ tf.logging.info(" Num steps = %d", num_train_steps)
1208
+ del train_examples
1209
+
1210
+ train_input_fn = input_fn_builder(
1211
+ input_file=train_writer.filename,
1212
+ seq_length=FLAGS.max_seq_length,
1213
+ is_training=True,
1214
+ drop_remainder=True)
1215
+ estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
1216
+
1217
+ if FLAGS.do_predict:
1218
+ eval_examples = read_squad_examples(
1219
+ input_file=FLAGS.predict_file, is_training=False)
1220
+
1221
+ eval_writer = FeatureWriter(
1222
+ filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
1223
+ is_training=False)
1224
+ eval_features = []
1225
+
1226
+ def append_feature(feature):
1227
+ eval_features.append(feature)
1228
+ eval_writer.process_feature(feature)
1229
+
1230
+ convert_examples_to_features(
1231
+ examples=eval_examples,
1232
+ tokenizer=tokenizer,
1233
+ max_seq_length=FLAGS.max_seq_length,
1234
+ doc_stride=FLAGS.doc_stride,
1235
+ max_query_length=FLAGS.max_query_length,
1236
+ is_training=False,
1237
+ output_fn=append_feature)
1238
+ eval_writer.close()
1239
+
1240
+ tf.logging.info("***** Running predictions *****")
1241
+ tf.logging.info(" Num orig examples = %d", len(eval_examples))
1242
+ tf.logging.info(" Num split examples = %d", len(eval_features))
1243
+ tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
1244
+
1245
+ all_results = []
1246
+
1247
+ predict_input_fn = input_fn_builder(
1248
+ input_file=eval_writer.filename,
1249
+ seq_length=FLAGS.max_seq_length,
1250
+ is_training=False,
1251
+ drop_remainder=False)
1252
+
1253
+ # If running eval on the TPU, you will need to specify the number of
1254
+ # steps.
1255
+ all_results = []
1256
+ for result in estimator.predict(
1257
+ predict_input_fn, yield_single_examples=True):
1258
+ if len(all_results) % 1000 == 0:
1259
+ tf.logging.info("Processing example: %d" % (len(all_results)))
1260
+ unique_id = int(result["unique_ids"])
1261
+ start_logits = [float(x) for x in result["start_logits"].flat]
1262
+ end_logits = [float(x) for x in result["end_logits"].flat]
1263
+ all_results.append(
1264
+ RawResult(
1265
+ unique_id=unique_id,
1266
+ start_logits=start_logits,
1267
+ end_logits=end_logits))
1268
+
1269
+ output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
1270
+ output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
1271
+ output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
1272
+
1273
+ write_predictions(eval_examples, eval_features, all_results,
1274
+ FLAGS.n_best_size, FLAGS.max_answer_length,
1275
+ FLAGS.do_lower_case, output_prediction_file,
1276
+ output_nbest_file, output_null_log_odds_file)
1277
+
1278
+
1279
+ if __name__ == "__main__":
1280
+ flags.mark_flag_as_required("vocab_file")
1281
+ flags.mark_flag_as_required("bert_config_file")
1282
+ flags.mark_flag_as_required("output_dir")
1283
+ tf.app.run()
bert-master/bert-master/sample_text.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This text is included to make sure Unicode is handled properly: 力加勝北区ᴵᴺᵀᵃছজটডণত
2
+ Text should be one-sentence-per-line, with empty lines between documents.
3
+ This sample text is public domain and was randomly selected from Project Guttenberg.
4
+
5
+ The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors.
6
+ Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity.
7
+ Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them.
8
+ "Cass" Beard had risen early that morning, but not with a view to discovery.
9
+ A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets.
10
+ The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency.
11
+ This was nearly opposite.
12
+ Mr. Cassius crossed the highway, and stopped suddenly.
13
+ Something glittered in the nearest red pool before him.
14
+ Gold, surely!
15
+ But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring.
16
+ Looking at it more attentively, he saw that it bore the inscription, "May to Cass."
17
+ Like most of his fellow gold-seekers, Cass was superstitious.
18
+
19
+ The fountain of classic wisdom, Hypatia herself.
20
+ As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge.
21
+ From my youth I felt in me a soul above the matter-entangled herd.
22
+ She revealed to me the glorious fact, that I am a spark of Divinity itself.
23
+ A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's.
24
+ There is a philosophic pleasure in opening one's treasures to the modest young.
25
+ Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street.
26
+ Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide;
27
+ but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind.
28
+ Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now.
29
+ His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert;
30
+ while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts.
31
+ At last they reached the quay at the opposite end of the street;
32
+ and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers.
33
+ He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him.
bert-master/bert-master/tokenization.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import collections
22
+ import re
23
+ import unicodedata
24
+ import six
25
+ import tensorflow as tf
26
+
27
+
28
+ def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
29
+ """Checks whether the casing config is consistent with the checkpoint name."""
30
+
31
+ # The casing has to be passed in by the user and there is no explicit check
32
+ # as to whether it matches the checkpoint. The casing information probably
33
+ # should have been stored in the bert_config.json file, but it's not, so
34
+ # we have to heuristically detect it to validate.
35
+
36
+ if not init_checkpoint:
37
+ return
38
+
39
+ m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint)
40
+ if m is None:
41
+ return
42
+
43
+ model_name = m.group(1)
44
+
45
+ lower_models = [
46
+ "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12",
47
+ "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12"
48
+ ]
49
+
50
+ cased_models = [
51
+ "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16",
52
+ "multi_cased_L-12_H-768_A-12"
53
+ ]
54
+
55
+ is_bad_config = False
56
+ if model_name in lower_models and not do_lower_case:
57
+ is_bad_config = True
58
+ actual_flag = "False"
59
+ case_name = "lowercased"
60
+ opposite_flag = "True"
61
+
62
+ if model_name in cased_models and do_lower_case:
63
+ is_bad_config = True
64
+ actual_flag = "True"
65
+ case_name = "cased"
66
+ opposite_flag = "False"
67
+
68
+ if is_bad_config:
69
+ raise ValueError(
70
+ "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. "
71
+ "However, `%s` seems to be a %s model, so you "
72
+ "should pass in `--do_lower_case=%s` so that the fine-tuning matches "
73
+ "how the model was pre-training. If this error is wrong, please "
74
+ "just comment out this check." % (actual_flag, init_checkpoint,
75
+ model_name, case_name, opposite_flag))
76
+
77
+
78
+ def convert_to_unicode(text):
79
+ """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
80
+ if six.PY3:
81
+ if isinstance(text, str):
82
+ return text
83
+ elif isinstance(text, bytes):
84
+ return text.decode("utf-8", "ignore")
85
+ else:
86
+ raise ValueError("Unsupported string type: %s" % (type(text)))
87
+ elif six.PY2:
88
+ if isinstance(text, str):
89
+ return text.decode("utf-8", "ignore")
90
+ elif isinstance(text, unicode):
91
+ return text
92
+ else:
93
+ raise ValueError("Unsupported string type: %s" % (type(text)))
94
+ else:
95
+ raise ValueError("Not running on Python2 or Python 3?")
96
+
97
+
98
+ def printable_text(text):
99
+ """Returns text encoded in a way suitable for print or `tf.logging`."""
100
+
101
+ # These functions want `str` for both Python2 and Python3, but in one case
102
+ # it's a Unicode string and in the other it's a byte string.
103
+ if six.PY3:
104
+ if isinstance(text, str):
105
+ return text
106
+ elif isinstance(text, bytes):
107
+ return text.decode("utf-8", "ignore")
108
+ else:
109
+ raise ValueError("Unsupported string type: %s" % (type(text)))
110
+ elif six.PY2:
111
+ if isinstance(text, str):
112
+ return text
113
+ elif isinstance(text, unicode):
114
+ return text.encode("utf-8")
115
+ else:
116
+ raise ValueError("Unsupported string type: %s" % (type(text)))
117
+ else:
118
+ raise ValueError("Not running on Python2 or Python 3?")
119
+
120
+
121
+ def load_vocab(vocab_file):
122
+ """Loads a vocabulary file into a dictionary."""
123
+ vocab = collections.OrderedDict()
124
+ index = 0
125
+ with tf.gfile.GFile(vocab_file, "r") as reader:
126
+ while True:
127
+ token = convert_to_unicode(reader.readline())
128
+ if not token:
129
+ break
130
+ token = token.strip()
131
+ vocab[token] = index
132
+ index += 1
133
+ return vocab
134
+
135
+
136
+ def convert_by_vocab(vocab, items):
137
+ """Converts a sequence of [tokens|ids] using the vocab."""
138
+ output = []
139
+ for item in items:
140
+ output.append(vocab[item])
141
+ return output
142
+
143
+
144
+ def convert_tokens_to_ids(vocab, tokens):
145
+ return convert_by_vocab(vocab, tokens)
146
+
147
+
148
+ def convert_ids_to_tokens(inv_vocab, ids):
149
+ return convert_by_vocab(inv_vocab, ids)
150
+
151
+
152
+ def whitespace_tokenize(text):
153
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
154
+ text = text.strip()
155
+ if not text:
156
+ return []
157
+ tokens = text.split()
158
+ return tokens
159
+
160
+
161
+ class FullTokenizer(object):
162
+ """Runs end-to-end tokenziation."""
163
+
164
+ def __init__(self, vocab_file, do_lower_case=True):
165
+ self.vocab = load_vocab(vocab_file)
166
+ self.inv_vocab = {v: k for k, v in self.vocab.items()}
167
+ self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
168
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
169
+
170
+ def tokenize(self, text):
171
+ split_tokens = []
172
+ for token in self.basic_tokenizer.tokenize(text):
173
+ for sub_token in self.wordpiece_tokenizer.tokenize(token):
174
+ split_tokens.append(sub_token)
175
+
176
+ return split_tokens
177
+
178
+ def convert_tokens_to_ids(self, tokens):
179
+ return convert_by_vocab(self.vocab, tokens)
180
+
181
+ def convert_ids_to_tokens(self, ids):
182
+ return convert_by_vocab(self.inv_vocab, ids)
183
+
184
+
185
+ class BasicTokenizer(object):
186
+ """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
187
+
188
+ def __init__(self, do_lower_case=True):
189
+ """Constructs a BasicTokenizer.
190
+
191
+ Args:
192
+ do_lower_case: Whether to lower case the input.
193
+ """
194
+ self.do_lower_case = do_lower_case
195
+
196
+ def tokenize(self, text):
197
+ """Tokenizes a piece of text."""
198
+ text = convert_to_unicode(text)
199
+ text = self._clean_text(text)
200
+
201
+ # This was added on November 1st, 2018 for the multilingual and Chinese
202
+ # models. This is also applied to the English models now, but it doesn't
203
+ # matter since the English models were not trained on any Chinese data
204
+ # and generally don't have any Chinese data in them (there are Chinese
205
+ # characters in the vocabulary because Wikipedia does have some Chinese
206
+ # words in the English Wikipedia.).
207
+ text = self._tokenize_chinese_chars(text)
208
+
209
+ orig_tokens = whitespace_tokenize(text)
210
+ split_tokens = []
211
+ for token in orig_tokens:
212
+ if self.do_lower_case:
213
+ token = token.lower()
214
+ token = self._run_strip_accents(token)
215
+ split_tokens.extend(self._run_split_on_punc(token))
216
+
217
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
218
+ return output_tokens
219
+
220
+ def _run_strip_accents(self, text):
221
+ """Strips accents from a piece of text."""
222
+ text = unicodedata.normalize("NFD", text)
223
+ output = []
224
+ for char in text:
225
+ cat = unicodedata.category(char)
226
+ if cat == "Mn":
227
+ continue
228
+ output.append(char)
229
+ return "".join(output)
230
+
231
+ def _run_split_on_punc(self, text):
232
+ """Splits punctuation on a piece of text."""
233
+ chars = list(text)
234
+ i = 0
235
+ start_new_word = True
236
+ output = []
237
+ while i < len(chars):
238
+ char = chars[i]
239
+ if _is_punctuation(char):
240
+ output.append([char])
241
+ start_new_word = True
242
+ else:
243
+ if start_new_word:
244
+ output.append([])
245
+ start_new_word = False
246
+ output[-1].append(char)
247
+ i += 1
248
+
249
+ return ["".join(x) for x in output]
250
+
251
+ def _tokenize_chinese_chars(self, text):
252
+ """Adds whitespace around any CJK character."""
253
+ output = []
254
+ for char in text:
255
+ cp = ord(char)
256
+ if self._is_chinese_char(cp):
257
+ output.append(" ")
258
+ output.append(char)
259
+ output.append(" ")
260
+ else:
261
+ output.append(char)
262
+ return "".join(output)
263
+
264
+ def _is_chinese_char(self, cp):
265
+ """Checks whether CP is the codepoint of a CJK character."""
266
+ # This defines a "chinese character" as anything in the CJK Unicode block:
267
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
268
+ #
269
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
270
+ # despite its name. The modern Korean Hangul alphabet is a different block,
271
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
272
+ # space-separated words, so they are not treated specially and handled
273
+ # like the all of the other languages.
274
+ if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
275
+ (cp >= 0x3400 and cp <= 0x4DBF) or #
276
+ (cp >= 0x20000 and cp <= 0x2A6DF) or #
277
+ (cp >= 0x2A700 and cp <= 0x2B73F) or #
278
+ (cp >= 0x2B740 and cp <= 0x2B81F) or #
279
+ (cp >= 0x2B820 and cp <= 0x2CEAF) or
280
+ (cp >= 0xF900 and cp <= 0xFAFF) or #
281
+ (cp >= 0x2F800 and cp <= 0x2FA1F)): #
282
+ return True
283
+
284
+ return False
285
+
286
+ def _clean_text(self, text):
287
+ """Performs invalid character removal and whitespace cleanup on text."""
288
+ output = []
289
+ for char in text:
290
+ cp = ord(char)
291
+ if cp == 0 or cp == 0xfffd or _is_control(char):
292
+ continue
293
+ if _is_whitespace(char):
294
+ output.append(" ")
295
+ else:
296
+ output.append(char)
297
+ return "".join(output)
298
+
299
+
300
+ class WordpieceTokenizer(object):
301
+ """Runs WordPiece tokenziation."""
302
+
303
+ def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
304
+ self.vocab = vocab
305
+ self.unk_token = unk_token
306
+ self.max_input_chars_per_word = max_input_chars_per_word
307
+
308
+ def tokenize(self, text):
309
+ """Tokenizes a piece of text into its word pieces.
310
+
311
+ This uses a greedy longest-match-first algorithm to perform tokenization
312
+ using the given vocabulary.
313
+
314
+ For example:
315
+ input = "unaffable"
316
+ output = ["un", "##aff", "##able"]
317
+
318
+ Args:
319
+ text: A single token or whitespace separated tokens. This should have
320
+ already been passed through `BasicTokenizer.
321
+
322
+ Returns:
323
+ A list of wordpiece tokens.
324
+ """
325
+
326
+ text = convert_to_unicode(text)
327
+
328
+ output_tokens = []
329
+ for token in whitespace_tokenize(text):
330
+ chars = list(token)
331
+ if len(chars) > self.max_input_chars_per_word:
332
+ output_tokens.append(self.unk_token)
333
+ continue
334
+
335
+ is_bad = False
336
+ start = 0
337
+ sub_tokens = []
338
+ while start < len(chars):
339
+ end = len(chars)
340
+ cur_substr = None
341
+ while start < end:
342
+ substr = "".join(chars[start:end])
343
+ if start > 0:
344
+ substr = "##" + substr
345
+ if substr in self.vocab:
346
+ cur_substr = substr
347
+ break
348
+ end -= 1
349
+ if cur_substr is None:
350
+ is_bad = True
351
+ break
352
+ sub_tokens.append(cur_substr)
353
+ start = end
354
+
355
+ if is_bad:
356
+ output_tokens.append(self.unk_token)
357
+ else:
358
+ output_tokens.extend(sub_tokens)
359
+ return output_tokens
360
+
361
+
362
+ def _is_whitespace(char):
363
+ """Checks whether `chars` is a whitespace character."""
364
+ # \t, \n, and \r are technically contorl characters but we treat them
365
+ # as whitespace since they are generally considered as such.
366
+ if char == " " or char == "\t" or char == "\n" or char == "\r":
367
+ return True
368
+ cat = unicodedata.category(char)
369
+ if cat == "Zs":
370
+ return True
371
+ return False
372
+
373
+
374
+ def _is_control(char):
375
+ """Checks whether `chars` is a control character."""
376
+ # These are technically control characters but we count them as whitespace
377
+ # characters.
378
+ if char == "\t" or char == "\n" or char == "\r":
379
+ return False
380
+ cat = unicodedata.category(char)
381
+ if cat in ("Cc", "Cf"):
382
+ return True
383
+ return False
384
+
385
+
386
+ def _is_punctuation(char):
387
+ """Checks whether `chars` is a punctuation character."""
388
+ cp = ord(char)
389
+ # We treat all non-letter/number ASCII as punctuation.
390
+ # Characters such as "^", "$", and "`" are not in the Unicode
391
+ # Punctuation class but we treat them as punctuation anyways, for
392
+ # consistency.
393
+ if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
394
+ (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
395
+ return True
396
+ cat = unicodedata.category(char)
397
+ if cat.startswith("P"):
398
+ return True
399
+ return False
bert-master/bert-master/tokenization_test.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import tempfile
21
+ import tokenization
22
+ import six
23
+ import tensorflow as tf
24
+
25
+
26
+ class TokenizationTest(tf.test.TestCase):
27
+
28
+ def test_full_tokenizer(self):
29
+ vocab_tokens = [
30
+ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
31
+ "##ing", ","
32
+ ]
33
+ with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
34
+ if six.PY2:
35
+ vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
36
+ else:
37
+ vocab_writer.write("".join(
38
+ [x + "\n" for x in vocab_tokens]).encode("utf-8"))
39
+
40
+ vocab_file = vocab_writer.name
41
+
42
+ tokenizer = tokenization.FullTokenizer(vocab_file)
43
+ os.unlink(vocab_file)
44
+
45
+ tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
46
+ self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
47
+
48
+ self.assertAllEqual(
49
+ tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
50
+
51
+ def test_chinese(self):
52
+ tokenizer = tokenization.BasicTokenizer()
53
+
54
+ self.assertAllEqual(
55
+ tokenizer.tokenize(u"ah\u535A\u63A8zz"),
56
+ [u"ah", u"\u535A", u"\u63A8", u"zz"])
57
+
58
+ def test_basic_tokenizer_lower(self):
59
+ tokenizer = tokenization.BasicTokenizer(do_lower_case=True)
60
+
61
+ self.assertAllEqual(
62
+ tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
63
+ ["hello", "!", "how", "are", "you", "?"])
64
+ self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"])
65
+
66
+ def test_basic_tokenizer_no_lower(self):
67
+ tokenizer = tokenization.BasicTokenizer(do_lower_case=False)
68
+
69
+ self.assertAllEqual(
70
+ tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
71
+ ["HeLLo", "!", "how", "Are", "yoU", "?"])
72
+
73
+ def test_wordpiece_tokenizer(self):
74
+ vocab_tokens = [
75
+ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
76
+ "##ing"
77
+ ]
78
+
79
+ vocab = {}
80
+ for (i, token) in enumerate(vocab_tokens):
81
+ vocab[token] = i
82
+ tokenizer = tokenization.WordpieceTokenizer(vocab=vocab)
83
+
84
+ self.assertAllEqual(tokenizer.tokenize(""), [])
85
+
86
+ self.assertAllEqual(
87
+ tokenizer.tokenize("unwanted running"),
88
+ ["un", "##want", "##ed", "runn", "##ing"])
89
+
90
+ self.assertAllEqual(
91
+ tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
92
+
93
+ def test_convert_tokens_to_ids(self):
94
+ vocab_tokens = [
95
+ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
96
+ "##ing"
97
+ ]
98
+
99
+ vocab = {}
100
+ for (i, token) in enumerate(vocab_tokens):
101
+ vocab[token] = i
102
+
103
+ self.assertAllEqual(
104
+ tokenization.convert_tokens_to_ids(
105
+ vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9])
106
+
107
+ def test_is_whitespace(self):
108
+ self.assertTrue(tokenization._is_whitespace(u" "))
109
+ self.assertTrue(tokenization._is_whitespace(u"\t"))
110
+ self.assertTrue(tokenization._is_whitespace(u"\r"))
111
+ self.assertTrue(tokenization._is_whitespace(u"\n"))
112
+ self.assertTrue(tokenization._is_whitespace(u"\u00A0"))
113
+
114
+ self.assertFalse(tokenization._is_whitespace(u"A"))
115
+ self.assertFalse(tokenization._is_whitespace(u"-"))
116
+
117
+ def test_is_control(self):
118
+ self.assertTrue(tokenization._is_control(u"\u0005"))
119
+
120
+ self.assertFalse(tokenization._is_control(u"A"))
121
+ self.assertFalse(tokenization._is_control(u" "))
122
+ self.assertFalse(tokenization._is_control(u"\t"))
123
+ self.assertFalse(tokenization._is_control(u"\r"))
124
+ self.assertFalse(tokenization._is_control(u"\U0001F4A9"))
125
+
126
+ def test_is_punctuation(self):
127
+ self.assertTrue(tokenization._is_punctuation(u"-"))
128
+ self.assertTrue(tokenization._is_punctuation(u"$"))
129
+ self.assertTrue(tokenization._is_punctuation(u"`"))
130
+ self.assertTrue(tokenization._is_punctuation(u"."))
131
+
132
+ self.assertFalse(tokenization._is_punctuation(u"A"))
133
+ self.assertFalse(tokenization._is_punctuation(u" "))
134
+
135
+
136
+ if __name__ == "__main__":
137
+ tf.test.main()
dark-bert-master/dark-bert-master/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
dark-bert-master/dark-bert-master/README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dark-bert
2
+ 🧠 Using large language models to classify dark net documents in a zero-shot learning enviornments.
3
+
4
+ Dark bert eneables you to cluster any corpus of markup documents in an entirely unsupervised way.
5
+
6
+ ```
7
+ usage: darkbert.py [-h] -m {bert,albert,roberta} -i INPUT -o OUTPUT
8
+
9
+ optional arguments:
10
+ -h, --help show this help message and exit
11
+ -m {bert,albert,roberta}, --model {bert,albert,roberta}
12
+ -i INPUT, --input INPUT
13
+ -o OUTPUT, --output OUTPUT
14
+ ```
dark-bert-master/dark-bert-master/darkbert.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Christopher K. Schmitt
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from sentence_transformers import SentenceTransformer
16
+ from sklearn.manifold import TSNE
17
+ from sklearn.cluster import DBSCAN
18
+ from sklearn.metrics import silhouette_score, calinski_harabasz_score
19
+ from pathlib import Path
20
+ from bs4 import BeautifulSoup
21
+ from argparse import ArgumentParser
22
+
23
+ import matplotlib.pyplot as plt
24
+ import numpy as np
25
+ import nltk as nltk
26
+
27
+ # The list of huggingface transformers with tensorflow
28
+ # support and compatible tokenizers.
29
+ available_models = {
30
+ "bert": "sentence-transformers/multi-qa-distilbert-cos-v1",
31
+ "albert": "sentence-transformers/paraphrase-albert-small-v2",
32
+ "roberta": "sentence-transformers/all-distilroberta-v1",
33
+ }
34
+
35
+ display_titles = {
36
+ "bert": "BERT",
37
+ "albert": "ALBERT",
38
+ "roberta": "RoBERTa",
39
+ }
40
+
41
+ # Define the CLI interface for modeling our data with
42
+ # different transformer models. We want to control the
43
+ # type of the tokenizer and the transformer we use, as well
44
+ # as the input and output directories
45
+ parser = ArgumentParser()
46
+ parser.add_argument("-m", "--model", choices=available_models.keys(), required=True)
47
+ parser.add_argument("-i", "--input", required=True)
48
+ parser.add_argument("-o", "--output", required=True)
49
+
50
+ args = parser.parse_args()
51
+ input_dir = args.input
52
+ output_dir = args.output
53
+ model_name = available_models[args.model]
54
+ display_name = display_titles[args.model]
55
+
56
+ # To remove random glyphs and other noise, we
57
+ # only extract words in the nltk corpus
58
+ nltk.download("words")
59
+ words = set(nltk.corpus.words.words())
60
+
61
+ def extract_words(document):
62
+ cleaned = ""
63
+
64
+ for word in nltk.wordpunct_tokenize(document):
65
+ if word.lower() in words:
66
+ cleaned += word.lower() + " "
67
+
68
+ return cleaned
69
+
70
+ # Iterate over all of the files in the provided data
71
+ # directory. Parse each file with beautiful soup to parse
72
+ # the relevant text out of the markup.
73
+ data = Path(input_dir).iterdir()
74
+ data = map(lambda doc: doc.read_bytes(), data)
75
+ data = map(lambda doc: BeautifulSoup(doc, "html.parser"), data)
76
+ data = map(lambda doc: doc.get_text(), data)
77
+ data = filter(lambda doc: len(doc) > 0, data)
78
+ data = map(extract_words, data)
79
+ data = filter(lambda doc: len(doc) > 10, data)
80
+ data = list(data)
81
+
82
+ # Initilize transformer models and predict all of the
83
+ # document embeddings as computed by bert and friends
84
+ model = SentenceTransformer(model_name)
85
+ embeddings = model.encode(data, show_progress_bar=True)
86
+
87
+ # Fit TSNE model for embedding space. Sqush down to 2
88
+ # dimentions for visualization purposes.
89
+ tsne = TSNE(n_components=2, random_state=2, init="pca", learning_rate="auto", perplexity=40)
90
+ tsne = tsne.fit_transform(embeddings)
91
+
92
+ # Hyperparameter optimizations
93
+ silhouettes = []
94
+ outliers = []
95
+ ch = []
96
+
97
+ for eps in np.arange(0.001, 1, 0.001):
98
+ dbscan = DBSCAN(eps, metric="cosine", n_jobs=-1)
99
+ dbscan = dbscan.fit_predict(embeddings)
100
+
101
+ if len(np.unique(dbscan)) > 1:
102
+ silhouettes.append(silhouette_score(embeddings, dbscan, metric="cosine"))
103
+ ch.append(calinski_harabasz_score(embeddings, dbscan))
104
+ else:
105
+ silhouettes.append(0)
106
+ ch.append(0)
107
+
108
+ outliers.append(len(dbscan[dbscan == -1]))
109
+
110
+ for p in range(15, 51):
111
+ best = np.argmax(silhouettes)
112
+
113
+ dbscan = DBSCAN(0.001 + 0.001 * best, metric="cosine", n_jobs=-1)
114
+ dbscan = dbscan.fit_predict(embeddings)
115
+
116
+ tsne = TSNE(n_components=2, perplexity=p, learning_rate="auto", init="pca", metric="cosine")
117
+ tsne = tsne.fit_transform(embeddings)
118
+
119
+ plt.figure()
120
+ plt.scatter(tsne[dbscan != -1][:, 0], tsne[dbscan != -1][:, 1], s=0.5, c=dbscan[dbscan != -1], cmap="hsv")
121
+ plt.scatter(tsne[dbscan == -1][:, 0], tsne[dbscan == -1][:, 1], s=0.5, c="#abb8c3")
122
+ plt.title(f"{display_name} Embeddings Visualized with T-SNE (p = {p})")
123
+ plt.savefig(f"{output_dir}/tnse_{p:02}.png", format="png", dpi=600)
124
+ plt.close()
125
+
126
+ plt.figure()
127
+ plt.plot(np.arange(0.001, 1, 0.001), silhouettes, lw=0.5, color="#dc322f")
128
+ plt.legend()
129
+ plt.xlabel("Epsilon")
130
+ plt.ylabel("silhouette score")
131
+ plt.title("Optimizing Epsilon by Silhouette Score")
132
+ plt.savefig(f"silhouettes.png", format="png", dpi=600)
133
+ plt.close()
134
+
135
+ plt.figure()
136
+ plt.plot(np.arange(0.001, 1, 0.001), outliers, lw=0.5, color="#dc322f")
137
+ plt.legend()
138
+ plt.xlabel("Epsilon")
139
+ plt.ylabel("outliers")
140
+ plt.title("Optimizing Epsilon by Number of Outliers")
141
+ plt.savefig(f"outliers.png", format="png", dpi=600)
142
+ plt.close()
143
+
144
+ plt.figure()
145
+ plt.plot(np.arange(0.001, 1, 0.001), ch, lw=0.5, color="#dc322f")
146
+ plt.legend()
147
+ plt.xlabel("Epsilon")
148
+ plt.ylabel("Calinski-Harabasz score")
149
+ plt.title("Optimizing Epsilon by Calinski-Harabasz Score")
150
+ plt.savefig(f"calinski-harabasz.png", format="png", dpi=600)
151
+ plt.close()
dark-bert-master/dark-bert-master/requirements.txt ADDED
Binary file (1.54 kB). View file
 
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master.gitignore ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initially taken from Github's Python gitignore file
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+
62
+ # Flask stuff:
63
+ instance/
64
+ .webassets-cache
65
+
66
+ # Scrapy stuff:
67
+ .scrapy
68
+
69
+ # Sphinx documentation
70
+ docs/_build/
71
+
72
+ # PyBuilder
73
+ target/
74
+
75
+ # Jupyter Notebook
76
+ .ipynb_checkpoints
77
+
78
+ # IPython
79
+ profile_default/
80
+ ipython_config.py
81
+
82
+ # pyenv
83
+ .python-version
84
+
85
+ # celery beat schedule file
86
+ celerybeat-schedule
87
+
88
+ # SageMath parsed files
89
+ *.sage.py
90
+
91
+ # Environments
92
+ .env
93
+ .venv
94
+ env/
95
+ venv/
96
+ ENV/
97
+ env.bak/
98
+ venv.bak/
99
+
100
+ # Spyder project settings
101
+ .spyderproject
102
+ .spyproject
103
+
104
+ # Rope project settings
105
+ .ropeproject
106
+
107
+ # mkdocs documentation
108
+ /site
109
+
110
+ # mypy
111
+ .mypy_cache/
112
+ .dmypy.json
113
+ dmypy.json
114
+
115
+ # Pyre type checker
116
+ .pyre/
117
+
118
+ # vscode
119
+ .vscode
120
+
121
+ # TF code
122
+ tensorflow_code
123
+
124
+ # Models
125
+ models
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/.circleci/config.yml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ jobs:
3
+ build_py3:
4
+ working_directory: ~/pytorch-pretrained-BERT
5
+ docker:
6
+ - image: circleci/python:3.5
7
+ steps:
8
+ - checkout
9
+ - run: sudo pip install --progress-bar off .
10
+ - run: sudo pip install pytest ftfy spacy
11
+ - run: sudo python -m spacy download en
12
+ - run: python -m pytest -sv tests/ --runslow
13
+ build_py2:
14
+ working_directory: ~/pytorch-pretrained-BERT
15
+ docker:
16
+ - image: circleci/python:2.7
17
+ steps:
18
+ - checkout
19
+ - run: sudo pip install --progress-bar off .
20
+ - run: sudo pip install pytest spacy
21
+ - run: sudo pip install ftfy==4.4.3
22
+ - run: sudo python -m spacy download en
23
+ - run: python -m pytest -sv tests/ --runslow
24
+ workflows:
25
+ version: 2
26
+ build_and_test:
27
+ jobs:
28
+ - build_py3
29
+ - build_py2
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/.github/stale.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Number of days of inactivity before an issue becomes stale
2
+ daysUntilStale: 60
3
+ # Number of days of inactivity before a stale issue is closed
4
+ daysUntilClose: 7
5
+ # Issues with these labels will never be considered stale
6
+ exemptLabels:
7
+ - pinned
8
+ - security
9
+ # Label to use when marking an issue as stale
10
+ staleLabel: wontfix
11
+ # Comment to post when marking an issue as stale. Set to `false` to disable
12
+ markComment: >
13
+ This issue has been automatically marked as stale because it has not had
14
+ recent activity. It will be closed if no further activity occurs. Thank you
15
+ for your contributions.
16
+ # Comment to post when closing a stale issue. Set to `false` to disable
17
+ closeComment: false
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ include LICENSE
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/README.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+ For installation and docs please refer to [release 0.6 of pytorch_pretrained_bert](https://github.com/huggingface/transformers/releases).
3
+
4
+ The current fork adds the jupyter notebook on the attention analysis of the 12 layer BERT model. For details please refer to [the paper](https://arxiv.org/abs/1908.08593).
5
+
6
+ Note that for the extraction of attention weights the source code of [](./pytorch_pretrained_bert/modeling.py) was modified (this functionality was added in later realeases of the forked repo).
7
+
8
+ # Requirements and usage
9
+ 1. Install the requirements as
10
+ ```
11
+ pip install -r requirements.txt
12
+ ```
13
+
14
+ 2. The current implementation assumes you have GLUE datasets downloaded and fine-tuned BERT model weights saved to a directory of your choice. You can download GLUE data as described [here](https://github.com/nyu-mll/GLUE-baselines/blob/master/download_glue_data.py). To fine-tune BERT, run [](./examples/run_classifier.py).
15
+
16
+ 3. The code for analysis is contained in [the jupyter notebook](./visualize_attention.ipynb).
17
+
18
+ 4. To repeat the results of experiments, make sure to change the `path_to_model` and `path_to_data` in the notebook.
19
+
20
+
21
+ # References
22
+ ```
23
+ @article{kovaleva2019revealing,
24
+ title={Revealing the Dark Secrets of BERT},
25
+ author={Kovaleva, Olga and Romanov, Alexey and Rogers, Anna and Rumshisky, Anna},
26
+ journal={arXiv preprint arXiv:1908.08593},
27
+ year={2019}
28
+ }
29
+ ```
30
+
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docker/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:latest
2
+
3
+ RUN git clone https://github.com/NVIDIA/apex.git && cd apex && python setup.py install --cuda_ext --cpp_ext
4
+
5
+ RUN pip install pytorch-pretrained-bert
6
+
7
+ WORKDIR /workspace
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_constant_schedule.png ADDED
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_hard_restarts_schedule.png ADDED
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_schedule.png ADDED
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_cosine_warm_restarts_schedule.png ADDED
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/docs/imgs/warmup_linear_schedule.png ADDED
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/extract_features.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Extract pre-computed feature vectors from a PyTorch BERT model."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import argparse
22
+ import collections
23
+ import logging
24
+ import json
25
+ import re
26
+
27
+ import torch
28
+ from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
29
+ from torch.utils.data.distributed import DistributedSampler
30
+
31
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
32
+ from pytorch_pretrained_bert.modeling import BertModel
33
+
34
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
35
+ datefmt = '%m/%d/%Y %H:%M:%S',
36
+ level = logging.INFO)
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ class InputExample(object):
41
+
42
+ def __init__(self, unique_id, text_a, text_b):
43
+ self.unique_id = unique_id
44
+ self.text_a = text_a
45
+ self.text_b = text_b
46
+
47
+
48
+ class InputFeatures(object):
49
+ """A single set of features of data."""
50
+
51
+ def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
52
+ self.unique_id = unique_id
53
+ self.tokens = tokens
54
+ self.input_ids = input_ids
55
+ self.input_mask = input_mask
56
+ self.input_type_ids = input_type_ids
57
+
58
+
59
+ def convert_examples_to_features(examples, seq_length, tokenizer):
60
+ """Loads a data file into a list of `InputFeature`s."""
61
+
62
+ features = []
63
+ for (ex_index, example) in enumerate(examples):
64
+ tokens_a = tokenizer.tokenize(example.text_a)
65
+
66
+ tokens_b = None
67
+ if example.text_b:
68
+ tokens_b = tokenizer.tokenize(example.text_b)
69
+
70
+ if tokens_b:
71
+ # Modifies `tokens_a` and `tokens_b` in place so that the total
72
+ # length is less than the specified length.
73
+ # Account for [CLS], [SEP], [SEP] with "- 3"
74
+ _truncate_seq_pair(tokens_a, tokens_b, seq_length - 3)
75
+ else:
76
+ # Account for [CLS] and [SEP] with "- 2"
77
+ if len(tokens_a) > seq_length - 2:
78
+ tokens_a = tokens_a[0:(seq_length - 2)]
79
+
80
+ # The convention in BERT is:
81
+ # (a) For sequence pairs:
82
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
83
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
84
+ # (b) For single sequences:
85
+ # tokens: [CLS] the dog is hairy . [SEP]
86
+ # type_ids: 0 0 0 0 0 0 0
87
+ #
88
+ # Where "type_ids" are used to indicate whether this is the first
89
+ # sequence or the second sequence. The embedding vectors for `type=0` and
90
+ # `type=1` were learned during pre-training and are added to the wordpiece
91
+ # embedding vector (and position vector). This is not *strictly* necessary
92
+ # since the [SEP] token unambigiously separates the sequences, but it makes
93
+ # it easier for the model to learn the concept of sequences.
94
+ #
95
+ # For classification tasks, the first vector (corresponding to [CLS]) is
96
+ # used as as the "sentence vector". Note that this only makes sense because
97
+ # the entire model is fine-tuned.
98
+ tokens = []
99
+ input_type_ids = []
100
+ tokens.append("[CLS]")
101
+ input_type_ids.append(0)
102
+ for token in tokens_a:
103
+ tokens.append(token)
104
+ input_type_ids.append(0)
105
+ tokens.append("[SEP]")
106
+ input_type_ids.append(0)
107
+
108
+ if tokens_b:
109
+ for token in tokens_b:
110
+ tokens.append(token)
111
+ input_type_ids.append(1)
112
+ tokens.append("[SEP]")
113
+ input_type_ids.append(1)
114
+
115
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
116
+
117
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
118
+ # tokens are attended to.
119
+ input_mask = [1] * len(input_ids)
120
+
121
+ # Zero-pad up to the sequence length.
122
+ while len(input_ids) < seq_length:
123
+ input_ids.append(0)
124
+ input_mask.append(0)
125
+ input_type_ids.append(0)
126
+
127
+ assert len(input_ids) == seq_length
128
+ assert len(input_mask) == seq_length
129
+ assert len(input_type_ids) == seq_length
130
+
131
+ if ex_index < 5:
132
+ logger.info("*** Example ***")
133
+ logger.info("unique_id: %s" % (example.unique_id))
134
+ logger.info("tokens: %s" % " ".join([str(x) for x in tokens]))
135
+ logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
136
+ logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
137
+ logger.info(
138
+ "input_type_ids: %s" % " ".join([str(x) for x in input_type_ids]))
139
+
140
+ features.append(
141
+ InputFeatures(
142
+ unique_id=example.unique_id,
143
+ tokens=tokens,
144
+ input_ids=input_ids,
145
+ input_mask=input_mask,
146
+ input_type_ids=input_type_ids))
147
+ return features
148
+
149
+
150
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
151
+ """Truncates a sequence pair in place to the maximum length."""
152
+
153
+ # This is a simple heuristic which will always truncate the longer sequence
154
+ # one token at a time. This makes more sense than truncating an equal percent
155
+ # of tokens from each, since if one sequence is very short then each token
156
+ # that's truncated likely contains more information than a longer sequence.
157
+ while True:
158
+ total_length = len(tokens_a) + len(tokens_b)
159
+ if total_length <= max_length:
160
+ break
161
+ if len(tokens_a) > len(tokens_b):
162
+ tokens_a.pop()
163
+ else:
164
+ tokens_b.pop()
165
+
166
+
167
+ def read_examples(input_file):
168
+ """Read a list of `InputExample`s from an input file."""
169
+ examples = []
170
+ unique_id = 0
171
+ with open(input_file, "r", encoding='utf-8') as reader:
172
+ while True:
173
+ line = reader.readline()
174
+ if not line:
175
+ break
176
+ line = line.strip()
177
+ text_a = None
178
+ text_b = None
179
+ m = re.match(r"^(.*) \|\|\| (.*)$", line)
180
+ if m is None:
181
+ text_a = line
182
+ else:
183
+ text_a = m.group(1)
184
+ text_b = m.group(2)
185
+ examples.append(
186
+ InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
187
+ unique_id += 1
188
+ return examples
189
+
190
+
191
+ def main():
192
+ parser = argparse.ArgumentParser()
193
+
194
+ ## Required parameters
195
+ parser.add_argument("--input_file", default=None, type=str, required=True)
196
+ parser.add_argument("--output_file", default=None, type=str, required=True)
197
+ parser.add_argument("--bert_model", default=None, type=str, required=True,
198
+ help="Bert pre-trained model selected in the list: bert-base-uncased, "
199
+ "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.")
200
+
201
+ ## Other parameters
202
+ parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.")
203
+ parser.add_argument("--layers", default="-1,-2,-3,-4", type=str)
204
+ parser.add_argument("--max_seq_length", default=128, type=int,
205
+ help="The maximum total input sequence length after WordPiece tokenization. Sequences longer "
206
+ "than this will be truncated, and sequences shorter than this will be padded.")
207
+ parser.add_argument("--batch_size", default=32, type=int, help="Batch size for predictions.")
208
+ parser.add_argument("--local_rank",
209
+ type=int,
210
+ default=-1,
211
+ help = "local_rank for distributed training on gpus")
212
+ parser.add_argument("--no_cuda",
213
+ action='store_true',
214
+ help="Whether not to use CUDA when available")
215
+
216
+ args = parser.parse_args()
217
+
218
+ if args.local_rank == -1 or args.no_cuda:
219
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
220
+ n_gpu = torch.cuda.device_count()
221
+ else:
222
+ device = torch.device("cuda", args.local_rank)
223
+ n_gpu = 1
224
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
225
+ torch.distributed.init_process_group(backend='nccl')
226
+ logger.info("device: {} n_gpu: {} distributed training: {}".format(device, n_gpu, bool(args.local_rank != -1)))
227
+
228
+ layer_indexes = [int(x) for x in args.layers.split(",")]
229
+
230
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
231
+
232
+ examples = read_examples(args.input_file)
233
+
234
+ features = convert_examples_to_features(
235
+ examples=examples, seq_length=args.max_seq_length, tokenizer=tokenizer)
236
+
237
+ unique_id_to_feature = {}
238
+ for feature in features:
239
+ unique_id_to_feature[feature.unique_id] = feature
240
+
241
+ model = BertModel.from_pretrained(args.bert_model)
242
+ model.to(device)
243
+
244
+ if args.local_rank != -1:
245
+ model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
246
+ output_device=args.local_rank)
247
+ elif n_gpu > 1:
248
+ model = torch.nn.DataParallel(model)
249
+
250
+ all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
251
+ all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
252
+ all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
253
+
254
+ eval_data = TensorDataset(all_input_ids, all_input_mask, all_example_index)
255
+ if args.local_rank == -1:
256
+ eval_sampler = SequentialSampler(eval_data)
257
+ else:
258
+ eval_sampler = DistributedSampler(eval_data)
259
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.batch_size)
260
+
261
+ model.eval()
262
+ with open(args.output_file, "w", encoding='utf-8') as writer:
263
+ for input_ids, input_mask, example_indices in eval_dataloader:
264
+ input_ids = input_ids.to(device)
265
+ input_mask = input_mask.to(device)
266
+
267
+ all_encoder_layers, _ = model(input_ids, token_type_ids=None, attention_mask=input_mask)
268
+ all_encoder_layers = all_encoder_layers
269
+
270
+ for b, example_index in enumerate(example_indices):
271
+ feature = features[example_index.item()]
272
+ unique_id = int(feature.unique_id)
273
+ # feature = unique_id_to_feature[unique_id]
274
+ output_json = collections.OrderedDict()
275
+ output_json["linex_index"] = unique_id
276
+ all_out_features = []
277
+ for (i, token) in enumerate(feature.tokens):
278
+ all_layers = []
279
+ for (j, layer_index) in enumerate(layer_indexes):
280
+ layer_output = all_encoder_layers[int(layer_index)].detach().cpu().numpy()
281
+ layer_output = layer_output[b]
282
+ layers = collections.OrderedDict()
283
+ layers["index"] = layer_index
284
+ layers["values"] = [
285
+ round(x.item(), 6) for x in layer_output[i]
286
+ ]
287
+ all_layers.append(layers)
288
+ out_features = collections.OrderedDict()
289
+ out_features["token"] = token
290
+ out_features["layers"] = all_layers
291
+ all_out_features.append(out_features)
292
+ output_json["features"] = all_out_features
293
+ writer.write(json.dumps(output_json) + "\n")
294
+
295
+
296
+ if __name__ == "__main__":
297
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BERT Model Finetuning using Masked Language Modeling objective
2
+
3
+ ## Introduction
4
+
5
+ The three example scripts in this folder can be used to **fine-tune** a pre-trained BERT model using the pretraining objective (combination of masked language modeling and next sentence prediction loss). In general, pretrained models like BERT are first trained with a pretraining objective (masked language modeling and next sentence prediction for BERT) on a large and general natural language corpus. A classifier head is then added on top of the pre-trained architecture and the model is quickly fine-tuned on a target task, while still (hopefully) retaining its general language understanding. This greatly reduces overfitting and yields state-of-the-art results, especially when training data for the target task are limited.
6
+
7
+ The [ULMFiT paper](https://arxiv.org/abs/1801.06146) took a slightly different approach, however, and added an intermediate step in which the model is fine-tuned on text **from the same domain as the target task and using the pretraining objective** before the final stage in which the classifier head is added and the model is trained on the target task itself. This paper reported significantly improved results from this step, and found that they could get high-quality classifications even with only tiny numbers (<1000) of labelled training examples, as long as they had a lot of unlabelled data from the target domain.
8
+
9
+ The BERT model has more capacity than the LSTM models used in the ULMFiT work, but the [BERT paper](https://arxiv.org/abs/1810.04805) did not test finetuning using the pretraining objective and at the present stage there aren't many examples of this approach being used for Transformer-based language models. As such, it's hard to predict what effect this step will have on final model performance, but it's reasonable to conjecture that this approach can improve the final classification performance, especially when a large unlabelled corpus from the target domain is available, labelled data is limited, or the target domain is very unusual and different from 'normal' English text. If you are aware of any literature on this subject, please feel free to add it in here, or open an issue and tag me (@Rocketknight1) and I'll include it.
10
+
11
+ ## Input format
12
+
13
+ The scripts in this folder expect a single file as input, consisting of untokenized text, with one **sentence** per line, and one blank line between documents. The reason for the sentence splitting is that part of BERT's training involves a _next sentence_ objective in which the model must predict whether two sequences of text are contiguous text from the same document or not, and to avoid making the task _too easy_, the split point between the sequences is always at the end of a sentence. The linebreaks in the file are therefore necessary to mark the points where the text can be split.
14
+
15
+ ## Usage
16
+
17
+ There are two ways to fine-tune a language model using these scripts. The first _quick_ approach is to use [`simple_lm_finetuning.py`](./simple_lm_finetuning.py). This script does everything in a single script, but generates training instances that consist of just two sentences. This is quite different from the BERT paper, where (confusingly) the NextSentence task concatenated sentences together from each document to form two long multi-sentences, which the paper just referred to as _sentences_. The difference between this simple approach and the original paper approach can have a significant effect for long sequences since two sentences will be much shorter than the max sequence length. In this case, most of each training example will just consist of blank padding characters, which wastes a lot of computation and results in a model that isn't really training on long sequences.
18
+
19
+ As such, the preferred approach (assuming you have documents containing multiple contiguous sentences from your target domain) is to use [`pregenerate_training_data.py`](./pregenerate_training_data.py) to pre-process your data into training examples following the methodology used for LM training in the original BERT paper and repository. Since there is a significant random component to training data generation for BERT, this script includes an option to generate multiple _epochs_ of pre-processed data, to avoid training on the same random splits each epoch. Generating an epoch of data for each training epoch should result a better final model, and so we recommend doing so.
20
+
21
+ You can then train on the pregenerated data using [`finetune_on_pregenerated.py`](./finetune_on_pregenerated.py), and pointing it to the folder created by [`pregenerate_training_data.py`](./pregenerate_training_data.py). Note that you should use the same `bert_model` and case options for both! Also note that `max_seq_len` does not need to be specified for the [`finetune_on_pregenerated.py`](./finetune_on_pregenerated.py) script, as it is inferred from the training examples.
22
+
23
+ There are various options that can be tweaked, but they are mostly set to the values from the BERT paper/repository and default values should make sense. The most relevant ones are:
24
+
25
+ - `--max_seq_len`: Controls the length of training examples (in wordpiece tokens) seen by the model. Defaults to 128 but can be set as high as 512. Higher values may yield stronger language models at the cost of slower and more memory-intensive training.
26
+ - `--fp16`: Enables fast half-precision training on recent GPUs.
27
+
28
+ In addition, if memory usage is an issue, especially when training on a single GPU, reducing `--train_batch_size` from the default 32 to a lower number (4-16) can be helpful, or leaving `--train_batch_size` at the default and increasing `--gradient_accumulation_steps` to 2-8. Changing `--gradient_accumulation_steps` may be preferable as alterations to the batch size may require corresponding changes in the learning rate to compensate. There is also a `--reduce_memory` option for both the `pregenerate_training_data.py` and `finetune_on_pregenerated.py` scripts that spills data to disc in shelf objects or numpy memmaps rather than retaining it in memory, which significantly reduces memory usage with little performance impact.
29
+
30
+ ## Examples
31
+
32
+ ### Simple fine-tuning
33
+
34
+ ```
35
+ python3 simple_lm_finetuning.py
36
+ --train_corpus my_corpus.txt
37
+ --bert_model bert-base-uncased
38
+ --do_lower_case
39
+ --output_dir finetuned_lm/
40
+ --do_train
41
+ ```
42
+
43
+ ### Pregenerating training data
44
+
45
+ ```
46
+ python3 pregenerate_training_data.py
47
+ --train_corpus my_corpus.txt
48
+ --bert_model bert-base-uncased
49
+ --do_lower_case
50
+ --output_dir training/
51
+ --epochs_to_generate 3
52
+ --max_seq_len 256
53
+ ```
54
+
55
+ ### Training on pregenerated data
56
+
57
+ ```
58
+ python3 finetune_on_pregenerated.py
59
+ --pregenerated_data training/
60
+ --bert_model bert-base-uncased
61
+ --do_lower_case
62
+ --output_dir finetuned_lm/
63
+ --epochs 3
64
+ ```
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/finetune_on_pregenerated.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser
2
+ from pathlib import Path
3
+ import torch
4
+ import logging
5
+ import json
6
+ import random
7
+ import numpy as np
8
+ from collections import namedtuple
9
+ from tempfile import TemporaryDirectory
10
+
11
+ from torch.utils.data import DataLoader, Dataset, RandomSampler
12
+ from torch.utils.data.distributed import DistributedSampler
13
+ from tqdm import tqdm
14
+
15
+ from pytorch_pretrained_bert.modeling import BertForPreTraining
16
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
17
+ from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
18
+
19
+ InputFeatures = namedtuple("InputFeatures", "input_ids input_mask segment_ids lm_label_ids is_next")
20
+
21
+ log_format = '%(asctime)-10s: %(message)s'
22
+ logging.basicConfig(level=logging.INFO, format=log_format)
23
+
24
+
25
+ def convert_example_to_features(example, tokenizer, max_seq_length):
26
+ tokens = example["tokens"]
27
+ segment_ids = example["segment_ids"]
28
+ is_random_next = example["is_random_next"]
29
+ masked_lm_positions = example["masked_lm_positions"]
30
+ masked_lm_labels = example["masked_lm_labels"]
31
+
32
+ assert len(tokens) == len(segment_ids) <= max_seq_length # The preprocessed data should be already truncated
33
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
34
+ masked_label_ids = tokenizer.convert_tokens_to_ids(masked_lm_labels)
35
+
36
+ input_array = np.zeros(max_seq_length, dtype=np.int)
37
+ input_array[:len(input_ids)] = input_ids
38
+
39
+ mask_array = np.zeros(max_seq_length, dtype=np.bool)
40
+ mask_array[:len(input_ids)] = 1
41
+
42
+ segment_array = np.zeros(max_seq_length, dtype=np.bool)
43
+ segment_array[:len(segment_ids)] = segment_ids
44
+
45
+ lm_label_array = np.full(max_seq_length, dtype=np.int, fill_value=-1)
46
+ lm_label_array[masked_lm_positions] = masked_label_ids
47
+
48
+ features = InputFeatures(input_ids=input_array,
49
+ input_mask=mask_array,
50
+ segment_ids=segment_array,
51
+ lm_label_ids=lm_label_array,
52
+ is_next=is_random_next)
53
+ return features
54
+
55
+
56
+ class PregeneratedDataset(Dataset):
57
+ def __init__(self, training_path, epoch, tokenizer, num_data_epochs, reduce_memory=False):
58
+ self.vocab = tokenizer.vocab
59
+ self.tokenizer = tokenizer
60
+ self.epoch = epoch
61
+ self.data_epoch = epoch % num_data_epochs
62
+ data_file = training_path / f"epoch_{self.data_epoch}.json"
63
+ metrics_file = training_path / f"epoch_{self.data_epoch}_metrics.json"
64
+ assert data_file.is_file() and metrics_file.is_file()
65
+ metrics = json.loads(metrics_file.read_text())
66
+ num_samples = metrics['num_training_examples']
67
+ seq_len = metrics['max_seq_len']
68
+ self.temp_dir = None
69
+ self.working_dir = None
70
+ if reduce_memory:
71
+ self.temp_dir = TemporaryDirectory()
72
+ self.working_dir = Path(self.temp_dir.name)
73
+ input_ids = np.memmap(filename=self.working_dir/'input_ids.memmap',
74
+ mode='w+', dtype=np.int32, shape=(num_samples, seq_len))
75
+ input_masks = np.memmap(filename=self.working_dir/'input_masks.memmap',
76
+ shape=(num_samples, seq_len), mode='w+', dtype=np.bool)
77
+ segment_ids = np.memmap(filename=self.working_dir/'input_masks.memmap',
78
+ shape=(num_samples, seq_len), mode='w+', dtype=np.bool)
79
+ lm_label_ids = np.memmap(filename=self.working_dir/'lm_label_ids.memmap',
80
+ shape=(num_samples, seq_len), mode='w+', dtype=np.int32)
81
+ lm_label_ids[:] = -1
82
+ is_nexts = np.memmap(filename=self.working_dir/'is_nexts.memmap',
83
+ shape=(num_samples,), mode='w+', dtype=np.bool)
84
+ else:
85
+ input_ids = np.zeros(shape=(num_samples, seq_len), dtype=np.int32)
86
+ input_masks = np.zeros(shape=(num_samples, seq_len), dtype=np.bool)
87
+ segment_ids = np.zeros(shape=(num_samples, seq_len), dtype=np.bool)
88
+ lm_label_ids = np.full(shape=(num_samples, seq_len), dtype=np.int32, fill_value=-1)
89
+ is_nexts = np.zeros(shape=(num_samples,), dtype=np.bool)
90
+ logging.info(f"Loading training examples for epoch {epoch}")
91
+ with data_file.open() as f:
92
+ for i, line in enumerate(tqdm(f, total=num_samples, desc="Training examples")):
93
+ line = line.strip()
94
+ example = json.loads(line)
95
+ features = convert_example_to_features(example, tokenizer, seq_len)
96
+ input_ids[i] = features.input_ids
97
+ segment_ids[i] = features.segment_ids
98
+ input_masks[i] = features.input_mask
99
+ lm_label_ids[i] = features.lm_label_ids
100
+ is_nexts[i] = features.is_next
101
+ assert i == num_samples - 1 # Assert that the sample count metric was true
102
+ logging.info("Loading complete!")
103
+ self.num_samples = num_samples
104
+ self.seq_len = seq_len
105
+ self.input_ids = input_ids
106
+ self.input_masks = input_masks
107
+ self.segment_ids = segment_ids
108
+ self.lm_label_ids = lm_label_ids
109
+ self.is_nexts = is_nexts
110
+
111
+ def __len__(self):
112
+ return self.num_samples
113
+
114
+ def __getitem__(self, item):
115
+ return (torch.tensor(self.input_ids[item].astype(np.int64)),
116
+ torch.tensor(self.input_masks[item].astype(np.int64)),
117
+ torch.tensor(self.segment_ids[item].astype(np.int64)),
118
+ torch.tensor(self.lm_label_ids[item].astype(np.int64)),
119
+ torch.tensor(self.is_nexts[item].astype(np.int64)))
120
+
121
+
122
+ def main():
123
+ parser = ArgumentParser()
124
+ parser.add_argument('--pregenerated_data', type=Path, required=True)
125
+ parser.add_argument('--output_dir', type=Path, required=True)
126
+ parser.add_argument("--bert_model", type=str, required=True, help="Bert pre-trained model selected in the list: bert-base-uncased, "
127
+ "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.")
128
+ parser.add_argument("--do_lower_case", action="store_true")
129
+ parser.add_argument("--reduce_memory", action="store_true",
130
+ help="Store training data as on-disc memmaps to massively reduce memory usage")
131
+
132
+ parser.add_argument("--epochs", type=int, default=3, help="Number of epochs to train for")
133
+ parser.add_argument("--local_rank",
134
+ type=int,
135
+ default=-1,
136
+ help="local_rank for distributed training on gpus")
137
+ parser.add_argument("--no_cuda",
138
+ action='store_true',
139
+ help="Whether not to use CUDA when available")
140
+ parser.add_argument('--gradient_accumulation_steps',
141
+ type=int,
142
+ default=1,
143
+ help="Number of updates steps to accumulate before performing a backward/update pass.")
144
+ parser.add_argument("--train_batch_size",
145
+ default=32,
146
+ type=int,
147
+ help="Total batch size for training.")
148
+ parser.add_argument('--fp16',
149
+ action='store_true',
150
+ help="Whether to use 16-bit float precision instead of 32-bit")
151
+ parser.add_argument('--loss_scale',
152
+ type=float, default=0,
153
+ help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
154
+ "0 (default value): dynamic loss scaling.\n"
155
+ "Positive power of 2: static loss scaling value.\n")
156
+ parser.add_argument("--warmup_proportion",
157
+ default=0.1,
158
+ type=float,
159
+ help="Proportion of training to perform linear learning rate warmup for. "
160
+ "E.g., 0.1 = 10%% of training.")
161
+ parser.add_argument("--learning_rate",
162
+ default=3e-5,
163
+ type=float,
164
+ help="The initial learning rate for Adam.")
165
+ parser.add_argument('--seed',
166
+ type=int,
167
+ default=42,
168
+ help="random seed for initialization")
169
+ args = parser.parse_args()
170
+
171
+ assert args.pregenerated_data.is_dir(), \
172
+ "--pregenerated_data should point to the folder of files made by pregenerate_training_data.py!"
173
+
174
+ samples_per_epoch = []
175
+ for i in range(args.epochs):
176
+ epoch_file = args.pregenerated_data / f"epoch_{i}.json"
177
+ metrics_file = args.pregenerated_data / f"epoch_{i}_metrics.json"
178
+ if epoch_file.is_file() and metrics_file.is_file():
179
+ metrics = json.loads(metrics_file.read_text())
180
+ samples_per_epoch.append(metrics['num_training_examples'])
181
+ else:
182
+ if i == 0:
183
+ exit("No training data was found!")
184
+ print(f"Warning! There are fewer epochs of pregenerated data ({i}) than training epochs ({args.epochs}).")
185
+ print("This script will loop over the available data, but training diversity may be negatively impacted.")
186
+ num_data_epochs = i
187
+ break
188
+ else:
189
+ num_data_epochs = args.epochs
190
+
191
+ if args.local_rank == -1 or args.no_cuda:
192
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
193
+ n_gpu = torch.cuda.device_count()
194
+ else:
195
+ torch.cuda.set_device(args.local_rank)
196
+ device = torch.device("cuda", args.local_rank)
197
+ n_gpu = 1
198
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
199
+ torch.distributed.init_process_group(backend='nccl')
200
+ logging.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
201
+ device, n_gpu, bool(args.local_rank != -1), args.fp16))
202
+
203
+ if args.gradient_accumulation_steps < 1:
204
+ raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
205
+ args.gradient_accumulation_steps))
206
+
207
+ args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
208
+
209
+ random.seed(args.seed)
210
+ np.random.seed(args.seed)
211
+ torch.manual_seed(args.seed)
212
+ if n_gpu > 0:
213
+ torch.cuda.manual_seed_all(args.seed)
214
+
215
+ if args.output_dir.is_dir() and list(args.output_dir.iterdir()):
216
+ logging.warning(f"Output directory ({args.output_dir}) already exists and is not empty!")
217
+ args.output_dir.mkdir(parents=True, exist_ok=True)
218
+
219
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
220
+
221
+ total_train_examples = 0
222
+ for i in range(args.epochs):
223
+ # The modulo takes into account the fact that we may loop over limited epochs of data
224
+ total_train_examples += samples_per_epoch[i % len(samples_per_epoch)]
225
+
226
+ num_train_optimization_steps = int(
227
+ total_train_examples / args.train_batch_size / args.gradient_accumulation_steps)
228
+ if args.local_rank != -1:
229
+ num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
230
+
231
+ # Prepare model
232
+ model = BertForPreTraining.from_pretrained(args.bert_model)
233
+ if args.fp16:
234
+ model.half()
235
+ model.to(device)
236
+ if args.local_rank != -1:
237
+ try:
238
+ from apex.parallel import DistributedDataParallel as DDP
239
+ except ImportError:
240
+ raise ImportError(
241
+ "Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
242
+ model = DDP(model)
243
+ elif n_gpu > 1:
244
+ model = torch.nn.DataParallel(model)
245
+
246
+ # Prepare optimizer
247
+ param_optimizer = list(model.named_parameters())
248
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
249
+ optimizer_grouped_parameters = [
250
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
251
+ 'weight_decay': 0.01},
252
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
253
+ ]
254
+
255
+ if args.fp16:
256
+ try:
257
+ from apex.optimizers import FP16_Optimizer
258
+ from apex.optimizers import FusedAdam
259
+ except ImportError:
260
+ raise ImportError(
261
+ "Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
262
+
263
+ optimizer = FusedAdam(optimizer_grouped_parameters,
264
+ lr=args.learning_rate,
265
+ bias_correction=False,
266
+ max_grad_norm=1.0)
267
+ if args.loss_scale == 0:
268
+ optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
269
+ else:
270
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
271
+
272
+ else:
273
+ optimizer = BertAdam(optimizer_grouped_parameters,
274
+ lr=args.learning_rate,
275
+ warmup=args.warmup_proportion,
276
+ t_total=num_train_optimization_steps)
277
+
278
+ global_step = 0
279
+ logging.info("***** Running training *****")
280
+ logging.info(f" Num examples = {total_train_examples}")
281
+ logging.info(" Batch size = %d", args.train_batch_size)
282
+ logging.info(" Num steps = %d", num_train_optimization_steps)
283
+ model.train()
284
+ for epoch in range(args.epochs):
285
+ epoch_dataset = PregeneratedDataset(epoch=epoch, training_path=args.pregenerated_data, tokenizer=tokenizer,
286
+ num_data_epochs=num_data_epochs)
287
+ if args.local_rank == -1:
288
+ train_sampler = RandomSampler(epoch_dataset)
289
+ else:
290
+ train_sampler = DistributedSampler(epoch_dataset)
291
+ train_dataloader = DataLoader(epoch_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
292
+ tr_loss = 0
293
+ nb_tr_examples, nb_tr_steps = 0, 0
294
+ with tqdm(total=len(train_dataloader), desc=f"Epoch {epoch}") as pbar:
295
+ for step, batch in enumerate(train_dataloader):
296
+ batch = tuple(t.to(device) for t in batch)
297
+ input_ids, input_mask, segment_ids, lm_label_ids, is_next = batch
298
+ loss = model(input_ids, segment_ids, input_mask, lm_label_ids, is_next)
299
+ if n_gpu > 1:
300
+ loss = loss.mean() # mean() to average on multi-gpu.
301
+ if args.gradient_accumulation_steps > 1:
302
+ loss = loss / args.gradient_accumulation_steps
303
+ if args.fp16:
304
+ optimizer.backward(loss)
305
+ else:
306
+ loss.backward()
307
+ tr_loss += loss.item()
308
+ nb_tr_examples += input_ids.size(0)
309
+ nb_tr_steps += 1
310
+ pbar.update(1)
311
+ mean_loss = tr_loss * args.gradient_accumulation_steps / nb_tr_steps
312
+ pbar.set_postfix_str(f"Loss: {mean_loss:.5f}")
313
+ if (step + 1) % args.gradient_accumulation_steps == 0:
314
+ if args.fp16:
315
+ # modify learning rate with special warm up BERT uses
316
+ # if args.fp16 is False, BertAdam is used that handles this automatically
317
+ lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps,
318
+ args.warmup_proportion)
319
+ for param_group in optimizer.param_groups:
320
+ param_group['lr'] = lr_this_step
321
+ optimizer.step()
322
+ optimizer.zero_grad()
323
+ global_step += 1
324
+
325
+ # Save a trained model
326
+ logging.info("** ** * Saving fine-tuned model ** ** * ")
327
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
328
+ output_model_file = args.output_dir / "pytorch_model.bin"
329
+ torch.save(model_to_save.state_dict(), str(output_model_file))
330
+
331
+
332
+ if __name__ == '__main__':
333
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/pregenerate_training_data.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser
2
+ from pathlib import Path
3
+ from tqdm import tqdm, trange
4
+ from tempfile import TemporaryDirectory
5
+ import shelve
6
+
7
+ from random import random, randrange, randint, shuffle, choice, sample
8
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
9
+ import numpy as np
10
+ import json
11
+
12
+
13
+ class DocumentDatabase:
14
+ def __init__(self, reduce_memory=False):
15
+ if reduce_memory:
16
+ self.temp_dir = TemporaryDirectory()
17
+ self.working_dir = Path(self.temp_dir.name)
18
+ self.document_shelf_filepath = self.working_dir / 'shelf.db'
19
+ self.document_shelf = shelve.open(str(self.document_shelf_filepath),
20
+ flag='n', protocol=-1)
21
+ self.documents = None
22
+ else:
23
+ self.documents = []
24
+ self.document_shelf = None
25
+ self.document_shelf_filepath = None
26
+ self.temp_dir = None
27
+ self.doc_lengths = []
28
+ self.doc_cumsum = None
29
+ self.cumsum_max = None
30
+ self.reduce_memory = reduce_memory
31
+
32
+ def add_document(self, document):
33
+ if not document:
34
+ return
35
+ if self.reduce_memory:
36
+ current_idx = len(self.doc_lengths)
37
+ self.document_shelf[str(current_idx)] = document
38
+ else:
39
+ self.documents.append(document)
40
+ self.doc_lengths.append(len(document))
41
+
42
+ def _precalculate_doc_weights(self):
43
+ self.doc_cumsum = np.cumsum(self.doc_lengths)
44
+ self.cumsum_max = self.doc_cumsum[-1]
45
+
46
+ def sample_doc(self, current_idx, sentence_weighted=True):
47
+ # Uses the current iteration counter to ensure we don't sample the same doc twice
48
+ if sentence_weighted:
49
+ # With sentence weighting, we sample docs proportionally to their sentence length
50
+ if self.doc_cumsum is None or len(self.doc_cumsum) != len(self.doc_lengths):
51
+ self._precalculate_doc_weights()
52
+ rand_start = self.doc_cumsum[current_idx]
53
+ rand_end = rand_start + self.cumsum_max - self.doc_lengths[current_idx]
54
+ sentence_index = randrange(rand_start, rand_end) % self.cumsum_max
55
+ sampled_doc_index = np.searchsorted(self.doc_cumsum, sentence_index, side='right')
56
+ else:
57
+ # If we don't use sentence weighting, then every doc has an equal chance to be chosen
58
+ sampled_doc_index = (current_idx + randrange(1, len(self.doc_lengths))) % len(self.doc_lengths)
59
+ assert sampled_doc_index != current_idx
60
+ if self.reduce_memory:
61
+ return self.document_shelf[str(sampled_doc_index)]
62
+ else:
63
+ return self.documents[sampled_doc_index]
64
+
65
+ def __len__(self):
66
+ return len(self.doc_lengths)
67
+
68
+ def __getitem__(self, item):
69
+ if self.reduce_memory:
70
+ return self.document_shelf[str(item)]
71
+ else:
72
+ return self.documents[item]
73
+
74
+ def __enter__(self):
75
+ return self
76
+
77
+ def __exit__(self, exc_type, exc_val, traceback):
78
+ if self.document_shelf is not None:
79
+ self.document_shelf.close()
80
+ if self.temp_dir is not None:
81
+ self.temp_dir.cleanup()
82
+
83
+
84
+ def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens):
85
+ """Truncates a pair of sequences to a maximum sequence length. Lifted from Google's BERT repo."""
86
+ while True:
87
+ total_length = len(tokens_a) + len(tokens_b)
88
+ if total_length <= max_num_tokens:
89
+ break
90
+
91
+ trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
92
+ assert len(trunc_tokens) >= 1
93
+
94
+ # We want to sometimes truncate from the front and sometimes from the
95
+ # back to add more randomness and avoid biases.
96
+ if random() < 0.5:
97
+ del trunc_tokens[0]
98
+ else:
99
+ trunc_tokens.pop()
100
+
101
+
102
+ def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list):
103
+ """Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but
104
+ with several refactors to clean it up and remove a lot of unnecessary variables."""
105
+ cand_indices = []
106
+ for (i, token) in enumerate(tokens):
107
+ if token == "[CLS]" or token == "[SEP]":
108
+ continue
109
+ cand_indices.append(i)
110
+
111
+ num_to_mask = min(max_predictions_per_seq,
112
+ max(1, int(round(len(tokens) * masked_lm_prob))))
113
+ shuffle(cand_indices)
114
+ mask_indices = sorted(sample(cand_indices, num_to_mask))
115
+ masked_token_labels = []
116
+ for index in mask_indices:
117
+ # 80% of the time, replace with [MASK]
118
+ if random() < 0.8:
119
+ masked_token = "[MASK]"
120
+ else:
121
+ # 10% of the time, keep original
122
+ if random() < 0.5:
123
+ masked_token = tokens[index]
124
+ # 10% of the time, replace with random word
125
+ else:
126
+ masked_token = choice(vocab_list)
127
+ masked_token_labels.append(tokens[index])
128
+ # Once we've saved the true label for that token, we can overwrite it with the masked version
129
+ tokens[index] = masked_token
130
+
131
+ return tokens, mask_indices, masked_token_labels
132
+
133
+
134
+ def create_instances_from_document(
135
+ doc_database, doc_idx, max_seq_length, short_seq_prob,
136
+ masked_lm_prob, max_predictions_per_seq, vocab_list):
137
+ """This code is mostly a duplicate of the equivalent function from Google BERT's repo.
138
+ However, we make some changes and improvements. Sampling is improved and no longer requires a loop in this function.
139
+ Also, documents are sampled proportionally to the number of sentences they contain, which means each sentence
140
+ (rather than each document) has an equal chance of being sampled as a false example for the NextSentence task."""
141
+ document = doc_database[doc_idx]
142
+ # Account for [CLS], [SEP], [SEP]
143
+ max_num_tokens = max_seq_length - 3
144
+
145
+ # We *usually* want to fill up the entire sequence since we are padding
146
+ # to `max_seq_length` anyways, so short sequences are generally wasted
147
+ # computation. However, we *sometimes*
148
+ # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
149
+ # sequences to minimize the mismatch between pre-training and fine-tuning.
150
+ # The `target_seq_length` is just a rough target however, whereas
151
+ # `max_seq_length` is a hard limit.
152
+ target_seq_length = max_num_tokens
153
+ if random() < short_seq_prob:
154
+ target_seq_length = randint(2, max_num_tokens)
155
+
156
+ # We DON'T just concatenate all of the tokens from a document into a long
157
+ # sequence and choose an arbitrary split point because this would make the
158
+ # next sentence prediction task too easy. Instead, we split the input into
159
+ # segments "A" and "B" based on the actual "sentences" provided by the user
160
+ # input.
161
+ instances = []
162
+ current_chunk = []
163
+ current_length = 0
164
+ i = 0
165
+ while i < len(document):
166
+ segment = document[i]
167
+ current_chunk.append(segment)
168
+ current_length += len(segment)
169
+ if i == len(document) - 1 or current_length >= target_seq_length:
170
+ if current_chunk:
171
+ # `a_end` is how many segments from `current_chunk` go into the `A`
172
+ # (first) sentence.
173
+ a_end = 1
174
+ if len(current_chunk) >= 2:
175
+ a_end = randrange(1, len(current_chunk))
176
+
177
+ tokens_a = []
178
+ for j in range(a_end):
179
+ tokens_a.extend(current_chunk[j])
180
+
181
+ tokens_b = []
182
+
183
+ # Random next
184
+ if len(current_chunk) == 1 or random() < 0.5:
185
+ is_random_next = True
186
+ target_b_length = target_seq_length - len(tokens_a)
187
+
188
+ # Sample a random document, with longer docs being sampled more frequently
189
+ random_document = doc_database.sample_doc(current_idx=doc_idx, sentence_weighted=True)
190
+
191
+ random_start = randrange(0, len(random_document))
192
+ for j in range(random_start, len(random_document)):
193
+ tokens_b.extend(random_document[j])
194
+ if len(tokens_b) >= target_b_length:
195
+ break
196
+ # We didn't actually use these segments so we "put them back" so
197
+ # they don't go to waste.
198
+ num_unused_segments = len(current_chunk) - a_end
199
+ i -= num_unused_segments
200
+ # Actual next
201
+ else:
202
+ is_random_next = False
203
+ for j in range(a_end, len(current_chunk)):
204
+ tokens_b.extend(current_chunk[j])
205
+ truncate_seq_pair(tokens_a, tokens_b, max_num_tokens)
206
+
207
+ assert len(tokens_a) >= 1
208
+ assert len(tokens_b) >= 1
209
+
210
+ tokens = ["[CLS]"] + tokens_a + ["[SEP]"] + tokens_b + ["[SEP]"]
211
+ # The segment IDs are 0 for the [CLS] token, the A tokens and the first [SEP]
212
+ # They are 1 for the B tokens and the final [SEP]
213
+ segment_ids = [0 for _ in range(len(tokens_a) + 2)] + [1 for _ in range(len(tokens_b) + 1)]
214
+
215
+ tokens, masked_lm_positions, masked_lm_labels = create_masked_lm_predictions(
216
+ tokens, masked_lm_prob, max_predictions_per_seq, vocab_list)
217
+
218
+ instance = {
219
+ "tokens": tokens,
220
+ "segment_ids": segment_ids,
221
+ "is_random_next": is_random_next,
222
+ "masked_lm_positions": masked_lm_positions,
223
+ "masked_lm_labels": masked_lm_labels}
224
+ instances.append(instance)
225
+ current_chunk = []
226
+ current_length = 0
227
+ i += 1
228
+
229
+ return instances
230
+
231
+
232
+ def main():
233
+ parser = ArgumentParser()
234
+ parser.add_argument('--train_corpus', type=Path, required=True)
235
+ parser.add_argument("--output_dir", type=Path, required=True)
236
+ parser.add_argument("--bert_model", type=str, required=True,
237
+ choices=["bert-base-uncased", "bert-large-uncased", "bert-base-cased",
238
+ "bert-base-multilingual", "bert-base-chinese"])
239
+ parser.add_argument("--do_lower_case", action="store_true")
240
+
241
+ parser.add_argument("--reduce_memory", action="store_true",
242
+ help="Reduce memory usage for large datasets by keeping data on disc rather than in memory")
243
+
244
+ parser.add_argument("--epochs_to_generate", type=int, default=3,
245
+ help="Number of epochs of data to pregenerate")
246
+ parser.add_argument("--max_seq_len", type=int, default=128)
247
+ parser.add_argument("--short_seq_prob", type=float, default=0.1,
248
+ help="Probability of making a short sentence as a training example")
249
+ parser.add_argument("--masked_lm_prob", type=float, default=0.15,
250
+ help="Probability of masking each token for the LM task")
251
+ parser.add_argument("--max_predictions_per_seq", type=int, default=20,
252
+ help="Maximum number of tokens to mask in each sequence")
253
+
254
+ args = parser.parse_args()
255
+
256
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
257
+ vocab_list = list(tokenizer.vocab.keys())
258
+ with DocumentDatabase(reduce_memory=args.reduce_memory) as docs:
259
+ with args.train_corpus.open() as f:
260
+ doc = []
261
+ for line in tqdm(f, desc="Loading Dataset", unit=" lines"):
262
+ line = line.strip()
263
+ if line == "":
264
+ docs.add_document(doc)
265
+ doc = []
266
+ else:
267
+ tokens = tokenizer.tokenize(line)
268
+ doc.append(tokens)
269
+ if doc:
270
+ docs.add_document(doc) # If the last doc didn't end on a newline, make sure it still gets added
271
+ if len(docs) <= 1:
272
+ exit("ERROR: No document breaks were found in the input file! These are necessary to allow the script to "
273
+ "ensure that random NextSentences are not sampled from the same document. Please add blank lines to "
274
+ "indicate breaks between documents in your input file. If your dataset does not contain multiple "
275
+ "documents, blank lines can be inserted at any natural boundary, such as the ends of chapters, "
276
+ "sections or paragraphs.")
277
+
278
+ args.output_dir.mkdir(exist_ok=True)
279
+ for epoch in trange(args.epochs_to_generate, desc="Epoch"):
280
+ epoch_filename = args.output_dir / f"epoch_{epoch}.json"
281
+ num_instances = 0
282
+ with epoch_filename.open('w') as epoch_file:
283
+ for doc_idx in trange(len(docs), desc="Document"):
284
+ doc_instances = create_instances_from_document(
285
+ docs, doc_idx, max_seq_length=args.max_seq_len, short_seq_prob=args.short_seq_prob,
286
+ masked_lm_prob=args.masked_lm_prob, max_predictions_per_seq=args.max_predictions_per_seq,
287
+ vocab_list=vocab_list)
288
+ doc_instances = [json.dumps(instance) for instance in doc_instances]
289
+ for instance in doc_instances:
290
+ epoch_file.write(instance + '\n')
291
+ num_instances += 1
292
+ metrics_file = args.output_dir / f"epoch_{epoch}_metrics.json"
293
+ with metrics_file.open('w') as metrics_file:
294
+ metrics = {
295
+ "num_training_examples": num_instances,
296
+ "max_seq_len": args.max_seq_len
297
+ }
298
+ metrics_file.write(json.dumps(metrics))
299
+
300
+
301
+ if __name__ == '__main__':
302
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/lm_finetuning/simple_lm_finetuning.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """BERT finetuning runner."""
17
+
18
+ from __future__ import absolute_import, division, print_function, unicode_literals
19
+
20
+ import argparse
21
+ import logging
22
+ import os
23
+ import random
24
+ from io import open
25
+
26
+ import numpy as np
27
+ import torch
28
+ from torch.utils.data import DataLoader, Dataset, RandomSampler
29
+ from torch.utils.data.distributed import DistributedSampler
30
+ from tqdm import tqdm, trange
31
+
32
+ from pytorch_pretrained_bert.modeling import BertForPreTraining
33
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
34
+ from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
35
+
36
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
37
+ datefmt='%m/%d/%Y %H:%M:%S',
38
+ level=logging.INFO)
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class BERTDataset(Dataset):
43
+ def __init__(self, corpus_path, tokenizer, seq_len, encoding="utf-8", corpus_lines=None, on_memory=True):
44
+ self.vocab = tokenizer.vocab
45
+ self.tokenizer = tokenizer
46
+ self.seq_len = seq_len
47
+ self.on_memory = on_memory
48
+ self.corpus_lines = corpus_lines # number of non-empty lines in input corpus
49
+ self.corpus_path = corpus_path
50
+ self.encoding = encoding
51
+ self.current_doc = 0 # to avoid random sentence from same doc
52
+
53
+ # for loading samples directly from file
54
+ self.sample_counter = 0 # used to keep track of full epochs on file
55
+ self.line_buffer = None # keep second sentence of a pair in memory and use as first sentence in next pair
56
+
57
+ # for loading samples in memory
58
+ self.current_random_doc = 0
59
+ self.num_docs = 0
60
+ self.sample_to_doc = [] # map sample index to doc and line
61
+
62
+ # load samples into memory
63
+ if on_memory:
64
+ self.all_docs = []
65
+ doc = []
66
+ self.corpus_lines = 0
67
+ with open(corpus_path, "r", encoding=encoding) as f:
68
+ for line in tqdm(f, desc="Loading Dataset", total=corpus_lines):
69
+ line = line.strip()
70
+ if line == "":
71
+ self.all_docs.append(doc)
72
+ doc = []
73
+ #remove last added sample because there won't be a subsequent line anymore in the doc
74
+ self.sample_to_doc.pop()
75
+ else:
76
+ #store as one sample
77
+ sample = {"doc_id": len(self.all_docs),
78
+ "line": len(doc)}
79
+ self.sample_to_doc.append(sample)
80
+ doc.append(line)
81
+ self.corpus_lines = self.corpus_lines + 1
82
+
83
+ # if last row in file is not empty
84
+ if self.all_docs[-1] != doc:
85
+ self.all_docs.append(doc)
86
+ self.sample_to_doc.pop()
87
+
88
+ self.num_docs = len(self.all_docs)
89
+
90
+ # load samples later lazily from disk
91
+ else:
92
+ if self.corpus_lines is None:
93
+ with open(corpus_path, "r", encoding=encoding) as f:
94
+ self.corpus_lines = 0
95
+ for line in tqdm(f, desc="Loading Dataset", total=corpus_lines):
96
+ if line.strip() == "":
97
+ self.num_docs += 1
98
+ else:
99
+ self.corpus_lines += 1
100
+
101
+ # if doc does not end with empty line
102
+ if line.strip() != "":
103
+ self.num_docs += 1
104
+
105
+ self.file = open(corpus_path, "r", encoding=encoding)
106
+ self.random_file = open(corpus_path, "r", encoding=encoding)
107
+
108
+ def __len__(self):
109
+ # last line of doc won't be used, because there's no "nextSentence". Additionally, we start counting at 0.
110
+ return self.corpus_lines - self.num_docs - 1
111
+
112
+ def __getitem__(self, item):
113
+ cur_id = self.sample_counter
114
+ self.sample_counter += 1
115
+ if not self.on_memory:
116
+ # after one epoch we start again from beginning of file
117
+ if cur_id != 0 and (cur_id % len(self) == 0):
118
+ self.file.close()
119
+ self.file = open(self.corpus_path, "r", encoding=self.encoding)
120
+
121
+ t1, t2, is_next_label = self.random_sent(item)
122
+
123
+ # tokenize
124
+ tokens_a = self.tokenizer.tokenize(t1)
125
+ tokens_b = self.tokenizer.tokenize(t2)
126
+
127
+ # combine to one sample
128
+ cur_example = InputExample(guid=cur_id, tokens_a=tokens_a, tokens_b=tokens_b, is_next=is_next_label)
129
+
130
+ # transform sample to features
131
+ cur_features = convert_example_to_features(cur_example, self.seq_len, self.tokenizer)
132
+
133
+ cur_tensors = (torch.tensor(cur_features.input_ids),
134
+ torch.tensor(cur_features.input_mask),
135
+ torch.tensor(cur_features.segment_ids),
136
+ torch.tensor(cur_features.lm_label_ids),
137
+ torch.tensor(cur_features.is_next))
138
+
139
+ return cur_tensors
140
+
141
+ def random_sent(self, index):
142
+ """
143
+ Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences
144
+ from one doc. With 50% the second sentence will be a random one from another doc.
145
+ :param index: int, index of sample.
146
+ :return: (str, str, int), sentence 1, sentence 2, isNextSentence Label
147
+ """
148
+ t1, t2 = self.get_corpus_line(index)
149
+ if random.random() > 0.5:
150
+ label = 0
151
+ else:
152
+ t2 = self.get_random_line()
153
+ label = 1
154
+
155
+ assert len(t1) > 0
156
+ assert len(t2) > 0
157
+ return t1, t2, label
158
+
159
+ def get_corpus_line(self, item):
160
+ """
161
+ Get one sample from corpus consisting of a pair of two subsequent lines from the same doc.
162
+ :param item: int, index of sample.
163
+ :return: (str, str), two subsequent sentences from corpus
164
+ """
165
+ t1 = ""
166
+ t2 = ""
167
+ assert item < self.corpus_lines
168
+ if self.on_memory:
169
+ sample = self.sample_to_doc[item]
170
+ t1 = self.all_docs[sample["doc_id"]][sample["line"]]
171
+ t2 = self.all_docs[sample["doc_id"]][sample["line"]+1]
172
+ # used later to avoid random nextSentence from same doc
173
+ self.current_doc = sample["doc_id"]
174
+ return t1, t2
175
+ else:
176
+ if self.line_buffer is None:
177
+ # read first non-empty line of file
178
+ while t1 == "" :
179
+ t1 = next(self.file).strip()
180
+ t2 = next(self.file).strip()
181
+ else:
182
+ # use t2 from previous iteration as new t1
183
+ t1 = self.line_buffer
184
+ t2 = next(self.file).strip()
185
+ # skip empty rows that are used for separating documents and keep track of current doc id
186
+ while t2 == "" or t1 == "":
187
+ t1 = next(self.file).strip()
188
+ t2 = next(self.file).strip()
189
+ self.current_doc = self.current_doc+1
190
+ self.line_buffer = t2
191
+
192
+ assert t1 != ""
193
+ assert t2 != ""
194
+ return t1, t2
195
+
196
+ def get_random_line(self):
197
+ """
198
+ Get random line from another document for nextSentence task.
199
+ :return: str, content of one line
200
+ """
201
+ # Similar to original tf repo: This outer loop should rarely go for more than one iteration for large
202
+ # corpora. However, just to be careful, we try to make sure that
203
+ # the random document is not the same as the document we're processing.
204
+ for _ in range(10):
205
+ if self.on_memory:
206
+ rand_doc_idx = random.randint(0, len(self.all_docs)-1)
207
+ rand_doc = self.all_docs[rand_doc_idx]
208
+ line = rand_doc[random.randrange(len(rand_doc))]
209
+ else:
210
+ rand_index = random.randint(1, self.corpus_lines if self.corpus_lines < 1000 else 1000)
211
+ #pick random line
212
+ for _ in range(rand_index):
213
+ line = self.get_next_line()
214
+ #check if our picked random line is really from another doc like we want it to be
215
+ if self.current_random_doc != self.current_doc:
216
+ break
217
+ return line
218
+
219
+ def get_next_line(self):
220
+ """ Gets next line of random_file and starts over when reaching end of file"""
221
+ try:
222
+ line = next(self.random_file).strip()
223
+ #keep track of which document we are currently looking at to later avoid having the same doc as t1
224
+ if line == "":
225
+ self.current_random_doc = self.current_random_doc + 1
226
+ line = next(self.random_file).strip()
227
+ except StopIteration:
228
+ self.random_file.close()
229
+ self.random_file = open(self.corpus_path, "r", encoding=self.encoding)
230
+ line = next(self.random_file).strip()
231
+ return line
232
+
233
+
234
+ class InputExample(object):
235
+ """A single training/test example for the language model."""
236
+
237
+ def __init__(self, guid, tokens_a, tokens_b=None, is_next=None, lm_labels=None):
238
+ """Constructs a InputExample.
239
+
240
+ Args:
241
+ guid: Unique id for the example.
242
+ tokens_a: string. The untokenized text of the first sequence. For single
243
+ sequence tasks, only this sequence must be specified.
244
+ tokens_b: (Optional) string. The untokenized text of the second sequence.
245
+ Only must be specified for sequence pair tasks.
246
+ label: (Optional) string. The label of the example. This should be
247
+ specified for train and dev examples, but not for test examples.
248
+ """
249
+ self.guid = guid
250
+ self.tokens_a = tokens_a
251
+ self.tokens_b = tokens_b
252
+ self.is_next = is_next # nextSentence
253
+ self.lm_labels = lm_labels # masked words for language model
254
+
255
+
256
+ class InputFeatures(object):
257
+ """A single set of features of data."""
258
+
259
+ def __init__(self, input_ids, input_mask, segment_ids, is_next, lm_label_ids):
260
+ self.input_ids = input_ids
261
+ self.input_mask = input_mask
262
+ self.segment_ids = segment_ids
263
+ self.is_next = is_next
264
+ self.lm_label_ids = lm_label_ids
265
+
266
+
267
+ def random_word(tokens, tokenizer):
268
+ """
269
+ Masking some random tokens for Language Model task with probabilities as in the original BERT paper.
270
+ :param tokens: list of str, tokenized sentence.
271
+ :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)
272
+ :return: (list of str, list of int), masked tokens and related labels for LM prediction
273
+ """
274
+ output_label = []
275
+
276
+ for i, token in enumerate(tokens):
277
+ prob = random.random()
278
+ # mask token with 15% probability
279
+ if prob < 0.15:
280
+ prob /= 0.15
281
+
282
+ # 80% randomly change token to mask token
283
+ if prob < 0.8:
284
+ tokens[i] = "[MASK]"
285
+
286
+ # 10% randomly change token to random token
287
+ elif prob < 0.9:
288
+ tokens[i] = random.choice(list(tokenizer.vocab.items()))[0]
289
+
290
+ # -> rest 10% randomly keep current token
291
+
292
+ # append current token to output (we will predict these later)
293
+ try:
294
+ output_label.append(tokenizer.vocab[token])
295
+ except KeyError:
296
+ # For unknown words (should not occur with BPE vocab)
297
+ output_label.append(tokenizer.vocab["[UNK]"])
298
+ logger.warning("Cannot find token '{}' in vocab. Using [UNK] insetad".format(token))
299
+ else:
300
+ # no masking token (will be ignored by loss function later)
301
+ output_label.append(-1)
302
+
303
+ return tokens, output_label
304
+
305
+
306
+ def convert_example_to_features(example, max_seq_length, tokenizer):
307
+ """
308
+ Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample with
309
+ IDs, LM labels, input_mask, CLS and SEP tokens etc.
310
+ :param example: InputExample, containing sentence input as strings and is_next label
311
+ :param max_seq_length: int, maximum length of sequence.
312
+ :param tokenizer: Tokenizer
313
+ :return: InputFeatures, containing all inputs and labels of one sample as IDs (as used for model training)
314
+ """
315
+ tokens_a = example.tokens_a
316
+ tokens_b = example.tokens_b
317
+ # Modifies `tokens_a` and `tokens_b` in place so that the total
318
+ # length is less than the specified length.
319
+ # Account for [CLS], [SEP], [SEP] with "- 3"
320
+ _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
321
+
322
+ tokens_a, t1_label = random_word(tokens_a, tokenizer)
323
+ tokens_b, t2_label = random_word(tokens_b, tokenizer)
324
+ # concatenate lm labels and account for CLS, SEP, SEP
325
+ lm_label_ids = ([-1] + t1_label + [-1] + t2_label + [-1])
326
+
327
+ # The convention in BERT is:
328
+ # (a) For sequence pairs:
329
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
330
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
331
+ # (b) For single sequences:
332
+ # tokens: [CLS] the dog is hairy . [SEP]
333
+ # type_ids: 0 0 0 0 0 0 0
334
+ #
335
+ # Where "type_ids" are used to indicate whether this is the first
336
+ # sequence or the second sequence. The embedding vectors for `type=0` and
337
+ # `type=1` were learned during pre-training and are added to the wordpiece
338
+ # embedding vector (and position vector). This is not *strictly* necessary
339
+ # since the [SEP] token unambigiously separates the sequences, but it makes
340
+ # it easier for the model to learn the concept of sequences.
341
+ #
342
+ # For classification tasks, the first vector (corresponding to [CLS]) is
343
+ # used as as the "sentence vector". Note that this only makes sense because
344
+ # the entire model is fine-tuned.
345
+ tokens = []
346
+ segment_ids = []
347
+ tokens.append("[CLS]")
348
+ segment_ids.append(0)
349
+ for token in tokens_a:
350
+ tokens.append(token)
351
+ segment_ids.append(0)
352
+ tokens.append("[SEP]")
353
+ segment_ids.append(0)
354
+
355
+ assert len(tokens_b) > 0
356
+ for token in tokens_b:
357
+ tokens.append(token)
358
+ segment_ids.append(1)
359
+ tokens.append("[SEP]")
360
+ segment_ids.append(1)
361
+
362
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
363
+
364
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
365
+ # tokens are attended to.
366
+ input_mask = [1] * len(input_ids)
367
+
368
+ # Zero-pad up to the sequence length.
369
+ while len(input_ids) < max_seq_length:
370
+ input_ids.append(0)
371
+ input_mask.append(0)
372
+ segment_ids.append(0)
373
+ lm_label_ids.append(-1)
374
+
375
+ assert len(input_ids) == max_seq_length
376
+ assert len(input_mask) == max_seq_length
377
+ assert len(segment_ids) == max_seq_length
378
+ assert len(lm_label_ids) == max_seq_length
379
+
380
+ if example.guid < 5:
381
+ logger.info("*** Example ***")
382
+ logger.info("guid: %s" % (example.guid))
383
+ logger.info("tokens: %s" % " ".join(
384
+ [str(x) for x in tokens]))
385
+ logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
386
+ logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
387
+ logger.info(
388
+ "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
389
+ logger.info("LM label: %s " % (lm_label_ids))
390
+ logger.info("Is next sentence label: %s " % (example.is_next))
391
+
392
+ features = InputFeatures(input_ids=input_ids,
393
+ input_mask=input_mask,
394
+ segment_ids=segment_ids,
395
+ lm_label_ids=lm_label_ids,
396
+ is_next=example.is_next)
397
+ return features
398
+
399
+
400
+ def main():
401
+ parser = argparse.ArgumentParser()
402
+
403
+ ## Required parameters
404
+ parser.add_argument("--train_corpus",
405
+ default=None,
406
+ type=str,
407
+ required=True,
408
+ help="The input train corpus.")
409
+ parser.add_argument("--bert_model", default=None, type=str, required=True,
410
+ help="Bert pre-trained model selected in the list: bert-base-uncased, "
411
+ "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.")
412
+ parser.add_argument("--output_dir",
413
+ default=None,
414
+ type=str,
415
+ required=True,
416
+ help="The output directory where the model checkpoints will be written.")
417
+
418
+ ## Other parameters
419
+ parser.add_argument("--max_seq_length",
420
+ default=128,
421
+ type=int,
422
+ help="The maximum total input sequence length after WordPiece tokenization. \n"
423
+ "Sequences longer than this will be truncated, and sequences shorter \n"
424
+ "than this will be padded.")
425
+ parser.add_argument("--do_train",
426
+ action='store_true',
427
+ help="Whether to run training.")
428
+ parser.add_argument("--train_batch_size",
429
+ default=32,
430
+ type=int,
431
+ help="Total batch size for training.")
432
+ parser.add_argument("--learning_rate",
433
+ default=3e-5,
434
+ type=float,
435
+ help="The initial learning rate for Adam.")
436
+ parser.add_argument("--num_train_epochs",
437
+ default=3.0,
438
+ type=float,
439
+ help="Total number of training epochs to perform.")
440
+ parser.add_argument("--warmup_proportion",
441
+ default=0.1,
442
+ type=float,
443
+ help="Proportion of training to perform linear learning rate warmup for. "
444
+ "E.g., 0.1 = 10%% of training.")
445
+ parser.add_argument("--no_cuda",
446
+ action='store_true',
447
+ help="Whether not to use CUDA when available")
448
+ parser.add_argument("--on_memory",
449
+ action='store_true',
450
+ help="Whether to load train samples into memory or use disk")
451
+ parser.add_argument("--do_lower_case",
452
+ action='store_true',
453
+ help="Whether to lower case the input text. True for uncased models, False for cased models.")
454
+ parser.add_argument("--local_rank",
455
+ type=int,
456
+ default=-1,
457
+ help="local_rank for distributed training on gpus")
458
+ parser.add_argument('--seed',
459
+ type=int,
460
+ default=42,
461
+ help="random seed for initialization")
462
+ parser.add_argument('--gradient_accumulation_steps',
463
+ type=int,
464
+ default=1,
465
+ help="Number of updates steps to accumualte before performing a backward/update pass.")
466
+ parser.add_argument('--fp16',
467
+ action='store_true',
468
+ help="Whether to use 16-bit float precision instead of 32-bit")
469
+ parser.add_argument('--loss_scale',
470
+ type = float, default = 0,
471
+ help = "Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
472
+ "0 (default value): dynamic loss scaling.\n"
473
+ "Positive power of 2: static loss scaling value.\n")
474
+
475
+ args = parser.parse_args()
476
+
477
+ if args.local_rank == -1 or args.no_cuda:
478
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
479
+ n_gpu = torch.cuda.device_count()
480
+ else:
481
+ torch.cuda.set_device(args.local_rank)
482
+ device = torch.device("cuda", args.local_rank)
483
+ n_gpu = 1
484
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
485
+ torch.distributed.init_process_group(backend='nccl')
486
+ logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
487
+ device, n_gpu, bool(args.local_rank != -1), args.fp16))
488
+
489
+ if args.gradient_accumulation_steps < 1:
490
+ raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
491
+ args.gradient_accumulation_steps))
492
+
493
+ args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
494
+
495
+ random.seed(args.seed)
496
+ np.random.seed(args.seed)
497
+ torch.manual_seed(args.seed)
498
+ if n_gpu > 0:
499
+ torch.cuda.manual_seed_all(args.seed)
500
+
501
+ if not args.do_train:
502
+ raise ValueError("Training is currently the only implemented execution option. Please set `do_train`.")
503
+
504
+ if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
505
+ raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
506
+ if not os.path.exists(args.output_dir):
507
+ os.makedirs(args.output_dir)
508
+
509
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
510
+
511
+ #train_examples = None
512
+ num_train_optimization_steps = None
513
+ if args.do_train:
514
+ print("Loading Train Dataset", args.train_corpus)
515
+ train_dataset = BERTDataset(args.train_corpus, tokenizer, seq_len=args.max_seq_length,
516
+ corpus_lines=None, on_memory=args.on_memory)
517
+ num_train_optimization_steps = int(
518
+ len(train_dataset) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs
519
+ if args.local_rank != -1:
520
+ num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
521
+
522
+ # Prepare model
523
+ model = BertForPreTraining.from_pretrained(args.bert_model)
524
+ if args.fp16:
525
+ model.half()
526
+ model.to(device)
527
+ if args.local_rank != -1:
528
+ try:
529
+ from apex.parallel import DistributedDataParallel as DDP
530
+ except ImportError:
531
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
532
+ model = DDP(model)
533
+ elif n_gpu > 1:
534
+ model = torch.nn.DataParallel(model)
535
+
536
+ # Prepare optimizer
537
+ param_optimizer = list(model.named_parameters())
538
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
539
+ optimizer_grouped_parameters = [
540
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
541
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
542
+ ]
543
+
544
+ if args.fp16:
545
+ try:
546
+ from apex.optimizers import FP16_Optimizer
547
+ from apex.optimizers import FusedAdam
548
+ except ImportError:
549
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
550
+
551
+ optimizer = FusedAdam(optimizer_grouped_parameters,
552
+ lr=args.learning_rate,
553
+ bias_correction=False,
554
+ max_grad_norm=1.0)
555
+ if args.loss_scale == 0:
556
+ optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
557
+ else:
558
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
559
+
560
+ else:
561
+ optimizer = BertAdam(optimizer_grouped_parameters,
562
+ lr=args.learning_rate,
563
+ warmup=args.warmup_proportion,
564
+ t_total=num_train_optimization_steps)
565
+
566
+ global_step = 0
567
+ if args.do_train:
568
+ logger.info("***** Running training *****")
569
+ logger.info(" Num examples = %d", len(train_dataset))
570
+ logger.info(" Batch size = %d", args.train_batch_size)
571
+ logger.info(" Num steps = %d", num_train_optimization_steps)
572
+
573
+ if args.local_rank == -1:
574
+ train_sampler = RandomSampler(train_dataset)
575
+ else:
576
+ #TODO: check if this works with current data generator from disk that relies on next(file)
577
+ # (it doesn't return item back by index)
578
+ train_sampler = DistributedSampler(train_dataset)
579
+ train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
580
+
581
+ model.train()
582
+ for _ in trange(int(args.num_train_epochs), desc="Epoch"):
583
+ tr_loss = 0
584
+ nb_tr_examples, nb_tr_steps = 0, 0
585
+ for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
586
+ batch = tuple(t.to(device) for t in batch)
587
+ input_ids, input_mask, segment_ids, lm_label_ids, is_next = batch
588
+ loss = model(input_ids, segment_ids, input_mask, lm_label_ids, is_next)
589
+ if n_gpu > 1:
590
+ loss = loss.mean() # mean() to average on multi-gpu.
591
+ if args.gradient_accumulation_steps > 1:
592
+ loss = loss / args.gradient_accumulation_steps
593
+ if args.fp16:
594
+ optimizer.backward(loss)
595
+ else:
596
+ loss.backward()
597
+ tr_loss += loss.item()
598
+ nb_tr_examples += input_ids.size(0)
599
+ nb_tr_steps += 1
600
+ if (step + 1) % args.gradient_accumulation_steps == 0:
601
+ if args.fp16:
602
+ # modify learning rate with special warm up BERT uses
603
+ # if args.fp16 is False, BertAdam is used that handles this automatically
604
+ lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)
605
+ for param_group in optimizer.param_groups:
606
+ param_group['lr'] = lr_this_step
607
+ optimizer.step()
608
+ optimizer.zero_grad()
609
+ global_step += 1
610
+
611
+ # Save a trained model
612
+ logger.info("** ** * Saving fine - tuned model ** ** * ")
613
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
614
+ output_model_file = os.path.join(args.output_dir, "pytorch_model.bin")
615
+ if args.do_train:
616
+ torch.save(model_to_save.state_dict(), output_model_file)
617
+
618
+
619
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
620
+ """Truncates a sequence pair in place to the maximum length."""
621
+
622
+ # This is a simple heuristic which will always truncate the longer sequence
623
+ # one token at a time. This makes more sense than truncating an equal percent
624
+ # of tokens from each, since if one sequence is very short then each token
625
+ # that's truncated likely contains more information than a longer sequence.
626
+ while True:
627
+ total_length = len(tokens_a) + len(tokens_b)
628
+ if total_length <= max_length:
629
+ break
630
+ if len(tokens_a) > len(tokens_b):
631
+ tokens_a.pop()
632
+ else:
633
+ tokens_b.pop()
634
+
635
+
636
+ def accuracy(out, labels):
637
+ outputs = np.argmax(out, axis=1)
638
+ return np.sum(outputs == labels)
639
+
640
+
641
+ if __name__ == "__main__":
642
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_classifier.py ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """BERT finetuning runner."""
17
+
18
+ from __future__ import absolute_import, division, print_function
19
+
20
+ import sys
21
+ sys.path.insert(0, "/home/okovaleva/projects/bert_attention/pretrained_bert/pytorch-pretrained-BERT")
22
+ print(sys.path)
23
+
24
+
25
+ import argparse
26
+ import csv
27
+ import logging
28
+ import os
29
+ import random
30
+ import sys
31
+
32
+ import numpy as np
33
+ import torch
34
+ from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
35
+ TensorDataset)
36
+ from torch.utils.data.distributed import DistributedSampler
37
+ from tqdm import tqdm, trange
38
+
39
+ from torch.nn import CrossEntropyLoss, MSELoss
40
+ from scipy.stats import pearsonr, spearmanr
41
+ from sklearn.metrics import matthews_corrcoef, f1_score
42
+
43
+ from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME
44
+ from pytorch_pretrained_bert.modeling import BertForSequenceClassification, BertConfig
45
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
46
+ from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ class InputExample(object):
52
+ """A single training/test example for simple sequence classification."""
53
+
54
+ def __init__(self, guid, text_a, text_b=None, label=None):
55
+ """Constructs a InputExample.
56
+
57
+ Args:
58
+ guid: Unique id for the example.
59
+ text_a: string. The untokenized text of the first sequence. For single
60
+ sequence tasks, only this sequence must be specified.
61
+ text_b: (Optional) string. The untokenized text of the second sequence.
62
+ Only must be specified for sequence pair tasks.
63
+ label: (Optional) string. The label of the example. This should be
64
+ specified for train and dev examples, but not for test examples.
65
+ """
66
+ self.guid = guid
67
+ self.text_a = text_a
68
+ self.text_b = text_b
69
+ self.label = label
70
+
71
+
72
+ class InputFeatures(object):
73
+ """A single set of features of data."""
74
+
75
+ def __init__(self, input_ids, input_mask, segment_ids, label_id):
76
+ self.input_ids = input_ids
77
+ self.input_mask = input_mask
78
+ self.segment_ids = segment_ids
79
+ self.label_id = label_id
80
+
81
+
82
+ class DataProcessor(object):
83
+ """Base class for data converters for sequence classification data sets."""
84
+
85
+ def get_train_examples(self, data_dir):
86
+ """Gets a collection of `InputExample`s for the train set."""
87
+ raise NotImplementedError()
88
+
89
+ def get_dev_examples(self, data_dir):
90
+ """Gets a collection of `InputExample`s for the dev set."""
91
+ raise NotImplementedError()
92
+
93
+ def get_labels(self):
94
+ """Gets the list of labels for this data set."""
95
+ raise NotImplementedError()
96
+
97
+ @classmethod
98
+ def _read_tsv(cls, input_file, quotechar=None):
99
+ """Reads a tab separated value file."""
100
+ with open(input_file, "r", encoding="utf-8") as f:
101
+ reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
102
+ lines = []
103
+ for line in reader:
104
+ if sys.version_info[0] == 2:
105
+ line = list(unicode(cell, 'utf-8') for cell in line)
106
+ lines.append(line)
107
+ return lines
108
+
109
+
110
+ class MrpcProcessor(DataProcessor):
111
+ """Processor for the MRPC data set (GLUE version)."""
112
+
113
+ def get_train_examples(self, data_dir):
114
+ """See base class."""
115
+ logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv")))
116
+ return self._create_examples(
117
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
118
+
119
+ def get_dev_examples(self, data_dir):
120
+ """See base class."""
121
+ return self._create_examples(
122
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
123
+
124
+ def get_labels(self):
125
+ """See base class."""
126
+ return ["0", "1"]
127
+
128
+ def _create_examples(self, lines, set_type):
129
+ """Creates examples for the training and dev sets."""
130
+ examples = []
131
+ for (i, line) in enumerate(lines):
132
+ if i == 0:
133
+ continue
134
+ guid = "%s-%s" % (set_type, i)
135
+ text_a = line[3]
136
+ text_b = line[4]
137
+ label = line[0]
138
+ examples.append(
139
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
140
+ return examples
141
+
142
+
143
+ class MnliProcessor(DataProcessor):
144
+ """Processor for the MultiNLI data set (GLUE version)."""
145
+
146
+ def get_train_examples(self, data_dir):
147
+ """See base class."""
148
+ return self._create_examples(
149
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
150
+
151
+ def get_dev_examples(self, data_dir):
152
+ """See base class."""
153
+ return self._create_examples(
154
+ self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")),
155
+ "dev_matched")
156
+
157
+ def get_labels(self):
158
+ """See base class."""
159
+ return ["contradiction", "entailment", "neutral"]
160
+
161
+ def _create_examples(self, lines, set_type):
162
+ """Creates examples for the training and dev sets."""
163
+ examples = []
164
+ for (i, line) in enumerate(lines):
165
+ if i == 0:
166
+ continue
167
+ guid = "%s-%s" % (set_type, line[0])
168
+ text_a = line[8]
169
+ text_b = line[9]
170
+ label = line[-1]
171
+ examples.append(
172
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
173
+ return examples
174
+
175
+
176
+ class MnliMismatchedProcessor(MnliProcessor):
177
+ """Processor for the MultiNLI Mismatched data set (GLUE version)."""
178
+
179
+ def get_dev_examples(self, data_dir):
180
+ """See base class."""
181
+ return self._create_examples(
182
+ self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")),
183
+ "dev_matched")
184
+
185
+
186
+ class ColaProcessor(DataProcessor):
187
+ """Processor for the CoLA data set (GLUE version)."""
188
+
189
+ def get_train_examples(self, data_dir):
190
+ """See base class."""
191
+ return self._create_examples(
192
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
193
+
194
+ def get_dev_examples(self, data_dir):
195
+ """See base class."""
196
+ return self._create_examples(
197
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
198
+
199
+ def get_labels(self):
200
+ """See base class."""
201
+ return ["0", "1"]
202
+
203
+ def _create_examples(self, lines, set_type):
204
+ """Creates examples for the training and dev sets."""
205
+ examples = []
206
+ for (i, line) in enumerate(lines):
207
+ guid = "%s-%s" % (set_type, i)
208
+ text_a = line[3]
209
+ label = line[1]
210
+ examples.append(
211
+ InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
212
+ return examples
213
+
214
+
215
+ class Sst2Processor(DataProcessor):
216
+ """Processor for the SST-2 data set (GLUE version)."""
217
+
218
+ def get_train_examples(self, data_dir):
219
+ """See base class."""
220
+ return self._create_examples(
221
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
222
+
223
+ def get_dev_examples(self, data_dir):
224
+ """See base class."""
225
+ return self._create_examples(
226
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
227
+
228
+ def get_labels(self):
229
+ """See base class."""
230
+ return ["0", "1"]
231
+
232
+ def _create_examples(self, lines, set_type):
233
+ """Creates examples for the training and dev sets."""
234
+ examples = []
235
+ for (i, line) in enumerate(lines):
236
+ if i == 0:
237
+ continue
238
+ guid = "%s-%s" % (set_type, i)
239
+ text_a = line[0]
240
+ label = line[1]
241
+ examples.append(
242
+ InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
243
+ return examples
244
+
245
+
246
+ class StsbProcessor(DataProcessor):
247
+ """Processor for the STS-B data set (GLUE version)."""
248
+
249
+ def get_train_examples(self, data_dir):
250
+ """See base class."""
251
+ return self._create_examples(
252
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
253
+
254
+ def get_dev_examples(self, data_dir):
255
+ """See base class."""
256
+ return self._create_examples(
257
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
258
+
259
+ def get_labels(self):
260
+ """See base class."""
261
+ return [None]
262
+
263
+ def _create_examples(self, lines, set_type):
264
+ """Creates examples for the training and dev sets."""
265
+ examples = []
266
+ for (i, line) in enumerate(lines):
267
+ if i == 0:
268
+ continue
269
+ guid = "%s-%s" % (set_type, line[0])
270
+ text_a = line[7]
271
+ text_b = line[8]
272
+ label = line[-1]
273
+ examples.append(
274
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
275
+ return examples
276
+
277
+
278
+ class QqpProcessor(DataProcessor):
279
+ """Processor for the STS-B data set (GLUE version)."""
280
+
281
+ def get_train_examples(self, data_dir):
282
+ """See base class."""
283
+ return self._create_examples(
284
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
285
+
286
+ def get_dev_examples(self, data_dir):
287
+ """See base class."""
288
+ return self._create_examples(
289
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
290
+
291
+ def get_labels(self):
292
+ """See base class."""
293
+ return ["0", "1"]
294
+
295
+ def _create_examples(self, lines, set_type):
296
+ """Creates examples for the training and dev sets."""
297
+ examples = []
298
+ for (i, line) in enumerate(lines):
299
+ if i == 0:
300
+ continue
301
+ guid = "%s-%s" % (set_type, line[0])
302
+ try:
303
+ text_a = line[3]
304
+ text_b = line[4]
305
+ label = line[5]
306
+ except IndexError:
307
+ continue
308
+ examples.append(
309
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
310
+ return examples
311
+
312
+
313
+ class QnliProcessor(DataProcessor):
314
+ """Processor for the STS-B data set (GLUE version)."""
315
+
316
+ def get_train_examples(self, data_dir):
317
+ """See base class."""
318
+ return self._create_examples(
319
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
320
+
321
+ def get_dev_examples(self, data_dir):
322
+ """See base class."""
323
+ return self._create_examples(
324
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")),
325
+ "dev_matched")
326
+
327
+ def get_labels(self):
328
+ """See base class."""
329
+ return ["entailment", "not_entailment"]
330
+
331
+ def _create_examples(self, lines, set_type):
332
+ """Creates examples for the training and dev sets."""
333
+ examples = []
334
+ for (i, line) in enumerate(lines):
335
+ if i == 0:
336
+ continue
337
+ guid = "%s-%s" % (set_type, line[0])
338
+ text_a = line[1]
339
+ text_b = line[2]
340
+ label = line[-1]
341
+ examples.append(
342
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
343
+ return examples
344
+
345
+
346
+ class RteProcessor(DataProcessor):
347
+ """Processor for the RTE data set (GLUE version)."""
348
+
349
+ def get_train_examples(self, data_dir):
350
+ """See base class."""
351
+ return self._create_examples(
352
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
353
+
354
+ def get_dev_examples(self, data_dir):
355
+ """See base class."""
356
+ return self._create_examples(
357
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
358
+
359
+ def get_labels(self):
360
+ """See base class."""
361
+ return ["entailment", "not_entailment"]
362
+
363
+ def _create_examples(self, lines, set_type):
364
+ """Creates examples for the training and dev sets."""
365
+ examples = []
366
+ for (i, line) in enumerate(lines):
367
+ if i == 0:
368
+ continue
369
+ guid = "%s-%s" % (set_type, line[0])
370
+ text_a = line[1]
371
+ text_b = line[2]
372
+ label = line[-1]
373
+ examples.append(
374
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
375
+ return examples
376
+
377
+
378
+ class WnliProcessor(DataProcessor):
379
+ """Processor for the WNLI data set (GLUE version)."""
380
+
381
+ def get_train_examples(self, data_dir):
382
+ """See base class."""
383
+ return self._create_examples(
384
+ self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
385
+
386
+ def get_dev_examples(self, data_dir):
387
+ """See base class."""
388
+ return self._create_examples(
389
+ self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
390
+
391
+ def get_labels(self):
392
+ """See base class."""
393
+ return ["0", "1"]
394
+
395
+ def _create_examples(self, lines, set_type):
396
+ """Creates examples for the training and dev sets."""
397
+ examples = []
398
+ for (i, line) in enumerate(lines):
399
+ if i == 0:
400
+ continue
401
+ guid = "%s-%s" % (set_type, line[0])
402
+ text_a = line[1]
403
+ text_b = line[2]
404
+ label = line[-1]
405
+ examples.append(
406
+ InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
407
+ return examples
408
+
409
+
410
+ def convert_examples_to_features(examples, label_list, max_seq_length,
411
+ tokenizer, output_mode):
412
+ """Loads a data file into a list of `InputBatch`s."""
413
+
414
+ label_map = {label : i for i, label in enumerate(label_list)}
415
+
416
+ features = []
417
+ for (ex_index, example) in enumerate(examples):
418
+ if ex_index % 10000 == 0:
419
+ logger.info("Writing example %d of %d" % (ex_index, len(examples)))
420
+
421
+ tokens_a = tokenizer.tokenize(example.text_a)
422
+
423
+ tokens_b = None
424
+ if example.text_b:
425
+ tokens_b = tokenizer.tokenize(example.text_b)
426
+ # Modifies `tokens_a` and `tokens_b` in place so that the total
427
+ # length is less than the specified length.
428
+ # Account for [CLS], [SEP], [SEP] with "- 3"
429
+ _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
430
+ else:
431
+ # Account for [CLS] and [SEP] with "- 2"
432
+ if len(tokens_a) > max_seq_length - 2:
433
+ tokens_a = tokens_a[:(max_seq_length - 2)]
434
+
435
+ # The convention in BERT is:
436
+ # (a) For sequence pairs:
437
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
438
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
439
+ # (b) For single sequences:
440
+ # tokens: [CLS] the dog is hairy . [SEP]
441
+ # type_ids: 0 0 0 0 0 0 0
442
+ #
443
+ # Where "type_ids" are used to indicate whether this is the first
444
+ # sequence or the second sequence. The embedding vectors for `type=0` and
445
+ # `type=1` were learned during pre-training and are added to the wordpiece
446
+ # embedding vector (and position vector). This is not *strictly* necessary
447
+ # since the [SEP] token unambiguously separates the sequences, but it makes
448
+ # it easier for the model to learn the concept of sequences.
449
+ #
450
+ # For classification tasks, the first vector (corresponding to [CLS]) is
451
+ # used as as the "sentence vector". Note that this only makes sense because
452
+ # the entire model is fine-tuned.
453
+ tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
454
+ segment_ids = [0] * len(tokens)
455
+
456
+ if tokens_b:
457
+ tokens += tokens_b + ["[SEP]"]
458
+ segment_ids += [1] * (len(tokens_b) + 1)
459
+
460
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
461
+
462
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
463
+ # tokens are attended to.
464
+ input_mask = [1] * len(input_ids)
465
+
466
+ # Zero-pad up to the sequence length.
467
+ padding = [0] * (max_seq_length - len(input_ids))
468
+ input_ids += padding
469
+ input_mask += padding
470
+ segment_ids += padding
471
+
472
+ assert len(input_ids) == max_seq_length
473
+ assert len(input_mask) == max_seq_length
474
+ assert len(segment_ids) == max_seq_length
475
+
476
+ if output_mode == "classification":
477
+ label_id = label_map[example.label]
478
+ elif output_mode == "regression":
479
+ label_id = float(example.label)
480
+ else:
481
+ raise KeyError(output_mode)
482
+
483
+ if ex_index < 5:
484
+ logger.info("*** Example ***")
485
+ logger.info("guid: %s" % (example.guid))
486
+ logger.info("tokens: %s" % " ".join(
487
+ [str(x) for x in tokens]))
488
+ logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
489
+ logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
490
+ logger.info(
491
+ "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
492
+ logger.info("label: %s (id = %d)" % (example.label, label_id))
493
+
494
+ features.append(
495
+ InputFeatures(input_ids=input_ids,
496
+ input_mask=input_mask,
497
+ segment_ids=segment_ids,
498
+ label_id=label_id))
499
+ return features
500
+
501
+
502
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
503
+ """Truncates a sequence pair in place to the maximum length."""
504
+
505
+ # This is a simple heuristic which will always truncate the longer sequence
506
+ # one token at a time. This makes more sense than truncating an equal percent
507
+ # of tokens from each, since if one sequence is very short then each token
508
+ # that's truncated likely contains more information than a longer sequence.
509
+ while True:
510
+ total_length = len(tokens_a) + len(tokens_b)
511
+ if total_length <= max_length:
512
+ break
513
+ if len(tokens_a) > len(tokens_b):
514
+ tokens_a.pop()
515
+ else:
516
+ tokens_b.pop()
517
+
518
+
519
+ def simple_accuracy(preds, labels):
520
+ return (preds == labels).mean()
521
+
522
+
523
+ def acc_and_f1(preds, labels):
524
+ acc = simple_accuracy(preds, labels)
525
+ f1 = f1_score(y_true=labels, y_pred=preds)
526
+ return {
527
+ "acc": acc,
528
+ "f1": f1,
529
+ "acc_and_f1": (acc + f1) / 2,
530
+ }
531
+
532
+
533
+ def pearson_and_spearman(preds, labels):
534
+ pearson_corr = pearsonr(preds, labels)[0]
535
+ spearman_corr = spearmanr(preds, labels)[0]
536
+ return {
537
+ "pearson": pearson_corr,
538
+ "spearmanr": spearman_corr,
539
+ "corr": (pearson_corr + spearman_corr) / 2,
540
+ }
541
+
542
+
543
+ def compute_metrics(task_name, preds, labels):
544
+ assert len(preds) == len(labels)
545
+ if task_name == "cola":
546
+ return {"mcc": matthews_corrcoef(labels, preds)}
547
+ elif task_name == "sst-2":
548
+ return {"acc": simple_accuracy(preds, labels)}
549
+ elif task_name == "mrpc":
550
+ return acc_and_f1(preds, labels)
551
+ elif task_name == "sts-b":
552
+ return pearson_and_spearman(preds, labels)
553
+ elif task_name == "qqp":
554
+ return acc_and_f1(preds, labels)
555
+ elif task_name == "mnli":
556
+ return {"acc": simple_accuracy(preds, labels)}
557
+ elif task_name == "mnli-mm":
558
+ return {"acc": simple_accuracy(preds, labels)}
559
+ elif task_name == "qnli":
560
+ return {"acc": simple_accuracy(preds, labels)}
561
+ elif task_name == "rte":
562
+ return {"acc": simple_accuracy(preds, labels)}
563
+ elif task_name == "wnli":
564
+ return {"acc": simple_accuracy(preds, labels)}
565
+ else:
566
+ raise KeyError(task_name)
567
+
568
+
569
+ def main():
570
+ parser = argparse.ArgumentParser()
571
+
572
+ ## Required parameters
573
+ parser.add_argument("--data_dir",
574
+ default=None,
575
+ type=str,
576
+ required=True,
577
+ help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
578
+ parser.add_argument("--bert_model", default=None, type=str, required=True,
579
+ help="Bert pre-trained model selected in the list: bert-base-uncased, "
580
+ "bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
581
+ "bert-base-multilingual-cased, bert-base-chinese.")
582
+ parser.add_argument("--task_name",
583
+ default=None,
584
+ type=str,
585
+ required=True,
586
+ help="The name of the task to train.")
587
+ parser.add_argument("--output_dir",
588
+ default=None,
589
+ type=str,
590
+ required=True,
591
+ help="The output directory where the model predictions and checkpoints will be written.")
592
+
593
+ ## Other parameters
594
+ parser.add_argument("--cache_dir",
595
+ default="",
596
+ type=str,
597
+ help="Where do you want to store the pre-trained models downloaded from s3")
598
+ parser.add_argument("--max_seq_length",
599
+ default=128,
600
+ type=int,
601
+ help="The maximum total input sequence length after WordPiece tokenization. \n"
602
+ "Sequences longer than this will be truncated, and sequences shorter \n"
603
+ "than this will be padded.")
604
+ parser.add_argument("--do_train",
605
+ action='store_true',
606
+ help="Whether to run training.")
607
+ parser.add_argument("--do_eval",
608
+ action='store_true',
609
+ help="Whether to run eval on the dev set.")
610
+ parser.add_argument("--do_lower_case",
611
+ action='store_true',
612
+ help="Set this flag if you are using an uncased model.")
613
+ parser.add_argument("--train_batch_size",
614
+ default=32,
615
+ type=int,
616
+ help="Total batch size for training.")
617
+ parser.add_argument("--eval_batch_size",
618
+ default=8,
619
+ type=int,
620
+ help="Total batch size for eval.")
621
+ parser.add_argument("--learning_rate",
622
+ default=5e-5,
623
+ type=float,
624
+ help="The initial learning rate for Adam.")
625
+ parser.add_argument("--num_train_epochs",
626
+ default=3.0,
627
+ type=float,
628
+ help="Total number of training epochs to perform.")
629
+ parser.add_argument("--warmup_proportion",
630
+ default=0.1,
631
+ type=float,
632
+ help="Proportion of training to perform linear learning rate warmup for. "
633
+ "E.g., 0.1 = 10%% of training.")
634
+ parser.add_argument("--no_cuda",
635
+ action='store_true',
636
+ help="Whether not to use CUDA when available")
637
+ parser.add_argument("--local_rank",
638
+ type=int,
639
+ default=-1,
640
+ help="local_rank for distributed training on gpus")
641
+ parser.add_argument('--seed',
642
+ type=int,
643
+ default=42,
644
+ help="random seed for initialization")
645
+ parser.add_argument('--gradient_accumulation_steps',
646
+ type=int,
647
+ default=1,
648
+ help="Number of updates steps to accumulate before performing a backward/update pass.")
649
+ parser.add_argument('--fp16',
650
+ action='store_true',
651
+ help="Whether to use 16-bit float precision instead of 32-bit")
652
+ parser.add_argument('--loss_scale',
653
+ type=float, default=0,
654
+ help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
655
+ "0 (default value): dynamic loss scaling.\n"
656
+ "Positive power of 2: static loss scaling value.\n")
657
+ parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.")
658
+ parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.")
659
+ args = parser.parse_args()
660
+
661
+ if args.server_ip and args.server_port:
662
+ # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
663
+ import ptvsd
664
+ print("Waiting for debugger attach")
665
+ ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
666
+ ptvsd.wait_for_attach()
667
+
668
+ processors = {
669
+ "cola": ColaProcessor,
670
+ "mnli": MnliProcessor,
671
+ "mnli-mm": MnliMismatchedProcessor,
672
+ "mrpc": MrpcProcessor,
673
+ "sst-2": Sst2Processor,
674
+ "sts-b": StsbProcessor,
675
+ "qqp": QqpProcessor,
676
+ "qnli": QnliProcessor,
677
+ "rte": RteProcessor,
678
+ "wnli": WnliProcessor,
679
+ }
680
+
681
+ output_modes = {
682
+ "cola": "classification",
683
+ "mnli": "classification",
684
+ "mrpc": "classification",
685
+ "sst-2": "classification",
686
+ "sts-b": "regression",
687
+ "qqp": "classification",
688
+ "qnli": "classification",
689
+ "rte": "classification",
690
+ "wnli": "classification",
691
+ }
692
+
693
+ if args.local_rank == -1 or args.no_cuda:
694
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
695
+ n_gpu = torch.cuda.device_count()
696
+ else:
697
+ torch.cuda.set_device(args.local_rank)
698
+ device = torch.device("cuda", args.local_rank)
699
+ n_gpu = 1
700
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
701
+ torch.distributed.init_process_group(backend='nccl')
702
+
703
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
704
+ datefmt = '%m/%d/%Y %H:%M:%S',
705
+ level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
706
+
707
+ logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
708
+ device, n_gpu, bool(args.local_rank != -1), args.fp16))
709
+
710
+ if args.gradient_accumulation_steps < 1:
711
+ raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
712
+ args.gradient_accumulation_steps))
713
+
714
+ args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
715
+
716
+ random.seed(args.seed)
717
+ np.random.seed(args.seed)
718
+ torch.manual_seed(args.seed)
719
+ if n_gpu > 0:
720
+ torch.cuda.manual_seed_all(args.seed)
721
+
722
+ if not args.do_train and not args.do_eval:
723
+ raise ValueError("At least one of `do_train` or `do_eval` must be True.")
724
+
725
+ if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:
726
+ raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
727
+ if not os.path.exists(args.output_dir):
728
+ os.makedirs(args.output_dir)
729
+
730
+ task_name = args.task_name.lower()
731
+
732
+ if task_name not in processors:
733
+ raise ValueError("Task not found: %s" % (task_name))
734
+
735
+ processor = processors[task_name]()
736
+ output_mode = output_modes[task_name]
737
+
738
+ label_list = processor.get_labels()
739
+ num_labels = len(label_list)
740
+
741
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
742
+
743
+ train_examples = None
744
+ num_train_optimization_steps = None
745
+ if args.do_train:
746
+ train_examples = processor.get_train_examples(args.data_dir)
747
+ num_train_optimization_steps = int(
748
+ len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs
749
+ if args.local_rank != -1:
750
+ num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
751
+
752
+ # Prepare model
753
+ cache_dir = args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(args.local_rank))
754
+ model = BertForSequenceClassification.from_pretrained(args.bert_model,
755
+ cache_dir=cache_dir,
756
+ num_labels=num_labels)
757
+
758
+ ### RANDOM INITIALIZATION ####
759
+ # config = BertConfig.from_dict({
760
+ # "attention_probs_dropout_prob": 0.1,
761
+ # "hidden_act": "gelu",
762
+ # "hidden_dropout_prob": 0.1,
763
+ # "hidden_size": 768,
764
+ # "initializer_range": 0.02,
765
+ # "intermediate_size": 3072,
766
+ # "max_position_embeddings": 512,
767
+ # "num_attention_heads": 12,
768
+ # "num_hidden_layers": 12,
769
+ # "type_vocab_size": 2,
770
+ # "vocab_size": 30522
771
+ # })
772
+ # model = BertForSequenceClassification(config=config, num_labels=num_labels)
773
+
774
+
775
+ ###############################
776
+
777
+ if args.fp16:
778
+ model.half()
779
+ model.to(device)
780
+ if args.local_rank != -1:
781
+ try:
782
+ from apex.parallel import DistributedDataParallel as DDP
783
+ except ImportError:
784
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
785
+
786
+ model = DDP(model)
787
+ elif n_gpu > 1:
788
+ model = torch.nn.DataParallel(model)
789
+
790
+ # Prepare optimizer
791
+ param_optimizer = list(model.named_parameters())
792
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
793
+ optimizer_grouped_parameters = [
794
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
795
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
796
+ ]
797
+ if args.fp16:
798
+ try:
799
+ from apex.optimizers import FP16_Optimizer
800
+ from apex.optimizers import FusedAdam
801
+ except ImportError:
802
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
803
+
804
+ optimizer = FusedAdam(optimizer_grouped_parameters,
805
+ lr=args.learning_rate,
806
+ bias_correction=False,
807
+ max_grad_norm=1.0)
808
+ if args.loss_scale == 0:
809
+ optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
810
+ else:
811
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
812
+
813
+ else:
814
+ optimizer = BertAdam(optimizer_grouped_parameters,
815
+ lr=args.learning_rate,
816
+ warmup=args.warmup_proportion,
817
+ t_total=num_train_optimization_steps)
818
+
819
+ global_step = 0
820
+ nb_tr_steps = 0
821
+ tr_loss = 0
822
+ if args.do_train:
823
+ train_features = convert_examples_to_features(
824
+ train_examples, label_list, args.max_seq_length, tokenizer, output_mode)
825
+ logger.info("***** Running training *****")
826
+ logger.info(" Num examples = %d", len(train_examples))
827
+ logger.info(" Batch size = %d", args.train_batch_size)
828
+ logger.info(" Num steps = %d", num_train_optimization_steps)
829
+ all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
830
+ all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
831
+ all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
832
+
833
+ if output_mode == "classification":
834
+ all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)
835
+ elif output_mode == "regression":
836
+ all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.float)
837
+
838
+ train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
839
+ if args.local_rank == -1:
840
+ train_sampler = RandomSampler(train_data)
841
+ else:
842
+ train_sampler = DistributedSampler(train_data)
843
+ train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
844
+
845
+ model.train()
846
+ for _ in trange(int(args.num_train_epochs), desc="Epoch"):
847
+ tr_loss = 0
848
+ nb_tr_examples, nb_tr_steps = 0, 0
849
+ for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
850
+ batch = tuple(t.to(device) for t in batch)
851
+ input_ids, input_mask, segment_ids, label_ids = batch
852
+
853
+ # define a new function to compute loss values for both output_modes
854
+ logits, _ = model(input_ids, segment_ids, input_mask, labels=None)
855
+
856
+ if output_mode == "classification":
857
+ loss_fct = CrossEntropyLoss()
858
+ loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))
859
+ elif output_mode == "regression":
860
+ loss_fct = MSELoss()
861
+ loss = loss_fct(logits.view(-1), label_ids.view(-1))
862
+
863
+ if n_gpu > 1:
864
+ loss = loss.mean() # mean() to average on multi-gpu.
865
+ if args.gradient_accumulation_steps > 1:
866
+ loss = loss / args.gradient_accumulation_steps
867
+
868
+ if args.fp16:
869
+ optimizer.backward(loss)
870
+ else:
871
+ loss.backward()
872
+
873
+ tr_loss += loss.item()
874
+ print(loss.item())
875
+ nb_tr_examples += input_ids.size(0)
876
+ nb_tr_steps += 1
877
+ if (step + 1) % args.gradient_accumulation_steps == 0:
878
+ if args.fp16:
879
+ # modify learning rate with special warm up BERT uses
880
+ # if args.fp16 is False, BertAdam is used that handles this automatically
881
+ lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)
882
+ for param_group in optimizer.param_groups:
883
+ param_group['lr'] = lr_this_step
884
+ optimizer.step()
885
+ optimizer.zero_grad()
886
+ global_step += 1
887
+
888
+ if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
889
+ # Save a trained model, configuration and tokenizer
890
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
891
+
892
+ # If we save using the predefined names, we can load using `from_pretrained`
893
+ output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)
894
+ output_config_file = os.path.join(args.output_dir, CONFIG_NAME)
895
+
896
+ torch.save(model_to_save.state_dict(), output_model_file)
897
+ model_to_save.config.to_json_file(output_config_file)
898
+ tokenizer.save_vocabulary(args.output_dir)
899
+
900
+ # Load a trained model and vocabulary that you have fine-tuned
901
+ model = BertForSequenceClassification.from_pretrained(args.output_dir, num_labels=num_labels)
902
+ tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
903
+ else:
904
+ model = BertForSequenceClassification.from_pretrained(args.bert_model, num_labels=num_labels)
905
+ model.to(device)
906
+
907
+ if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
908
+ eval_examples = processor.get_dev_examples(args.data_dir)
909
+ eval_features = convert_examples_to_features(
910
+ eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)
911
+ logger.info("***** Running evaluation *****")
912
+ logger.info(" Num examples = %d", len(eval_examples))
913
+ logger.info(" Batch size = %d", args.eval_batch_size)
914
+ all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
915
+ all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
916
+ all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
917
+
918
+ if output_mode == "classification":
919
+ all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)
920
+ elif output_mode == "regression":
921
+ all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.float)
922
+
923
+ eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
924
+ # Run prediction for full data
925
+ eval_sampler = SequentialSampler(eval_data)
926
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
927
+
928
+ model.eval()
929
+ eval_loss = 0
930
+ nb_eval_steps = 0
931
+ preds = []
932
+
933
+ for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating"):
934
+ input_ids = input_ids.to(device)
935
+ input_mask = input_mask.to(device)
936
+ segment_ids = segment_ids.to(device)
937
+ label_ids = label_ids.to(device)
938
+
939
+ with torch.no_grad():
940
+ logits, attns = model(input_ids, segment_ids, input_mask, labels=None)
941
+
942
+ # create eval loss and other metric required by the task
943
+ if output_mode == "classification":
944
+ loss_fct = CrossEntropyLoss()
945
+ tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))
946
+ elif output_mode == "regression":
947
+ loss_fct = MSELoss()
948
+ tmp_eval_loss = loss_fct(logits.view(-1), label_ids.view(-1))
949
+
950
+ eval_loss += tmp_eval_loss.mean().item()
951
+ nb_eval_steps += 1
952
+ if len(preds) == 0:
953
+ preds.append(logits.detach().cpu().numpy())
954
+ else:
955
+ preds[0] = np.append(preds[0], logits.detach().cpu().numpy(), axis=0)
956
+
957
+ eval_loss = eval_loss / nb_eval_steps
958
+ preds = preds[0]
959
+ if output_mode == "classification":
960
+ preds = np.argmax(preds, axis=1)
961
+ elif output_mode == "regression":
962
+ preds = np.squeeze(preds)
963
+ result = compute_metrics(task_name, preds, all_label_ids.numpy())
964
+ loss = tr_loss/nb_tr_steps if args.do_train else None
965
+
966
+ result['eval_loss'] = eval_loss
967
+ result['global_step'] = global_step
968
+ result['loss'] = loss
969
+
970
+ output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
971
+ with open(output_eval_file, "w") as writer:
972
+ logger.info("***** Eval results *****")
973
+ for key in sorted(result.keys()):
974
+ logger.info(" %s = %s", key, str(result[key]))
975
+ writer.write("%s = %s\n" % (key, str(result[key])))
976
+
977
+ # hack for MNLI-MM
978
+ if task_name == "mnli":
979
+ task_name = "mnli-mm"
980
+ processor = processors[task_name]()
981
+
982
+ if os.path.exists(args.output_dir + '-MM') and os.listdir(args.output_dir + '-MM') and args.do_train:
983
+ raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
984
+ if not os.path.exists(args.output_dir + '-MM'):
985
+ os.makedirs(args.output_dir + '-MM')
986
+
987
+ eval_examples = processor.get_dev_examples(args.data_dir)
988
+ eval_features = convert_examples_to_features(
989
+ eval_examples, label_list, args.max_seq_length, tokenizer, output_mode)
990
+ logger.info("***** Running evaluation *****")
991
+ logger.info(" Num examples = %d", len(eval_examples))
992
+ logger.info(" Batch size = %d", args.eval_batch_size)
993
+ all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
994
+ all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
995
+ all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
996
+ all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)
997
+
998
+ eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
999
+ # Run prediction for full data
1000
+ eval_sampler = SequentialSampler(eval_data)
1001
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
1002
+
1003
+ model.eval()
1004
+ eval_loss = 0
1005
+ nb_eval_steps = 0
1006
+ preds = []
1007
+
1008
+ for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating"):
1009
+ input_ids = input_ids.to(device)
1010
+ input_mask = input_mask.to(device)
1011
+ segment_ids = segment_ids.to(device)
1012
+ label_ids = label_ids.to(device)
1013
+
1014
+ with torch.no_grad():
1015
+ logits = model(input_ids, segment_ids, input_mask, labels=None)
1016
+
1017
+ loss_fct = CrossEntropyLoss()
1018
+ tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))
1019
+
1020
+ eval_loss += tmp_eval_loss.mean().item()
1021
+ nb_eval_steps += 1
1022
+ if len(preds) == 0:
1023
+ preds.append(logits.detach().cpu().numpy())
1024
+ else:
1025
+ preds[0] = np.append(
1026
+ preds[0], logits.detach().cpu().numpy(), axis=0)
1027
+
1028
+ eval_loss = eval_loss / nb_eval_steps
1029
+ preds = preds[0]
1030
+ preds = np.argmax(preds, axis=1)
1031
+ result = compute_metrics(task_name, preds, all_label_ids.numpy())
1032
+ loss = tr_loss/nb_tr_steps if args.do_train else None
1033
+
1034
+ result['eval_loss'] = eval_loss
1035
+ result['global_step'] = global_step
1036
+ result['loss'] = loss
1037
+
1038
+ output_eval_file = os.path.join(args.output_dir + '-MM', "eval_results.txt")
1039
+ with open(output_eval_file, "w") as writer:
1040
+ logger.info("***** Eval results *****")
1041
+ for key in sorted(result.keys()):
1042
+ logger.info(" %s = %s", key, str(result[key]))
1043
+ writer.write("%s = %s\n" % (key, str(result[key])))
1044
+
1045
+
1046
+ if __name__ == "__main__":
1047
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_gpt2.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import logging
5
+ from tqdm import trange
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import numpy as np
10
+
11
+ from pytorch_pretrained_bert import GPT2LMHeadModel, GPT2Tokenizer
12
+
13
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
14
+ datefmt = '%m/%d/%Y %H:%M:%S',
15
+ level = logging.INFO)
16
+ logger = logging.getLogger(__name__)
17
+
18
+ def top_k_logits(logits, k):
19
+ """
20
+ Masks everything but the k top entries as -infinity (1e10).
21
+ Used to mask logits such that e^-infinity -> 0 won't contribute to the
22
+ sum of the denominator.
23
+ """
24
+ if k == 0:
25
+ return logits
26
+ else:
27
+ values = torch.topk(logits, k)[0]
28
+ batch_mins = values[:, -1].view(-1, 1).expand_as(logits)
29
+ return torch.where(logits < batch_mins, torch.ones_like(logits) * -1e10, logits)
30
+
31
+ def sample_sequence(model, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0, device='cuda', sample=True):
32
+ if start_token is None:
33
+ assert context is not None, 'Specify exactly one of start_token and context!'
34
+ context = torch.tensor(context, device=device, dtype=torch.long).unsqueeze(0).repeat(batch_size, 1)
35
+ else:
36
+ assert context is None, 'Specify exactly one of start_token and context!'
37
+ context = torch.full((batch_size, 1), start_token, device=device, dtype=torch.long)
38
+ prev = context
39
+ output = context
40
+ past = None
41
+ with torch.no_grad():
42
+ for i in trange(length):
43
+ logits, past = model(prev, past=past)
44
+ logits = logits[:, -1, :] / temperature
45
+ logits = top_k_logits(logits, k=top_k)
46
+ log_probs = F.softmax(logits, dim=-1)
47
+ if sample:
48
+ prev = torch.multinomial(log_probs, num_samples=1)
49
+ else:
50
+ _, prev = torch.topk(log_probs, k=1, dim=-1)
51
+ output = torch.cat((output, prev), dim=1)
52
+ return output
53
+
54
+ def run_model():
55
+ parser = argparse.ArgumentParser()
56
+ parser.add_argument('--model_name_or_path', type=str, default='gpt2', help='pretrained model name or path to local checkpoint')
57
+ parser.add_argument("--seed", type=int, default=0)
58
+ parser.add_argument("--nsamples", type=int, default=1)
59
+ parser.add_argument("--batch_size", type=int, default=-1)
60
+ parser.add_argument("--length", type=int, default=-1)
61
+ parser.add_argument("--temperature", type=float, default=1.0)
62
+ parser.add_argument("--top_k", type=int, default=0)
63
+ parser.add_argument('--unconditional', action='store_true', help='If true, unconditional generation.')
64
+ args = parser.parse_args()
65
+ print(args)
66
+
67
+ if args.batch_size == -1:
68
+ args.batch_size = 1
69
+ assert args.nsamples % args.batch_size == 0
70
+
71
+ np.random.seed(args.seed)
72
+ torch.random.manual_seed(args.seed)
73
+ torch.cuda.manual_seed(args.seed)
74
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
75
+
76
+ enc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
77
+ model = GPT2LMHeadModel.from_pretrained(args.model_name_or_path)
78
+ model.to(device)
79
+ model.eval()
80
+
81
+ if args.length == -1:
82
+ args.length = model.config.n_ctx // 2
83
+ elif args.length > model.config.n_ctx:
84
+ raise ValueError("Can't get samples longer than window size: %s" % model.config.n_ctx)
85
+
86
+ while True:
87
+ context_tokens = []
88
+ if not args.unconditional:
89
+ raw_text = input("Model prompt >>> ")
90
+ while not raw_text:
91
+ print('Prompt should not be empty!')
92
+ raw_text = input("Model prompt >>> ")
93
+ context_tokens = enc.encode(raw_text)
94
+ generated = 0
95
+ for _ in range(args.nsamples // args.batch_size):
96
+ out = sample_sequence(
97
+ model=model, length=args.length,
98
+ context=context_tokens,
99
+ start_token=None,
100
+ batch_size=args.batch_size,
101
+ temperature=args.temperature, top_k=args.top_k, device=device
102
+ )
103
+ out = out[:, len(context_tokens):].tolist()
104
+ for i in range(args.batch_size):
105
+ generated += 1
106
+ text = enc.decode(out[i])
107
+ print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
108
+ print(text)
109
+ print("=" * 80)
110
+ if args.unconditional:
111
+ generated = 0
112
+ for _ in range(args.nsamples // args.batch_size):
113
+ out = sample_sequence(
114
+ model=model, length=args.length,
115
+ context=None,
116
+ start_token=enc.encoder['<|endoftext|>'],
117
+ batch_size=args.batch_size,
118
+ temperature=args.temperature, top_k=args.top_k, device=device
119
+ )
120
+ out = out[:,1:].tolist()
121
+ for i in range(args.batch_size):
122
+ generated += 1
123
+ text = enc.decode(out[i])
124
+ print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
125
+ print(text)
126
+ print("=" * 80)
127
+ if args.unconditional:
128
+ break
129
+
130
+ if __name__ == '__main__':
131
+ run_model()
132
+
133
+
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_openai_gpt.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ OpenAI GPT model fine-tuning script.
17
+ Adapted from https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/train.py
18
+ It self adapted from https://github.com/openai/finetune-transformer-lm/blob/master/train.py
19
+
20
+ This script with default values fine-tunes and evaluate a pretrained OpenAI GPT on the RocStories dataset:
21
+ python run_openai_gpt.py \
22
+ --model_name openai-gpt \
23
+ --do_train \
24
+ --do_eval \
25
+ --train_dataset $ROC_STORIES_DIR/cloze_test_val__spring2016\ -\ cloze_test_ALL_val.csv \
26
+ --eval_dataset $ROC_STORIES_DIR/cloze_test_test__spring2016\ -\ cloze_test_ALL_test.csv \
27
+ --output_dir ../log \
28
+ --train_batch_size 16 \
29
+ """
30
+ import argparse
31
+ import os
32
+ import csv
33
+ import random
34
+ import logging
35
+ from tqdm import tqdm, trange
36
+
37
+ import numpy as np
38
+ import torch
39
+ from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
40
+ TensorDataset)
41
+
42
+ from pytorch_pretrained_bert import (OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer,
43
+ OpenAIAdam, cached_path, WEIGHTS_NAME, CONFIG_NAME)
44
+
45
+ ROCSTORIES_URL = "https://s3.amazonaws.com/datasets.huggingface.co/ROCStories.tar.gz"
46
+
47
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
48
+ datefmt = '%m/%d/%Y %H:%M:%S',
49
+ level = logging.INFO)
50
+ logger = logging.getLogger(__name__)
51
+
52
+ def accuracy(out, labels):
53
+ outputs = np.argmax(out, axis=1)
54
+ return np.sum(outputs == labels)
55
+
56
+ def load_rocstories_dataset(dataset_path):
57
+ """ Output a list of tuples(story, 1st continuation, 2nd continuation, label) """
58
+ with open(dataset_path, encoding='utf_8') as f:
59
+ f = csv.reader(f)
60
+ output = []
61
+ next(f) # skip the first line
62
+ for line in tqdm(f):
63
+ output.append((' '.join(line[1:5]), line[5], line[6], int(line[-1])-1))
64
+ return output
65
+
66
+ def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token):
67
+ """ Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)
68
+
69
+ To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:
70
+ input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]
71
+ """
72
+ tensor_datasets = []
73
+ for dataset in encoded_datasets:
74
+ n_batch = len(dataset)
75
+ input_ids = np.zeros((n_batch, 2, input_len), dtype=np.int64)
76
+ mc_token_ids = np.zeros((n_batch, 2), dtype=np.int64)
77
+ lm_labels = np.full((n_batch, 2, input_len), fill_value=-1, dtype=np.int64)
78
+ mc_labels = np.zeros((n_batch,), dtype=np.int64)
79
+ for i, (story, cont1, cont2, mc_label), in enumerate(dataset):
80
+ with_cont1 = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]
81
+ with_cont2 = [start_token] + story[:cap_length] + [delimiter_token] + cont2[:cap_length] + [clf_token]
82
+ input_ids[i, 0, :len(with_cont1)] = with_cont1
83
+ input_ids[i, 1, :len(with_cont2)] = with_cont2
84
+ mc_token_ids[i, 0] = len(with_cont1) - 1
85
+ mc_token_ids[i, 1] = len(with_cont2) - 1
86
+ lm_labels[i, 0, :len(with_cont1)-1] = with_cont1[1:]
87
+ lm_labels[i, 1, :len(with_cont2)-1] = with_cont2[1:]
88
+ mc_labels[i] = mc_label
89
+ all_inputs = (input_ids, mc_token_ids, lm_labels, mc_labels)
90
+ tensor_datasets.append(tuple(torch.tensor(t) for t in all_inputs))
91
+ return tensor_datasets
92
+
93
+ def main():
94
+ parser = argparse.ArgumentParser()
95
+ parser.add_argument('--model_name', type=str, default='openai-gpt',
96
+ help='pretrained model name')
97
+ parser.add_argument("--do_train", action='store_true', help="Whether to run training.")
98
+ parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.")
99
+ parser.add_argument("--output_dir", default=None, type=str, required=True,
100
+ help="The output directory where the model predictions and checkpoints will be written.")
101
+ parser.add_argument('--train_dataset', type=str, default='')
102
+ parser.add_argument('--eval_dataset', type=str, default='')
103
+ parser.add_argument('--seed', type=int, default=42)
104
+ parser.add_argument('--num_train_epochs', type=int, default=3)
105
+ parser.add_argument('--train_batch_size', type=int, default=8)
106
+ parser.add_argument('--eval_batch_size', type=int, default=16)
107
+ parser.add_argument('--max_grad_norm', type=int, default=1)
108
+ parser.add_argument('--learning_rate', type=float, default=6.25e-5)
109
+ parser.add_argument('--warmup_proportion', type=float, default=0.002)
110
+ parser.add_argument('--lr_schedule', type=str, default='warmup_linear')
111
+ parser.add_argument('--weight_decay', type=float, default=0.01)
112
+ parser.add_argument('--lm_coef', type=float, default=0.9)
113
+ parser.add_argument('--n_valid', type=int, default=374)
114
+
115
+ parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.")
116
+ parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.")
117
+ args = parser.parse_args()
118
+ print(args)
119
+
120
+ if args.server_ip and args.server_port:
121
+ # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
122
+ import ptvsd
123
+ print("Waiting for debugger attach")
124
+ ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
125
+ ptvsd.wait_for_attach()
126
+
127
+ random.seed(args.seed)
128
+ np.random.seed(args.seed)
129
+ torch.manual_seed(args.seed)
130
+ torch.cuda.manual_seed_all(args.seed)
131
+
132
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
133
+ n_gpu = torch.cuda.device_count()
134
+ logger.info("device: {}, n_gpu {}".format(device, n_gpu))
135
+
136
+ if not args.do_train and not args.do_eval:
137
+ raise ValueError("At least one of `do_train` or `do_eval` must be True.")
138
+
139
+ if not os.path.exists(args.output_dir):
140
+ os.makedirs(args.output_dir)
141
+
142
+ # Load tokenizer and model
143
+ # This loading functions also add new tokens and embeddings called `special tokens`
144
+ # These new embeddings will be fine-tuned on the RocStories dataset
145
+ special_tokens = ['_start_', '_delimiter_', '_classify_']
146
+ tokenizer = OpenAIGPTTokenizer.from_pretrained(args.model_name, special_tokens=special_tokens)
147
+ special_tokens_ids = list(tokenizer.convert_tokens_to_ids(token) for token in special_tokens)
148
+ model = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name, num_special_tokens=len(special_tokens))
149
+ model.to(device)
150
+
151
+ # Load and encode the datasets
152
+ if not args.train_dataset and not args.eval_dataset:
153
+ roc_stories = cached_path(ROCSTORIES_URL)
154
+ def tokenize_and_encode(obj):
155
+ """ Tokenize and encode a nested object """
156
+ if isinstance(obj, str):
157
+ return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj))
158
+ elif isinstance(obj, int):
159
+ return obj
160
+ return list(tokenize_and_encode(o) for o in obj)
161
+ logger.info("Encoding dataset...")
162
+ train_dataset = load_rocstories_dataset(args.train_dataset)
163
+ eval_dataset = load_rocstories_dataset(args.eval_dataset)
164
+ datasets = (train_dataset, eval_dataset)
165
+ encoded_datasets = tokenize_and_encode(datasets)
166
+
167
+ # Compute the max input length for the Transformer
168
+ max_length = model.config.n_positions // 2 - 2
169
+ input_length = max(len(story[:max_length]) + max(len(cont1[:max_length]), len(cont2[:max_length])) + 3 \
170
+ for dataset in encoded_datasets for story, cont1, cont2, _ in dataset)
171
+ input_length = min(input_length, model.config.n_positions) # Max size of input for the pre-trained model
172
+
173
+ # Prepare inputs tensors and dataloaders
174
+ tensor_datasets = pre_process_datasets(encoded_datasets, input_length, max_length, *special_tokens_ids)
175
+ train_tensor_dataset, eval_tensor_dataset = tensor_datasets[0], tensor_datasets[1]
176
+
177
+ train_data = TensorDataset(*train_tensor_dataset)
178
+ train_sampler = RandomSampler(train_data)
179
+ train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
180
+
181
+ eval_data = TensorDataset(*eval_tensor_dataset)
182
+ eval_sampler = SequentialSampler(eval_data)
183
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
184
+
185
+ # Prepare optimizer
186
+ param_optimizer = list(model.named_parameters())
187
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
188
+ optimizer_grouped_parameters = [
189
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
190
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
191
+ ]
192
+ num_train_optimization_steps = len(train_data) * args.num_train_epochs // args.train_batch_size
193
+ optimizer = OpenAIAdam(optimizer_grouped_parameters,
194
+ lr=args.learning_rate,
195
+ warmup=args.warmup_proportion,
196
+ max_grad_norm=args.max_grad_norm,
197
+ weight_decay=args.weight_decay,
198
+ t_total=num_train_optimization_steps)
199
+
200
+ if args.do_train:
201
+ nb_tr_steps, tr_loss, exp_average_loss = 0, 0, None
202
+ model.train()
203
+ for _ in trange(int(args.num_train_epochs), desc="Epoch"):
204
+ tr_loss = 0
205
+ nb_tr_steps = 0
206
+ tqdm_bar = tqdm(train_dataloader, desc="Training")
207
+ for step, batch in enumerate(tqdm_bar):
208
+ batch = tuple(t.to(device) for t in batch)
209
+ input_ids, mc_token_ids, lm_labels, mc_labels = batch
210
+ losses = model(input_ids, mc_token_ids, lm_labels, mc_labels)
211
+ loss = args.lm_coef * losses[0] + losses[1]
212
+ loss.backward()
213
+ optimizer.step()
214
+ optimizer.zero_grad()
215
+ tr_loss += loss.item()
216
+ exp_average_loss = loss.item() if exp_average_loss is None else 0.7*exp_average_loss+0.3*loss.item()
217
+ nb_tr_steps += 1
218
+ tqdm_bar.desc = "Training loss: {:.2e} lr: {:.2e}".format(exp_average_loss, optimizer.get_lr()[0])
219
+
220
+ # Save a trained model
221
+ if args.do_train:
222
+ # Save a trained model, configuration and tokenizer
223
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
224
+
225
+ # If we save using the predefined names, we can load using `from_pretrained`
226
+ output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)
227
+ output_config_file = os.path.join(args.output_dir, CONFIG_NAME)
228
+
229
+ torch.save(model_to_save.state_dict(), output_model_file)
230
+ model_to_save.config.to_json_file(output_config_file)
231
+ tokenizer.save_vocabulary(args.output_dir)
232
+
233
+ # Load a trained model and vocabulary that you have fine-tuned
234
+ model = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir)
235
+ tokenizer = OpenAIGPTTokenizer.from_pretrained(args.output_dir)
236
+ model.to(device)
237
+
238
+ if args.do_eval:
239
+ model.eval()
240
+ eval_loss, eval_accuracy = 0, 0
241
+ nb_eval_steps, nb_eval_examples = 0, 0
242
+ for batch in tqdm(eval_dataloader, desc="Evaluating"):
243
+ batch = tuple(t.to(device) for t in batch)
244
+ input_ids, mc_token_ids, lm_labels, mc_labels = batch
245
+ with torch.no_grad():
246
+ _, mc_loss = model(input_ids, mc_token_ids, lm_labels, mc_labels)
247
+ _, mc_logits = model(input_ids, mc_token_ids)
248
+
249
+ mc_logits = mc_logits.detach().cpu().numpy()
250
+ mc_labels = mc_labels.to('cpu').numpy()
251
+ tmp_eval_accuracy = accuracy(mc_logits, mc_labels)
252
+
253
+ eval_loss += mc_loss.mean().item()
254
+ eval_accuracy += tmp_eval_accuracy
255
+
256
+ nb_eval_examples += input_ids.size(0)
257
+ nb_eval_steps += 1
258
+
259
+ eval_loss = eval_loss / nb_eval_steps
260
+ eval_accuracy = eval_accuracy / nb_eval_examples
261
+ train_loss = tr_loss/nb_tr_steps if args.do_train else None
262
+ result = {'eval_loss': eval_loss,
263
+ 'eval_accuracy': eval_accuracy,
264
+ 'train_loss': train_loss}
265
+
266
+ output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
267
+ with open(output_eval_file, "w") as writer:
268
+ logger.info("***** Eval results *****")
269
+ for key in sorted(result.keys()):
270
+ logger.info(" %s = %s", key, str(result[key]))
271
+ writer.write("%s = %s\n" % (key, str(result[key])))
272
+
273
+ if __name__ == '__main__':
274
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_squad.py ADDED
@@ -0,0 +1,1098 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Run BERT on SQuAD."""
17
+
18
+ from __future__ import absolute_import, division, print_function
19
+
20
+ import argparse
21
+ import collections
22
+ import json
23
+ import logging
24
+ import math
25
+ import os
26
+ import random
27
+ import sys
28
+ from io import open
29
+
30
+ import numpy as np
31
+ import torch
32
+ from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
33
+ TensorDataset)
34
+ from torch.utils.data.distributed import DistributedSampler
35
+ from tqdm import tqdm, trange
36
+
37
+ from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME
38
+ from pytorch_pretrained_bert.modeling import BertForQuestionAnswering, BertConfig
39
+ from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
40
+ from pytorch_pretrained_bert.tokenization import (BasicTokenizer,
41
+ BertTokenizer,
42
+ whitespace_tokenize)
43
+
44
+ if sys.version_info[0] == 2:
45
+ import cPickle as pickle
46
+ else:
47
+ import pickle
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ class SquadExample(object):
53
+ """
54
+ A single training/test example for the Squad dataset.
55
+ For examples without an answer, the start and end position are -1.
56
+ """
57
+
58
+ def __init__(self,
59
+ qas_id,
60
+ question_text,
61
+ doc_tokens,
62
+ orig_answer_text=None,
63
+ start_position=None,
64
+ end_position=None,
65
+ is_impossible=None):
66
+ self.qas_id = qas_id
67
+ self.question_text = question_text
68
+ self.doc_tokens = doc_tokens
69
+ self.orig_answer_text = orig_answer_text
70
+ self.start_position = start_position
71
+ self.end_position = end_position
72
+ self.is_impossible = is_impossible
73
+
74
+ def __str__(self):
75
+ return self.__repr__()
76
+
77
+ def __repr__(self):
78
+ s = ""
79
+ s += "qas_id: %s" % (self.qas_id)
80
+ s += ", question_text: %s" % (
81
+ self.question_text)
82
+ s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
83
+ if self.start_position:
84
+ s += ", start_position: %d" % (self.start_position)
85
+ if self.end_position:
86
+ s += ", end_position: %d" % (self.end_position)
87
+ if self.is_impossible:
88
+ s += ", is_impossible: %r" % (self.is_impossible)
89
+ return s
90
+
91
+
92
+ class InputFeatures(object):
93
+ """A single set of features of data."""
94
+
95
+ def __init__(self,
96
+ unique_id,
97
+ example_index,
98
+ doc_span_index,
99
+ tokens,
100
+ token_to_orig_map,
101
+ token_is_max_context,
102
+ input_ids,
103
+ input_mask,
104
+ segment_ids,
105
+ start_position=None,
106
+ end_position=None,
107
+ is_impossible=None):
108
+ self.unique_id = unique_id
109
+ self.example_index = example_index
110
+ self.doc_span_index = doc_span_index
111
+ self.tokens = tokens
112
+ self.token_to_orig_map = token_to_orig_map
113
+ self.token_is_max_context = token_is_max_context
114
+ self.input_ids = input_ids
115
+ self.input_mask = input_mask
116
+ self.segment_ids = segment_ids
117
+ self.start_position = start_position
118
+ self.end_position = end_position
119
+ self.is_impossible = is_impossible
120
+
121
+
122
+ def read_squad_examples(input_file, is_training, version_2_with_negative):
123
+ """Read a SQuAD json file into a list of SquadExample."""
124
+ with open(input_file, "r", encoding='utf-8') as reader:
125
+ input_data = json.load(reader)["data"]
126
+
127
+ def is_whitespace(c):
128
+ if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
129
+ return True
130
+ return False
131
+
132
+ examples = []
133
+ for entry in input_data:
134
+ for paragraph in entry["paragraphs"]:
135
+ paragraph_text = paragraph["context"]
136
+ doc_tokens = []
137
+ char_to_word_offset = []
138
+ prev_is_whitespace = True
139
+ for c in paragraph_text:
140
+ if is_whitespace(c):
141
+ prev_is_whitespace = True
142
+ else:
143
+ if prev_is_whitespace:
144
+ doc_tokens.append(c)
145
+ else:
146
+ doc_tokens[-1] += c
147
+ prev_is_whitespace = False
148
+ char_to_word_offset.append(len(doc_tokens) - 1)
149
+
150
+ for qa in paragraph["qas"]:
151
+ qas_id = qa["id"]
152
+ question_text = qa["question"]
153
+ start_position = None
154
+ end_position = None
155
+ orig_answer_text = None
156
+ is_impossible = False
157
+ if is_training:
158
+ if version_2_with_negative:
159
+ is_impossible = qa["is_impossible"]
160
+ if (len(qa["answers"]) != 1) and (not is_impossible):
161
+ raise ValueError(
162
+ "For training, each question should have exactly 1 answer.")
163
+ if not is_impossible:
164
+ answer = qa["answers"][0]
165
+ orig_answer_text = answer["text"]
166
+ answer_offset = answer["answer_start"]
167
+ answer_length = len(orig_answer_text)
168
+ start_position = char_to_word_offset[answer_offset]
169
+ end_position = char_to_word_offset[answer_offset + answer_length - 1]
170
+ # Only add answers where the text can be exactly recovered from the
171
+ # document. If this CAN'T happen it's likely due to weird Unicode
172
+ # stuff so we will just skip the example.
173
+ #
174
+ # Note that this means for training mode, every example is NOT
175
+ # guaranteed to be preserved.
176
+ actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
177
+ cleaned_answer_text = " ".join(
178
+ whitespace_tokenize(orig_answer_text))
179
+ if actual_text.find(cleaned_answer_text) == -1:
180
+ logger.warning("Could not find answer: '%s' vs. '%s'",
181
+ actual_text, cleaned_answer_text)
182
+ continue
183
+ else:
184
+ start_position = -1
185
+ end_position = -1
186
+ orig_answer_text = ""
187
+
188
+ example = SquadExample(
189
+ qas_id=qas_id,
190
+ question_text=question_text,
191
+ doc_tokens=doc_tokens,
192
+ orig_answer_text=orig_answer_text,
193
+ start_position=start_position,
194
+ end_position=end_position,
195
+ is_impossible=is_impossible)
196
+ examples.append(example)
197
+ return examples
198
+
199
+
200
+ def convert_examples_to_features(examples, tokenizer, max_seq_length,
201
+ doc_stride, max_query_length, is_training):
202
+ """Loads a data file into a list of `InputBatch`s."""
203
+
204
+ unique_id = 1000000000
205
+
206
+ features = []
207
+ for (example_index, example) in enumerate(examples):
208
+ query_tokens = tokenizer.tokenize(example.question_text)
209
+
210
+ if len(query_tokens) > max_query_length:
211
+ query_tokens = query_tokens[0:max_query_length]
212
+
213
+ tok_to_orig_index = []
214
+ orig_to_tok_index = []
215
+ all_doc_tokens = []
216
+ for (i, token) in enumerate(example.doc_tokens):
217
+ orig_to_tok_index.append(len(all_doc_tokens))
218
+ sub_tokens = tokenizer.tokenize(token)
219
+ for sub_token in sub_tokens:
220
+ tok_to_orig_index.append(i)
221
+ all_doc_tokens.append(sub_token)
222
+
223
+ tok_start_position = None
224
+ tok_end_position = None
225
+ if is_training and example.is_impossible:
226
+ tok_start_position = -1
227
+ tok_end_position = -1
228
+ if is_training and not example.is_impossible:
229
+ tok_start_position = orig_to_tok_index[example.start_position]
230
+ if example.end_position < len(example.doc_tokens) - 1:
231
+ tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
232
+ else:
233
+ tok_end_position = len(all_doc_tokens) - 1
234
+ (tok_start_position, tok_end_position) = _improve_answer_span(
235
+ all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
236
+ example.orig_answer_text)
237
+
238
+ # The -3 accounts for [CLS], [SEP] and [SEP]
239
+ max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
240
+
241
+ # We can have documents that are longer than the maximum sequence length.
242
+ # To deal with this we do a sliding window approach, where we take chunks
243
+ # of the up to our max length with a stride of `doc_stride`.
244
+ _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
245
+ "DocSpan", ["start", "length"])
246
+ doc_spans = []
247
+ start_offset = 0
248
+ while start_offset < len(all_doc_tokens):
249
+ length = len(all_doc_tokens) - start_offset
250
+ if length > max_tokens_for_doc:
251
+ length = max_tokens_for_doc
252
+ doc_spans.append(_DocSpan(start=start_offset, length=length))
253
+ if start_offset + length == len(all_doc_tokens):
254
+ break
255
+ start_offset += min(length, doc_stride)
256
+
257
+ for (doc_span_index, doc_span) in enumerate(doc_spans):
258
+ tokens = []
259
+ token_to_orig_map = {}
260
+ token_is_max_context = {}
261
+ segment_ids = []
262
+ tokens.append("[CLS]")
263
+ segment_ids.append(0)
264
+ for token in query_tokens:
265
+ tokens.append(token)
266
+ segment_ids.append(0)
267
+ tokens.append("[SEP]")
268
+ segment_ids.append(0)
269
+
270
+ for i in range(doc_span.length):
271
+ split_token_index = doc_span.start + i
272
+ token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
273
+
274
+ is_max_context = _check_is_max_context(doc_spans, doc_span_index,
275
+ split_token_index)
276
+ token_is_max_context[len(tokens)] = is_max_context
277
+ tokens.append(all_doc_tokens[split_token_index])
278
+ segment_ids.append(1)
279
+ tokens.append("[SEP]")
280
+ segment_ids.append(1)
281
+
282
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
283
+
284
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
285
+ # tokens are attended to.
286
+ input_mask = [1] * len(input_ids)
287
+
288
+ # Zero-pad up to the sequence length.
289
+ while len(input_ids) < max_seq_length:
290
+ input_ids.append(0)
291
+ input_mask.append(0)
292
+ segment_ids.append(0)
293
+
294
+ assert len(input_ids) == max_seq_length
295
+ assert len(input_mask) == max_seq_length
296
+ assert len(segment_ids) == max_seq_length
297
+
298
+ start_position = None
299
+ end_position = None
300
+ if is_training and not example.is_impossible:
301
+ # For training, if our document chunk does not contain an annotation
302
+ # we throw it out, since there is nothing to predict.
303
+ doc_start = doc_span.start
304
+ doc_end = doc_span.start + doc_span.length - 1
305
+ out_of_span = False
306
+ if not (tok_start_position >= doc_start and
307
+ tok_end_position <= doc_end):
308
+ out_of_span = True
309
+ if out_of_span:
310
+ start_position = 0
311
+ end_position = 0
312
+ else:
313
+ doc_offset = len(query_tokens) + 2
314
+ start_position = tok_start_position - doc_start + doc_offset
315
+ end_position = tok_end_position - doc_start + doc_offset
316
+ if is_training and example.is_impossible:
317
+ start_position = 0
318
+ end_position = 0
319
+ if example_index < 20:
320
+ logger.info("*** Example ***")
321
+ logger.info("unique_id: %s" % (unique_id))
322
+ logger.info("example_index: %s" % (example_index))
323
+ logger.info("doc_span_index: %s" % (doc_span_index))
324
+ logger.info("tokens: %s" % " ".join(tokens))
325
+ logger.info("token_to_orig_map: %s" % " ".join([
326
+ "%d:%d" % (x, y) for (x, y) in token_to_orig_map.items()]))
327
+ logger.info("token_is_max_context: %s" % " ".join([
328
+ "%d:%s" % (x, y) for (x, y) in token_is_max_context.items()
329
+ ]))
330
+ logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
331
+ logger.info(
332
+ "input_mask: %s" % " ".join([str(x) for x in input_mask]))
333
+ logger.info(
334
+ "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
335
+ if is_training and example.is_impossible:
336
+ logger.info("impossible example")
337
+ if is_training and not example.is_impossible:
338
+ answer_text = " ".join(tokens[start_position:(end_position + 1)])
339
+ logger.info("start_position: %d" % (start_position))
340
+ logger.info("end_position: %d" % (end_position))
341
+ logger.info(
342
+ "answer: %s" % (answer_text))
343
+
344
+ features.append(
345
+ InputFeatures(
346
+ unique_id=unique_id,
347
+ example_index=example_index,
348
+ doc_span_index=doc_span_index,
349
+ tokens=tokens,
350
+ token_to_orig_map=token_to_orig_map,
351
+ token_is_max_context=token_is_max_context,
352
+ input_ids=input_ids,
353
+ input_mask=input_mask,
354
+ segment_ids=segment_ids,
355
+ start_position=start_position,
356
+ end_position=end_position,
357
+ is_impossible=example.is_impossible))
358
+ unique_id += 1
359
+
360
+ return features
361
+
362
+
363
+ def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
364
+ orig_answer_text):
365
+ """Returns tokenized answer spans that better match the annotated answer."""
366
+
367
+ # The SQuAD annotations are character based. We first project them to
368
+ # whitespace-tokenized words. But then after WordPiece tokenization, we can
369
+ # often find a "better match". For example:
370
+ #
371
+ # Question: What year was John Smith born?
372
+ # Context: The leader was John Smith (1895-1943).
373
+ # Answer: 1895
374
+ #
375
+ # The original whitespace-tokenized answer will be "(1895-1943).". However
376
+ # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
377
+ # the exact answer, 1895.
378
+ #
379
+ # However, this is not always possible. Consider the following:
380
+ #
381
+ # Question: What country is the top exporter of electornics?
382
+ # Context: The Japanese electronics industry is the lagest in the world.
383
+ # Answer: Japan
384
+ #
385
+ # In this case, the annotator chose "Japan" as a character sub-span of
386
+ # the word "Japanese". Since our WordPiece tokenizer does not split
387
+ # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
388
+ # in SQuAD, but does happen.
389
+ tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
390
+
391
+ for new_start in range(input_start, input_end + 1):
392
+ for new_end in range(input_end, new_start - 1, -1):
393
+ text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
394
+ if text_span == tok_answer_text:
395
+ return (new_start, new_end)
396
+
397
+ return (input_start, input_end)
398
+
399
+
400
+ def _check_is_max_context(doc_spans, cur_span_index, position):
401
+ """Check if this is the 'max context' doc span for the token."""
402
+
403
+ # Because of the sliding window approach taken to scoring documents, a single
404
+ # token can appear in multiple documents. E.g.
405
+ # Doc: the man went to the store and bought a gallon of milk
406
+ # Span A: the man went to the
407
+ # Span B: to the store and bought
408
+ # Span C: and bought a gallon of
409
+ # ...
410
+ #
411
+ # Now the word 'bought' will have two scores from spans B and C. We only
412
+ # want to consider the score with "maximum context", which we define as
413
+ # the *minimum* of its left and right context (the *sum* of left and
414
+ # right context will always be the same, of course).
415
+ #
416
+ # In the example the maximum context for 'bought' would be span C since
417
+ # it has 1 left context and 3 right context, while span B has 4 left context
418
+ # and 0 right context.
419
+ best_score = None
420
+ best_span_index = None
421
+ for (span_index, doc_span) in enumerate(doc_spans):
422
+ end = doc_span.start + doc_span.length - 1
423
+ if position < doc_span.start:
424
+ continue
425
+ if position > end:
426
+ continue
427
+ num_left_context = position - doc_span.start
428
+ num_right_context = end - position
429
+ score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
430
+ if best_score is None or score > best_score:
431
+ best_score = score
432
+ best_span_index = span_index
433
+
434
+ return cur_span_index == best_span_index
435
+
436
+
437
+ RawResult = collections.namedtuple("RawResult",
438
+ ["unique_id", "start_logits", "end_logits"])
439
+
440
+
441
+ def write_predictions(all_examples, all_features, all_results, n_best_size,
442
+ max_answer_length, do_lower_case, output_prediction_file,
443
+ output_nbest_file, output_null_log_odds_file, verbose_logging,
444
+ version_2_with_negative, null_score_diff_threshold):
445
+ """Write final predictions to the json file and log-odds of null if needed."""
446
+ logger.info("Writing predictions to: %s" % (output_prediction_file))
447
+ logger.info("Writing nbest to: %s" % (output_nbest_file))
448
+
449
+ example_index_to_features = collections.defaultdict(list)
450
+ for feature in all_features:
451
+ example_index_to_features[feature.example_index].append(feature)
452
+
453
+ unique_id_to_result = {}
454
+ for result in all_results:
455
+ unique_id_to_result[result.unique_id] = result
456
+
457
+ _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
458
+ "PrelimPrediction",
459
+ ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
460
+
461
+ all_predictions = collections.OrderedDict()
462
+ all_nbest_json = collections.OrderedDict()
463
+ scores_diff_json = collections.OrderedDict()
464
+
465
+ for (example_index, example) in enumerate(all_examples):
466
+ features = example_index_to_features[example_index]
467
+
468
+ prelim_predictions = []
469
+ # keep track of the minimum score of null start+end of position 0
470
+ score_null = 1000000 # large and positive
471
+ min_null_feature_index = 0 # the paragraph slice with min null score
472
+ null_start_logit = 0 # the start logit at the slice with min null score
473
+ null_end_logit = 0 # the end logit at the slice with min null score
474
+ for (feature_index, feature) in enumerate(features):
475
+ result = unique_id_to_result[feature.unique_id]
476
+ start_indexes = _get_best_indexes(result.start_logits, n_best_size)
477
+ end_indexes = _get_best_indexes(result.end_logits, n_best_size)
478
+ # if we could have irrelevant answers, get the min score of irrelevant
479
+ if version_2_with_negative:
480
+ feature_null_score = result.start_logits[0] + result.end_logits[0]
481
+ if feature_null_score < score_null:
482
+ score_null = feature_null_score
483
+ min_null_feature_index = feature_index
484
+ null_start_logit = result.start_logits[0]
485
+ null_end_logit = result.end_logits[0]
486
+ for start_index in start_indexes:
487
+ for end_index in end_indexes:
488
+ # We could hypothetically create invalid predictions, e.g., predict
489
+ # that the start of the span is in the question. We throw out all
490
+ # invalid predictions.
491
+ if start_index >= len(feature.tokens):
492
+ continue
493
+ if end_index >= len(feature.tokens):
494
+ continue
495
+ if start_index not in feature.token_to_orig_map:
496
+ continue
497
+ if end_index not in feature.token_to_orig_map:
498
+ continue
499
+ if not feature.token_is_max_context.get(start_index, False):
500
+ continue
501
+ if end_index < start_index:
502
+ continue
503
+ length = end_index - start_index + 1
504
+ if length > max_answer_length:
505
+ continue
506
+ prelim_predictions.append(
507
+ _PrelimPrediction(
508
+ feature_index=feature_index,
509
+ start_index=start_index,
510
+ end_index=end_index,
511
+ start_logit=result.start_logits[start_index],
512
+ end_logit=result.end_logits[end_index]))
513
+ if version_2_with_negative:
514
+ prelim_predictions.append(
515
+ _PrelimPrediction(
516
+ feature_index=min_null_feature_index,
517
+ start_index=0,
518
+ end_index=0,
519
+ start_logit=null_start_logit,
520
+ end_logit=null_end_logit))
521
+ prelim_predictions = sorted(
522
+ prelim_predictions,
523
+ key=lambda x: (x.start_logit + x.end_logit),
524
+ reverse=True)
525
+
526
+ _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
527
+ "NbestPrediction", ["text", "start_logit", "end_logit"])
528
+
529
+ seen_predictions = {}
530
+ nbest = []
531
+ for pred in prelim_predictions:
532
+ if len(nbest) >= n_best_size:
533
+ break
534
+ feature = features[pred.feature_index]
535
+ if pred.start_index > 0: # this is a non-null prediction
536
+ tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
537
+ orig_doc_start = feature.token_to_orig_map[pred.start_index]
538
+ orig_doc_end = feature.token_to_orig_map[pred.end_index]
539
+ orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
540
+ tok_text = " ".join(tok_tokens)
541
+
542
+ # De-tokenize WordPieces that have been split off.
543
+ tok_text = tok_text.replace(" ##", "")
544
+ tok_text = tok_text.replace("##", "")
545
+
546
+ # Clean whitespace
547
+ tok_text = tok_text.strip()
548
+ tok_text = " ".join(tok_text.split())
549
+ orig_text = " ".join(orig_tokens)
550
+
551
+ final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging)
552
+ if final_text in seen_predictions:
553
+ continue
554
+
555
+ seen_predictions[final_text] = True
556
+ else:
557
+ final_text = ""
558
+ seen_predictions[final_text] = True
559
+
560
+ nbest.append(
561
+ _NbestPrediction(
562
+ text=final_text,
563
+ start_logit=pred.start_logit,
564
+ end_logit=pred.end_logit))
565
+ # if we didn't include the empty option in the n-best, include it
566
+ if version_2_with_negative:
567
+ if "" not in seen_predictions:
568
+ nbest.append(
569
+ _NbestPrediction(
570
+ text="",
571
+ start_logit=null_start_logit,
572
+ end_logit=null_end_logit))
573
+
574
+ # In very rare edge cases we could only have single null prediction.
575
+ # So we just create a nonce prediction in this case to avoid failure.
576
+ if len(nbest)==1:
577
+ nbest.insert(0,
578
+ _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
579
+
580
+ # In very rare edge cases we could have no valid predictions. So we
581
+ # just create a nonce prediction in this case to avoid failure.
582
+ if not nbest:
583
+ nbest.append(
584
+ _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
585
+
586
+ assert len(nbest) >= 1
587
+
588
+ total_scores = []
589
+ best_non_null_entry = None
590
+ for entry in nbest:
591
+ total_scores.append(entry.start_logit + entry.end_logit)
592
+ if not best_non_null_entry:
593
+ if entry.text:
594
+ best_non_null_entry = entry
595
+
596
+ probs = _compute_softmax(total_scores)
597
+
598
+ nbest_json = []
599
+ for (i, entry) in enumerate(nbest):
600
+ output = collections.OrderedDict()
601
+ output["text"] = entry.text
602
+ output["probability"] = probs[i]
603
+ output["start_logit"] = entry.start_logit
604
+ output["end_logit"] = entry.end_logit
605
+ nbest_json.append(output)
606
+
607
+ assert len(nbest_json) >= 1
608
+
609
+ if not version_2_with_negative:
610
+ all_predictions[example.qas_id] = nbest_json[0]["text"]
611
+ else:
612
+ # predict "" iff the null score - the score of best non-null > threshold
613
+ score_diff = score_null - best_non_null_entry.start_logit - (
614
+ best_non_null_entry.end_logit)
615
+ scores_diff_json[example.qas_id] = score_diff
616
+ if score_diff > null_score_diff_threshold:
617
+ all_predictions[example.qas_id] = ""
618
+ else:
619
+ all_predictions[example.qas_id] = best_non_null_entry.text
620
+ all_nbest_json[example.qas_id] = nbest_json
621
+
622
+ with open(output_prediction_file, "w") as writer:
623
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
624
+
625
+ with open(output_nbest_file, "w") as writer:
626
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
627
+
628
+ if version_2_with_negative:
629
+ with open(output_null_log_odds_file, "w") as writer:
630
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
631
+
632
+
633
+ def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False):
634
+ """Project the tokenized prediction back to the original text."""
635
+
636
+ # When we created the data, we kept track of the alignment between original
637
+ # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
638
+ # now `orig_text` contains the span of our original text corresponding to the
639
+ # span that we predicted.
640
+ #
641
+ # However, `orig_text` may contain extra characters that we don't want in
642
+ # our prediction.
643
+ #
644
+ # For example, let's say:
645
+ # pred_text = steve smith
646
+ # orig_text = Steve Smith's
647
+ #
648
+ # We don't want to return `orig_text` because it contains the extra "'s".
649
+ #
650
+ # We don't want to return `pred_text` because it's already been normalized
651
+ # (the SQuAD eval script also does punctuation stripping/lower casing but
652
+ # our tokenizer does additional normalization like stripping accent
653
+ # characters).
654
+ #
655
+ # What we really want to return is "Steve Smith".
656
+ #
657
+ # Therefore, we have to apply a semi-complicated alignment heuristic between
658
+ # `pred_text` and `orig_text` to get a character-to-character alignment. This
659
+ # can fail in certain cases in which case we just return `orig_text`.
660
+
661
+ def _strip_spaces(text):
662
+ ns_chars = []
663
+ ns_to_s_map = collections.OrderedDict()
664
+ for (i, c) in enumerate(text):
665
+ if c == " ":
666
+ continue
667
+ ns_to_s_map[len(ns_chars)] = i
668
+ ns_chars.append(c)
669
+ ns_text = "".join(ns_chars)
670
+ return (ns_text, ns_to_s_map)
671
+
672
+ # We first tokenize `orig_text`, strip whitespace from the result
673
+ # and `pred_text`, and check if they are the same length. If they are
674
+ # NOT the same length, the heuristic has failed. If they are the same
675
+ # length, we assume the characters are one-to-one aligned.
676
+ tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
677
+
678
+ tok_text = " ".join(tokenizer.tokenize(orig_text))
679
+
680
+ start_position = tok_text.find(pred_text)
681
+ if start_position == -1:
682
+ if verbose_logging:
683
+ logger.info(
684
+ "Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
685
+ return orig_text
686
+ end_position = start_position + len(pred_text) - 1
687
+
688
+ (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
689
+ (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
690
+
691
+ if len(orig_ns_text) != len(tok_ns_text):
692
+ if verbose_logging:
693
+ logger.info("Length not equal after stripping spaces: '%s' vs '%s'",
694
+ orig_ns_text, tok_ns_text)
695
+ return orig_text
696
+
697
+ # We then project the characters in `pred_text` back to `orig_text` using
698
+ # the character-to-character alignment.
699
+ tok_s_to_ns_map = {}
700
+ for (i, tok_index) in tok_ns_to_s_map.items():
701
+ tok_s_to_ns_map[tok_index] = i
702
+
703
+ orig_start_position = None
704
+ if start_position in tok_s_to_ns_map:
705
+ ns_start_position = tok_s_to_ns_map[start_position]
706
+ if ns_start_position in orig_ns_to_s_map:
707
+ orig_start_position = orig_ns_to_s_map[ns_start_position]
708
+
709
+ if orig_start_position is None:
710
+ if verbose_logging:
711
+ logger.info("Couldn't map start position")
712
+ return orig_text
713
+
714
+ orig_end_position = None
715
+ if end_position in tok_s_to_ns_map:
716
+ ns_end_position = tok_s_to_ns_map[end_position]
717
+ if ns_end_position in orig_ns_to_s_map:
718
+ orig_end_position = orig_ns_to_s_map[ns_end_position]
719
+
720
+ if orig_end_position is None:
721
+ if verbose_logging:
722
+ logger.info("Couldn't map end position")
723
+ return orig_text
724
+
725
+ output_text = orig_text[orig_start_position:(orig_end_position + 1)]
726
+ return output_text
727
+
728
+
729
+ def _get_best_indexes(logits, n_best_size):
730
+ """Get the n-best logits from a list."""
731
+ index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
732
+
733
+ best_indexes = []
734
+ for i in range(len(index_and_score)):
735
+ if i >= n_best_size:
736
+ break
737
+ best_indexes.append(index_and_score[i][0])
738
+ return best_indexes
739
+
740
+
741
+ def _compute_softmax(scores):
742
+ """Compute softmax probability over raw logits."""
743
+ if not scores:
744
+ return []
745
+
746
+ max_score = None
747
+ for score in scores:
748
+ if max_score is None or score > max_score:
749
+ max_score = score
750
+
751
+ exp_scores = []
752
+ total_sum = 0.0
753
+ for score in scores:
754
+ x = math.exp(score - max_score)
755
+ exp_scores.append(x)
756
+ total_sum += x
757
+
758
+ probs = []
759
+ for score in exp_scores:
760
+ probs.append(score / total_sum)
761
+ return probs
762
+
763
+ def main():
764
+ parser = argparse.ArgumentParser()
765
+
766
+ ## Required parameters
767
+ parser.add_argument("--bert_model", default=None, type=str, required=True,
768
+ help="Bert pre-trained model selected in the list: bert-base-uncased, "
769
+ "bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
770
+ "bert-base-multilingual-cased, bert-base-chinese.")
771
+ parser.add_argument("--output_dir", default=None, type=str, required=True,
772
+ help="The output directory where the model checkpoints and predictions will be written.")
773
+
774
+ ## Other parameters
775
+ parser.add_argument("--train_file", default=None, type=str, help="SQuAD json for training. E.g., train-v1.1.json")
776
+ parser.add_argument("--predict_file", default=None, type=str,
777
+ help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
778
+ parser.add_argument("--max_seq_length", default=384, type=int,
779
+ help="The maximum total input sequence length after WordPiece tokenization. Sequences "
780
+ "longer than this will be truncated, and sequences shorter than this will be padded.")
781
+ parser.add_argument("--doc_stride", default=128, type=int,
782
+ help="When splitting up a long document into chunks, how much stride to take between chunks.")
783
+ parser.add_argument("--max_query_length", default=64, type=int,
784
+ help="The maximum number of tokens for the question. Questions longer than this will "
785
+ "be truncated to this length.")
786
+ parser.add_argument("--do_train", action='store_true', help="Whether to run training.")
787
+ parser.add_argument("--do_predict", action='store_true', help="Whether to run eval on the dev set.")
788
+ parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.")
789
+ parser.add_argument("--predict_batch_size", default=8, type=int, help="Total batch size for predictions.")
790
+ parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
791
+ parser.add_argument("--num_train_epochs", default=3.0, type=float,
792
+ help="Total number of training epochs to perform.")
793
+ parser.add_argument("--warmup_proportion", default=0.1, type=float,
794
+ help="Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10%% "
795
+ "of training.")
796
+ parser.add_argument("--n_best_size", default=20, type=int,
797
+ help="The total number of n-best predictions to generate in the nbest_predictions.json "
798
+ "output file.")
799
+ parser.add_argument("--max_answer_length", default=30, type=int,
800
+ help="The maximum length of an answer that can be generated. This is needed because the start "
801
+ "and end predictions are not conditioned on one another.")
802
+ parser.add_argument("--verbose_logging", action='store_true',
803
+ help="If true, all of the warnings related to data processing will be printed. "
804
+ "A number of warnings are expected for a normal SQuAD evaluation.")
805
+ parser.add_argument("--no_cuda",
806
+ action='store_true',
807
+ help="Whether not to use CUDA when available")
808
+ parser.add_argument('--seed',
809
+ type=int,
810
+ default=42,
811
+ help="random seed for initialization")
812
+ parser.add_argument('--gradient_accumulation_steps',
813
+ type=int,
814
+ default=1,
815
+ help="Number of updates steps to accumulate before performing a backward/update pass.")
816
+ parser.add_argument("--do_lower_case",
817
+ action='store_true',
818
+ help="Whether to lower case the input text. True for uncased models, False for cased models.")
819
+ parser.add_argument("--local_rank",
820
+ type=int,
821
+ default=-1,
822
+ help="local_rank for distributed training on gpus")
823
+ parser.add_argument('--fp16',
824
+ action='store_true',
825
+ help="Whether to use 16-bit float precision instead of 32-bit")
826
+ parser.add_argument('--loss_scale',
827
+ type=float, default=0,
828
+ help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
829
+ "0 (default value): dynamic loss scaling.\n"
830
+ "Positive power of 2: static loss scaling value.\n")
831
+ parser.add_argument('--version_2_with_negative',
832
+ action='store_true',
833
+ help='If true, the SQuAD examples contain some that do not have an answer.')
834
+ parser.add_argument('--null_score_diff_threshold',
835
+ type=float, default=0.0,
836
+ help="If null_score - best_non_null is greater than the threshold predict null.")
837
+ parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.")
838
+ parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.")
839
+ args = parser.parse_args()
840
+ print(args)
841
+
842
+ if args.server_ip and args.server_port:
843
+ # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
844
+ import ptvsd
845
+ print("Waiting for debugger attach")
846
+ ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
847
+ ptvsd.wait_for_attach()
848
+
849
+ if args.local_rank == -1 or args.no_cuda:
850
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
851
+ n_gpu = torch.cuda.device_count()
852
+ else:
853
+ torch.cuda.set_device(args.local_rank)
854
+ device = torch.device("cuda", args.local_rank)
855
+ n_gpu = 1
856
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
857
+ torch.distributed.init_process_group(backend='nccl')
858
+
859
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
860
+ datefmt = '%m/%d/%Y %H:%M:%S',
861
+ level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
862
+
863
+ logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
864
+ device, n_gpu, bool(args.local_rank != -1), args.fp16))
865
+
866
+ if args.gradient_accumulation_steps < 1:
867
+ raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
868
+ args.gradient_accumulation_steps))
869
+
870
+ args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
871
+
872
+ random.seed(args.seed)
873
+ np.random.seed(args.seed)
874
+ torch.manual_seed(args.seed)
875
+ if n_gpu > 0:
876
+ torch.cuda.manual_seed_all(args.seed)
877
+
878
+ if not args.do_train and not args.do_predict:
879
+ raise ValueError("At least one of `do_train` or `do_predict` must be True.")
880
+
881
+ if args.do_train:
882
+ if not args.train_file:
883
+ raise ValueError(
884
+ "If `do_train` is True, then `train_file` must be specified.")
885
+ if args.do_predict:
886
+ if not args.predict_file:
887
+ raise ValueError(
888
+ "If `do_predict` is True, then `predict_file` must be specified.")
889
+
890
+ if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:
891
+ raise ValueError("Output directory () already exists and is not empty.")
892
+ if not os.path.exists(args.output_dir):
893
+ os.makedirs(args.output_dir)
894
+
895
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
896
+
897
+ train_examples = None
898
+ num_train_optimization_steps = None
899
+ if args.do_train:
900
+ train_examples = read_squad_examples(
901
+ input_file=args.train_file, is_training=True, version_2_with_negative=args.version_2_with_negative)
902
+ num_train_optimization_steps = int(
903
+ len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs
904
+ if args.local_rank != -1:
905
+ num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
906
+
907
+ # Prepare model
908
+ model = BertForQuestionAnswering.from_pretrained(args.bert_model,
909
+ cache_dir=os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(args.local_rank)))
910
+
911
+ if args.fp16:
912
+ model.half()
913
+ model.to(device)
914
+ if args.local_rank != -1:
915
+ try:
916
+ from apex.parallel import DistributedDataParallel as DDP
917
+ except ImportError:
918
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
919
+
920
+ model = DDP(model)
921
+ elif n_gpu > 1:
922
+ model = torch.nn.DataParallel(model)
923
+
924
+ # Prepare optimizer
925
+ param_optimizer = list(model.named_parameters())
926
+
927
+ # hack to remove pooler, which is not used
928
+ # thus it produce None grad that break apex
929
+ param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
930
+
931
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
932
+ optimizer_grouped_parameters = [
933
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
934
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
935
+ ]
936
+
937
+ if args.fp16:
938
+ try:
939
+ from apex.optimizers import FP16_Optimizer
940
+ from apex.optimizers import FusedAdam
941
+ except ImportError:
942
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
943
+
944
+ optimizer = FusedAdam(optimizer_grouped_parameters,
945
+ lr=args.learning_rate,
946
+ bias_correction=False,
947
+ max_grad_norm=1.0)
948
+ if args.loss_scale == 0:
949
+ optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
950
+ else:
951
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
952
+ else:
953
+ optimizer = BertAdam(optimizer_grouped_parameters,
954
+ lr=args.learning_rate,
955
+ warmup=args.warmup_proportion,
956
+ t_total=num_train_optimization_steps)
957
+
958
+ global_step = 0
959
+ if args.do_train:
960
+ cached_train_features_file = args.train_file+'_{0}_{1}_{2}_{3}'.format(
961
+ list(filter(None, args.bert_model.split('/'))).pop(), str(args.max_seq_length), str(args.doc_stride), str(args.max_query_length))
962
+ train_features = None
963
+ try:
964
+ with open(cached_train_features_file, "rb") as reader:
965
+ train_features = pickle.load(reader)
966
+ except:
967
+ train_features = convert_examples_to_features(
968
+ examples=train_examples,
969
+ tokenizer=tokenizer,
970
+ max_seq_length=args.max_seq_length,
971
+ doc_stride=args.doc_stride,
972
+ max_query_length=args.max_query_length,
973
+ is_training=True)
974
+ if args.local_rank == -1 or torch.distributed.get_rank() == 0:
975
+ logger.info(" Saving train features into cached file %s", cached_train_features_file)
976
+ with open(cached_train_features_file, "wb") as writer:
977
+ pickle.dump(train_features, writer)
978
+ logger.info("***** Running training *****")
979
+ logger.info(" Num orig examples = %d", len(train_examples))
980
+ logger.info(" Num split examples = %d", len(train_features))
981
+ logger.info(" Batch size = %d", args.train_batch_size)
982
+ logger.info(" Num steps = %d", num_train_optimization_steps)
983
+ all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
984
+ all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
985
+ all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
986
+ all_start_positions = torch.tensor([f.start_position for f in train_features], dtype=torch.long)
987
+ all_end_positions = torch.tensor([f.end_position for f in train_features], dtype=torch.long)
988
+ train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids,
989
+ all_start_positions, all_end_positions)
990
+ if args.local_rank == -1:
991
+ train_sampler = RandomSampler(train_data)
992
+ else:
993
+ train_sampler = DistributedSampler(train_data)
994
+ train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
995
+
996
+ model.train()
997
+ for _ in trange(int(args.num_train_epochs), desc="Epoch"):
998
+ for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])):
999
+ if n_gpu == 1:
1000
+ batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
1001
+ input_ids, input_mask, segment_ids, start_positions, end_positions = batch
1002
+ loss = model(input_ids, segment_ids, input_mask, start_positions, end_positions)
1003
+ if n_gpu > 1:
1004
+ loss = loss.mean() # mean() to average on multi-gpu.
1005
+ if args.gradient_accumulation_steps > 1:
1006
+ loss = loss / args.gradient_accumulation_steps
1007
+
1008
+ if args.fp16:
1009
+ optimizer.backward(loss)
1010
+ else:
1011
+ loss.backward()
1012
+ if (step + 1) % args.gradient_accumulation_steps == 0:
1013
+ if args.fp16:
1014
+ # modify learning rate with special warm up BERT uses
1015
+ # if args.fp16 is False, BertAdam is used and handles this automatically
1016
+ lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)
1017
+ for param_group in optimizer.param_groups:
1018
+ param_group['lr'] = lr_this_step
1019
+ optimizer.step()
1020
+ optimizer.zero_grad()
1021
+ global_step += 1
1022
+
1023
+ if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
1024
+ # Save a trained model, configuration and tokenizer
1025
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
1026
+
1027
+ # If we save using the predefined names, we can load using `from_pretrained`
1028
+ output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)
1029
+ output_config_file = os.path.join(args.output_dir, CONFIG_NAME)
1030
+
1031
+ torch.save(model_to_save.state_dict(), output_model_file)
1032
+ model_to_save.config.to_json_file(output_config_file)
1033
+ tokenizer.save_vocabulary(args.output_dir)
1034
+
1035
+ # Load a trained model and vocabulary that you have fine-tuned
1036
+ model = BertForQuestionAnswering.from_pretrained(args.output_dir)
1037
+ tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
1038
+ else:
1039
+ model = BertForQuestionAnswering.from_pretrained(args.bert_model)
1040
+
1041
+ model.to(device)
1042
+
1043
+ if args.do_predict and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
1044
+ eval_examples = read_squad_examples(
1045
+ input_file=args.predict_file, is_training=False, version_2_with_negative=args.version_2_with_negative)
1046
+ eval_features = convert_examples_to_features(
1047
+ examples=eval_examples,
1048
+ tokenizer=tokenizer,
1049
+ max_seq_length=args.max_seq_length,
1050
+ doc_stride=args.doc_stride,
1051
+ max_query_length=args.max_query_length,
1052
+ is_training=False)
1053
+
1054
+ logger.info("***** Running predictions *****")
1055
+ logger.info(" Num orig examples = %d", len(eval_examples))
1056
+ logger.info(" Num split examples = %d", len(eval_features))
1057
+ logger.info(" Batch size = %d", args.predict_batch_size)
1058
+
1059
+ all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
1060
+ all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
1061
+ all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
1062
+ all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
1063
+ eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index)
1064
+ # Run prediction for full data
1065
+ eval_sampler = SequentialSampler(eval_data)
1066
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)
1067
+
1068
+ model.eval()
1069
+ all_results = []
1070
+ logger.info("Start evaluating")
1071
+ for input_ids, input_mask, segment_ids, example_indices in tqdm(eval_dataloader, desc="Evaluating", disable=args.local_rank not in [-1, 0]):
1072
+ if len(all_results) % 1000 == 0:
1073
+ logger.info("Processing example: %d" % (len(all_results)))
1074
+ input_ids = input_ids.to(device)
1075
+ input_mask = input_mask.to(device)
1076
+ segment_ids = segment_ids.to(device)
1077
+ with torch.no_grad():
1078
+ batch_start_logits, batch_end_logits = model(input_ids, segment_ids, input_mask)
1079
+ for i, example_index in enumerate(example_indices):
1080
+ start_logits = batch_start_logits[i].detach().cpu().tolist()
1081
+ end_logits = batch_end_logits[i].detach().cpu().tolist()
1082
+ eval_feature = eval_features[example_index.item()]
1083
+ unique_id = int(eval_feature.unique_id)
1084
+ all_results.append(RawResult(unique_id=unique_id,
1085
+ start_logits=start_logits,
1086
+ end_logits=end_logits))
1087
+ output_prediction_file = os.path.join(args.output_dir, "predictions.json")
1088
+ output_nbest_file = os.path.join(args.output_dir, "nbest_predictions.json")
1089
+ output_null_log_odds_file = os.path.join(args.output_dir, "null_odds.json")
1090
+ write_predictions(eval_examples, eval_features, all_results,
1091
+ args.n_best_size, args.max_answer_length,
1092
+ args.do_lower_case, output_prediction_file,
1093
+ output_nbest_file, output_null_log_odds_file, args.verbose_logging,
1094
+ args.version_2_with_negative, args.null_score_diff_threshold)
1095
+
1096
+
1097
+ if __name__ == "__main__":
1098
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_swag.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """BERT finetuning runner."""
17
+
18
+ from __future__ import absolute_import
19
+
20
+ import argparse
21
+ import csv
22
+ import logging
23
+ import os
24
+ import random
25
+ import sys
26
+ from io import open
27
+
28
+ import numpy as np
29
+ import torch
30
+ from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
31
+ TensorDataset)
32
+ from torch.utils.data.distributed import DistributedSampler
33
+ from tqdm import tqdm, trange
34
+
35
+ from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME
36
+ from pytorch_pretrained_bert.modeling import BertForMultipleChoice, BertConfig
37
+ from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
38
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
39
+
40
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
41
+ datefmt = '%m/%d/%Y %H:%M:%S',
42
+ level = logging.INFO)
43
+ logger = logging.getLogger(__name__)
44
+
45
+
46
+ class SwagExample(object):
47
+ """A single training/test example for the SWAG dataset."""
48
+ def __init__(self,
49
+ swag_id,
50
+ context_sentence,
51
+ start_ending,
52
+ ending_0,
53
+ ending_1,
54
+ ending_2,
55
+ ending_3,
56
+ label = None):
57
+ self.swag_id = swag_id
58
+ self.context_sentence = context_sentence
59
+ self.start_ending = start_ending
60
+ self.endings = [
61
+ ending_0,
62
+ ending_1,
63
+ ending_2,
64
+ ending_3,
65
+ ]
66
+ self.label = label
67
+
68
+ def __str__(self):
69
+ return self.__repr__()
70
+
71
+ def __repr__(self):
72
+ l = [
73
+ "swag_id: {}".format(self.swag_id),
74
+ "context_sentence: {}".format(self.context_sentence),
75
+ "start_ending: {}".format(self.start_ending),
76
+ "ending_0: {}".format(self.endings[0]),
77
+ "ending_1: {}".format(self.endings[1]),
78
+ "ending_2: {}".format(self.endings[2]),
79
+ "ending_3: {}".format(self.endings[3]),
80
+ ]
81
+
82
+ if self.label is not None:
83
+ l.append("label: {}".format(self.label))
84
+
85
+ return ", ".join(l)
86
+
87
+
88
+ class InputFeatures(object):
89
+ def __init__(self,
90
+ example_id,
91
+ choices_features,
92
+ label
93
+
94
+ ):
95
+ self.example_id = example_id
96
+ self.choices_features = [
97
+ {
98
+ 'input_ids': input_ids,
99
+ 'input_mask': input_mask,
100
+ 'segment_ids': segment_ids
101
+ }
102
+ for _, input_ids, input_mask, segment_ids in choices_features
103
+ ]
104
+ self.label = label
105
+
106
+
107
+ def read_swag_examples(input_file, is_training):
108
+ with open(input_file, 'r', encoding='utf-8') as f:
109
+ reader = csv.reader(f)
110
+ lines = []
111
+ for line in reader:
112
+ if sys.version_info[0] == 2:
113
+ line = list(unicode(cell, 'utf-8') for cell in line)
114
+ lines.append(line)
115
+
116
+ if is_training and lines[0][-1] != 'label':
117
+ raise ValueError(
118
+ "For training, the input file must contain a label column."
119
+ )
120
+
121
+ examples = [
122
+ SwagExample(
123
+ swag_id = line[2],
124
+ context_sentence = line[4],
125
+ start_ending = line[5], # in the swag dataset, the
126
+ # common beginning of each
127
+ # choice is stored in "sent2".
128
+ ending_0 = line[7],
129
+ ending_1 = line[8],
130
+ ending_2 = line[9],
131
+ ending_3 = line[10],
132
+ label = int(line[11]) if is_training else None
133
+ ) for line in lines[1:] # we skip the line with the column names
134
+ ]
135
+
136
+ return examples
137
+
138
+ def convert_examples_to_features(examples, tokenizer, max_seq_length,
139
+ is_training):
140
+ """Loads a data file into a list of `InputBatch`s."""
141
+
142
+ # Swag is a multiple choice task. To perform this task using Bert,
143
+ # we will use the formatting proposed in "Improving Language
144
+ # Understanding by Generative Pre-Training" and suggested by
145
+ # @jacobdevlin-google in this issue
146
+ # https://github.com/google-research/bert/issues/38.
147
+ #
148
+ # Each choice will correspond to a sample on which we run the
149
+ # inference. For a given Swag example, we will create the 4
150
+ # following inputs:
151
+ # - [CLS] context [SEP] choice_1 [SEP]
152
+ # - [CLS] context [SEP] choice_2 [SEP]
153
+ # - [CLS] context [SEP] choice_3 [SEP]
154
+ # - [CLS] context [SEP] choice_4 [SEP]
155
+ # The model will output a single value for each input. To get the
156
+ # final decision of the model, we will run a softmax over these 4
157
+ # outputs.
158
+ features = []
159
+ for example_index, example in enumerate(examples):
160
+ context_tokens = tokenizer.tokenize(example.context_sentence)
161
+ start_ending_tokens = tokenizer.tokenize(example.start_ending)
162
+
163
+ choices_features = []
164
+ for ending_index, ending in enumerate(example.endings):
165
+ # We create a copy of the context tokens in order to be
166
+ # able to shrink it according to ending_tokens
167
+ context_tokens_choice = context_tokens[:]
168
+ ending_tokens = start_ending_tokens + tokenizer.tokenize(ending)
169
+ # Modifies `context_tokens_choice` and `ending_tokens` in
170
+ # place so that the total length is less than the
171
+ # specified length. Account for [CLS], [SEP], [SEP] with
172
+ # "- 3"
173
+ _truncate_seq_pair(context_tokens_choice, ending_tokens, max_seq_length - 3)
174
+
175
+ tokens = ["[CLS]"] + context_tokens_choice + ["[SEP]"] + ending_tokens + ["[SEP]"]
176
+ segment_ids = [0] * (len(context_tokens_choice) + 2) + [1] * (len(ending_tokens) + 1)
177
+
178
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
179
+ input_mask = [1] * len(input_ids)
180
+
181
+ # Zero-pad up to the sequence length.
182
+ padding = [0] * (max_seq_length - len(input_ids))
183
+ input_ids += padding
184
+ input_mask += padding
185
+ segment_ids += padding
186
+
187
+ assert len(input_ids) == max_seq_length
188
+ assert len(input_mask) == max_seq_length
189
+ assert len(segment_ids) == max_seq_length
190
+
191
+ choices_features.append((tokens, input_ids, input_mask, segment_ids))
192
+
193
+ label = example.label
194
+ if example_index < 5:
195
+ logger.info("*** Example ***")
196
+ logger.info("swag_id: {}".format(example.swag_id))
197
+ for choice_idx, (tokens, input_ids, input_mask, segment_ids) in enumerate(choices_features):
198
+ logger.info("choice: {}".format(choice_idx))
199
+ logger.info("tokens: {}".format(' '.join(tokens)))
200
+ logger.info("input_ids: {}".format(' '.join(map(str, input_ids))))
201
+ logger.info("input_mask: {}".format(' '.join(map(str, input_mask))))
202
+ logger.info("segment_ids: {}".format(' '.join(map(str, segment_ids))))
203
+ if is_training:
204
+ logger.info("label: {}".format(label))
205
+
206
+ features.append(
207
+ InputFeatures(
208
+ example_id = example.swag_id,
209
+ choices_features = choices_features,
210
+ label = label
211
+ )
212
+ )
213
+
214
+ return features
215
+
216
+ def _truncate_seq_pair(tokens_a, tokens_b, max_length):
217
+ """Truncates a sequence pair in place to the maximum length."""
218
+
219
+ # This is a simple heuristic which will always truncate the longer sequence
220
+ # one token at a time. This makes more sense than truncating an equal percent
221
+ # of tokens from each, since if one sequence is very short then each token
222
+ # that's truncated likely contains more information than a longer sequence.
223
+ while True:
224
+ total_length = len(tokens_a) + len(tokens_b)
225
+ if total_length <= max_length:
226
+ break
227
+ if len(tokens_a) > len(tokens_b):
228
+ tokens_a.pop()
229
+ else:
230
+ tokens_b.pop()
231
+
232
+ def accuracy(out, labels):
233
+ outputs = np.argmax(out, axis=1)
234
+ return np.sum(outputs == labels)
235
+
236
+ def select_field(features, field):
237
+ return [
238
+ [
239
+ choice[field]
240
+ for choice in feature.choices_features
241
+ ]
242
+ for feature in features
243
+ ]
244
+
245
+ def main():
246
+ parser = argparse.ArgumentParser()
247
+
248
+ ## Required parameters
249
+ parser.add_argument("--data_dir",
250
+ default=None,
251
+ type=str,
252
+ required=True,
253
+ help="The input data dir. Should contain the .csv files (or other data files) for the task.")
254
+ parser.add_argument("--bert_model", default=None, type=str, required=True,
255
+ help="Bert pre-trained model selected in the list: bert-base-uncased, "
256
+ "bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
257
+ "bert-base-multilingual-cased, bert-base-chinese.")
258
+ parser.add_argument("--output_dir",
259
+ default=None,
260
+ type=str,
261
+ required=True,
262
+ help="The output directory where the model checkpoints will be written.")
263
+
264
+ ## Other parameters
265
+ parser.add_argument("--max_seq_length",
266
+ default=128,
267
+ type=int,
268
+ help="The maximum total input sequence length after WordPiece tokenization. \n"
269
+ "Sequences longer than this will be truncated, and sequences shorter \n"
270
+ "than this will be padded.")
271
+ parser.add_argument("--do_train",
272
+ action='store_true',
273
+ help="Whether to run training.")
274
+ parser.add_argument("--do_eval",
275
+ action='store_true',
276
+ help="Whether to run eval on the dev set.")
277
+ parser.add_argument("--do_lower_case",
278
+ action='store_true',
279
+ help="Set this flag if you are using an uncased model.")
280
+ parser.add_argument("--train_batch_size",
281
+ default=32,
282
+ type=int,
283
+ help="Total batch size for training.")
284
+ parser.add_argument("--eval_batch_size",
285
+ default=8,
286
+ type=int,
287
+ help="Total batch size for eval.")
288
+ parser.add_argument("--learning_rate",
289
+ default=5e-5,
290
+ type=float,
291
+ help="The initial learning rate for Adam.")
292
+ parser.add_argument("--num_train_epochs",
293
+ default=3.0,
294
+ type=float,
295
+ help="Total number of training epochs to perform.")
296
+ parser.add_argument("--warmup_proportion",
297
+ default=0.1,
298
+ type=float,
299
+ help="Proportion of training to perform linear learning rate warmup for. "
300
+ "E.g., 0.1 = 10%% of training.")
301
+ parser.add_argument("--no_cuda",
302
+ action='store_true',
303
+ help="Whether not to use CUDA when available")
304
+ parser.add_argument("--local_rank",
305
+ type=int,
306
+ default=-1,
307
+ help="local_rank for distributed training on gpus")
308
+ parser.add_argument('--seed',
309
+ type=int,
310
+ default=42,
311
+ help="random seed for initialization")
312
+ parser.add_argument('--gradient_accumulation_steps',
313
+ type=int,
314
+ default=1,
315
+ help="Number of updates steps to accumulate before performing a backward/update pass.")
316
+ parser.add_argument('--fp16',
317
+ action='store_true',
318
+ help="Whether to use 16-bit float precision instead of 32-bit")
319
+ parser.add_argument('--loss_scale',
320
+ type=float, default=0,
321
+ help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
322
+ "0 (default value): dynamic loss scaling.\n"
323
+ "Positive power of 2: static loss scaling value.\n")
324
+
325
+ args = parser.parse_args()
326
+
327
+ if args.local_rank == -1 or args.no_cuda:
328
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
329
+ n_gpu = torch.cuda.device_count()
330
+ else:
331
+ torch.cuda.set_device(args.local_rank)
332
+ device = torch.device("cuda", args.local_rank)
333
+ n_gpu = 1
334
+ # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
335
+ torch.distributed.init_process_group(backend='nccl')
336
+ logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
337
+ device, n_gpu, bool(args.local_rank != -1), args.fp16))
338
+
339
+ if args.gradient_accumulation_steps < 1:
340
+ raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
341
+ args.gradient_accumulation_steps))
342
+
343
+ args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
344
+
345
+ random.seed(args.seed)
346
+ np.random.seed(args.seed)
347
+ torch.manual_seed(args.seed)
348
+ if n_gpu > 0:
349
+ torch.cuda.manual_seed_all(args.seed)
350
+
351
+ if not args.do_train and not args.do_eval:
352
+ raise ValueError("At least one of `do_train` or `do_eval` must be True.")
353
+
354
+ if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
355
+ raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
356
+ if not os.path.exists(args.output_dir):
357
+ os.makedirs(args.output_dir)
358
+
359
+ tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
360
+
361
+ train_examples = None
362
+ num_train_optimization_steps = None
363
+ if args.do_train:
364
+ train_examples = read_swag_examples(os.path.join(args.data_dir, 'train.csv'), is_training = True)
365
+ num_train_optimization_steps = int(
366
+ len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs
367
+ if args.local_rank != -1:
368
+ num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
369
+
370
+ # Prepare model
371
+ model = BertForMultipleChoice.from_pretrained(args.bert_model,
372
+ cache_dir=os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(args.local_rank)),
373
+ num_choices=4)
374
+ if args.fp16:
375
+ model.half()
376
+ model.to(device)
377
+ if args.local_rank != -1:
378
+ try:
379
+ from apex.parallel import DistributedDataParallel as DDP
380
+ except ImportError:
381
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
382
+
383
+ model = DDP(model)
384
+ elif n_gpu > 1:
385
+ model = torch.nn.DataParallel(model)
386
+
387
+ # Prepare optimizer
388
+ param_optimizer = list(model.named_parameters())
389
+
390
+ # hack to remove pooler, which is not used
391
+ # thus it produce None grad that break apex
392
+ param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
393
+
394
+ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
395
+ optimizer_grouped_parameters = [
396
+ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
397
+ {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
398
+ ]
399
+ if args.fp16:
400
+ try:
401
+ from apex.optimizers import FP16_Optimizer
402
+ from apex.optimizers import FusedAdam
403
+ except ImportError:
404
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
405
+
406
+ optimizer = FusedAdam(optimizer_grouped_parameters,
407
+ lr=args.learning_rate,
408
+ bias_correction=False,
409
+ max_grad_norm=1.0)
410
+ if args.loss_scale == 0:
411
+ optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
412
+ else:
413
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
414
+ else:
415
+ optimizer = BertAdam(optimizer_grouped_parameters,
416
+ lr=args.learning_rate,
417
+ warmup=args.warmup_proportion,
418
+ t_total=num_train_optimization_steps)
419
+
420
+ global_step = 0
421
+ if args.do_train:
422
+ train_features = convert_examples_to_features(
423
+ train_examples, tokenizer, args.max_seq_length, True)
424
+ logger.info("***** Running training *****")
425
+ logger.info(" Num examples = %d", len(train_examples))
426
+ logger.info(" Batch size = %d", args.train_batch_size)
427
+ logger.info(" Num steps = %d", num_train_optimization_steps)
428
+ all_input_ids = torch.tensor(select_field(train_features, 'input_ids'), dtype=torch.long)
429
+ all_input_mask = torch.tensor(select_field(train_features, 'input_mask'), dtype=torch.long)
430
+ all_segment_ids = torch.tensor(select_field(train_features, 'segment_ids'), dtype=torch.long)
431
+ all_label = torch.tensor([f.label for f in train_features], dtype=torch.long)
432
+ train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label)
433
+ if args.local_rank == -1:
434
+ train_sampler = RandomSampler(train_data)
435
+ else:
436
+ train_sampler = DistributedSampler(train_data)
437
+ train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
438
+
439
+ model.train()
440
+ for _ in trange(int(args.num_train_epochs), desc="Epoch"):
441
+ tr_loss = 0
442
+ nb_tr_examples, nb_tr_steps = 0, 0
443
+ for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
444
+ batch = tuple(t.to(device) for t in batch)
445
+ input_ids, input_mask, segment_ids, label_ids = batch
446
+ loss = model(input_ids, segment_ids, input_mask, label_ids)
447
+ if n_gpu > 1:
448
+ loss = loss.mean() # mean() to average on multi-gpu.
449
+ if args.fp16 and args.loss_scale != 1.0:
450
+ # rescale loss for fp16 training
451
+ # see https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html
452
+ loss = loss * args.loss_scale
453
+ if args.gradient_accumulation_steps > 1:
454
+ loss = loss / args.gradient_accumulation_steps
455
+ tr_loss += loss.item()
456
+ nb_tr_examples += input_ids.size(0)
457
+ nb_tr_steps += 1
458
+
459
+ if args.fp16:
460
+ optimizer.backward(loss)
461
+ else:
462
+ loss.backward()
463
+ if (step + 1) % args.gradient_accumulation_steps == 0:
464
+ if args.fp16:
465
+ # modify learning rate with special warm up BERT uses
466
+ # if args.fp16 is False, BertAdam is used that handles this automatically
467
+ lr_this_step = args.learning_rate * warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)
468
+ for param_group in optimizer.param_groups:
469
+ param_group['lr'] = lr_this_step
470
+ optimizer.step()
471
+ optimizer.zero_grad()
472
+ global_step += 1
473
+
474
+
475
+ if args.do_train:
476
+ # Save a trained model, configuration and tokenizer
477
+ model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
478
+
479
+ # If we save using the predefined names, we can load using `from_pretrained`
480
+ output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)
481
+ output_config_file = os.path.join(args.output_dir, CONFIG_NAME)
482
+
483
+ torch.save(model_to_save.state_dict(), output_model_file)
484
+ model_to_save.config.to_json_file(output_config_file)
485
+ tokenizer.save_vocabulary(args.output_dir)
486
+
487
+ # Load a trained model and vocabulary that you have fine-tuned
488
+ model = BertForMultipleChoice.from_pretrained(args.output_dir, num_choices=4)
489
+ tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
490
+ else:
491
+ model = BertForMultipleChoice.from_pretrained(args.bert_model, num_choices=4)
492
+ model.to(device)
493
+
494
+
495
+ if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
496
+ eval_examples = read_swag_examples(os.path.join(args.data_dir, 'val.csv'), is_training = True)
497
+ eval_features = convert_examples_to_features(
498
+ eval_examples, tokenizer, args.max_seq_length, True)
499
+ logger.info("***** Running evaluation *****")
500
+ logger.info(" Num examples = %d", len(eval_examples))
501
+ logger.info(" Batch size = %d", args.eval_batch_size)
502
+ all_input_ids = torch.tensor(select_field(eval_features, 'input_ids'), dtype=torch.long)
503
+ all_input_mask = torch.tensor(select_field(eval_features, 'input_mask'), dtype=torch.long)
504
+ all_segment_ids = torch.tensor(select_field(eval_features, 'segment_ids'), dtype=torch.long)
505
+ all_label = torch.tensor([f.label for f in eval_features], dtype=torch.long)
506
+ eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label)
507
+ # Run prediction for full data
508
+ eval_sampler = SequentialSampler(eval_data)
509
+ eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
510
+
511
+ model.eval()
512
+ eval_loss, eval_accuracy = 0, 0
513
+ nb_eval_steps, nb_eval_examples = 0, 0
514
+ for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating"):
515
+ input_ids = input_ids.to(device)
516
+ input_mask = input_mask.to(device)
517
+ segment_ids = segment_ids.to(device)
518
+ label_ids = label_ids.to(device)
519
+
520
+ with torch.no_grad():
521
+ tmp_eval_loss = model(input_ids, segment_ids, input_mask, label_ids)
522
+ logits = model(input_ids, segment_ids, input_mask)
523
+
524
+ logits = logits.detach().cpu().numpy()
525
+ label_ids = label_ids.to('cpu').numpy()
526
+ tmp_eval_accuracy = accuracy(logits, label_ids)
527
+
528
+ eval_loss += tmp_eval_loss.mean().item()
529
+ eval_accuracy += tmp_eval_accuracy
530
+
531
+ nb_eval_examples += input_ids.size(0)
532
+ nb_eval_steps += 1
533
+
534
+ eval_loss = eval_loss / nb_eval_steps
535
+ eval_accuracy = eval_accuracy / nb_eval_examples
536
+
537
+ result = {'eval_loss': eval_loss,
538
+ 'eval_accuracy': eval_accuracy,
539
+ 'global_step': global_step,
540
+ 'loss': tr_loss/nb_tr_steps}
541
+
542
+ output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
543
+ with open(output_eval_file, "w") as writer:
544
+ logger.info("***** Eval results *****")
545
+ for key in sorted(result.keys()):
546
+ logger.info(" %s = %s", key, str(result[key]))
547
+ writer.write("%s = %s\n" % (key, str(result[key])))
548
+
549
+
550
+ if __name__ == "__main__":
551
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/examples/run_transfo_xl.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch Transformer XL model evaluation script.
17
+ Adapted from https://github.com/kimiyoung/transformer-xl.
18
+ In particular https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/eval.py
19
+
20
+ This script with default values evaluates a pretrained Transformer-XL on WikiText 103
21
+ """
22
+ from __future__ import absolute_import, division, print_function, unicode_literals
23
+
24
+ import argparse
25
+ import logging
26
+ import time
27
+ import math
28
+
29
+ import torch
30
+
31
+ from pytorch_pretrained_bert import TransfoXLLMHeadModel, TransfoXLCorpus, TransfoXLTokenizer
32
+
33
+ logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
34
+ datefmt = '%m/%d/%Y %H:%M:%S',
35
+ level = logging.INFO)
36
+ logger = logging.getLogger(__name__)
37
+
38
+ def main():
39
+ parser = argparse.ArgumentParser(description='PyTorch Transformer Language Model')
40
+ parser.add_argument('--model_name', type=str, default='transfo-xl-wt103',
41
+ help='pretrained model name')
42
+ parser.add_argument('--split', type=str, default='test',
43
+ choices=['all', 'valid', 'test'],
44
+ help='which split to evaluate')
45
+ parser.add_argument('--batch_size', type=int, default=10,
46
+ help='batch size')
47
+ parser.add_argument('--tgt_len', type=int, default=128,
48
+ help='number of tokens to predict')
49
+ parser.add_argument('--ext_len', type=int, default=0,
50
+ help='length of the extended context')
51
+ parser.add_argument('--mem_len', type=int, default=1600,
52
+ help='length of the retained previous heads')
53
+ parser.add_argument('--clamp_len', type=int, default=1000,
54
+ help='max positional embedding index')
55
+ parser.add_argument('--no_cuda', action='store_true',
56
+ help='Do not use CUDA even though CUA is available')
57
+ parser.add_argument('--work_dir', type=str, required=True,
58
+ help='path to the work_dir')
59
+ parser.add_argument('--no_log', action='store_true',
60
+ help='do not log the eval result')
61
+ parser.add_argument('--same_length', action='store_true',
62
+ help='set same length attention with masking')
63
+ parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.")
64
+ parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.")
65
+ args = parser.parse_args()
66
+ assert args.ext_len >= 0, 'extended context length must be non-negative'
67
+
68
+ if args.server_ip and args.server_port:
69
+ # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
70
+ import ptvsd
71
+ print("Waiting for debugger attach")
72
+ ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
73
+ ptvsd.wait_for_attach()
74
+
75
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
76
+ logger.info("device: {}".format(device))
77
+
78
+ # Load a pre-processed dataset
79
+ # You can also build the corpus yourself using TransfoXLCorpus methods
80
+ # The pre-processing involve computing word frequencies to prepare the Adaptive input and SoftMax
81
+ # and tokenizing the dataset
82
+ # The pre-processed corpus is a convertion (using the conversion script )
83
+ tokenizer = TransfoXLTokenizer.from_pretrained(args.model_name)
84
+ corpus = TransfoXLCorpus.from_pretrained(args.model_name)
85
+ ntokens = len(corpus.vocab)
86
+
87
+ va_iter = corpus.get_iterator('valid', args.batch_size, args.tgt_len,
88
+ device=device, ext_len=args.ext_len)
89
+ te_iter = corpus.get_iterator('test', args.batch_size, args.tgt_len,
90
+ device=device, ext_len=args.ext_len)
91
+
92
+ # Load a pre-trained model
93
+ model = TransfoXLLMHeadModel.from_pretrained(args.model_name)
94
+ model = model.to(device)
95
+
96
+ logger.info('Evaluating with bsz {} tgt_len {} ext_len {} mem_len {} clamp_len {}'.format(
97
+ args.batch_size, args.tgt_len, args.ext_len, args.mem_len, args.clamp_len))
98
+
99
+ model.reset_length(args.tgt_len, args.ext_len, args.mem_len)
100
+ if args.clamp_len > 0:
101
+ model.clamp_len = args.clamp_len
102
+ if args.same_length:
103
+ model.same_length = True
104
+
105
+ ###############################################################################
106
+ # Evaluation code
107
+ ###############################################################################
108
+ def evaluate(eval_iter):
109
+ # Turn on evaluation mode which disables dropout.
110
+ model.eval()
111
+ total_len, total_loss = 0, 0.
112
+ start_time = time.time()
113
+ with torch.no_grad():
114
+ mems = None
115
+ for idx, (data, target, seq_len) in enumerate(eval_iter):
116
+ ret = model(data, target, mems)
117
+ loss, mems = ret
118
+ loss = loss.mean()
119
+ total_loss += seq_len * loss.item()
120
+ total_len += seq_len
121
+ total_time = time.time() - start_time
122
+ logger.info('Time : {:.2f}s, {:.2f}ms/segment'.format(
123
+ total_time, 1000 * total_time / (idx+1)))
124
+ return total_loss / total_len
125
+
126
+ # Run on test data.
127
+ if args.split == 'all':
128
+ test_loss = evaluate(te_iter)
129
+ valid_loss = evaluate(va_iter)
130
+ elif args.split == 'valid':
131
+ valid_loss = evaluate(va_iter)
132
+ test_loss = None
133
+ elif args.split == 'test':
134
+ test_loss = evaluate(te_iter)
135
+ valid_loss = None
136
+
137
+ def format_log(loss, split):
138
+ log_str = '| {0} loss {1:5.2f} | {0} ppl {2:9.3f} '.format(
139
+ split, loss, math.exp(loss))
140
+ return log_str
141
+
142
+ log_str = ''
143
+ if valid_loss is not None:
144
+ log_str += format_log(valid_loss, 'valid')
145
+ if test_loss is not None:
146
+ log_str += format_log(test_loss, 'test')
147
+
148
+ logger.info('=' * 100)
149
+ logger.info(log_str)
150
+ logger.info('=' * 100)
151
+
152
+ if __name__ == '__main__':
153
+ main()
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/hubconf.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytorch_pretrained_bert.tokenization import BertTokenizer
2
+ from pytorch_pretrained_bert.modeling import (
3
+ BertModel,
4
+ BertForNextSentencePrediction,
5
+ BertForMaskedLM,
6
+ BertForMultipleChoice,
7
+ BertForPreTraining,
8
+ BertForQuestionAnswering,
9
+ BertForSequenceClassification,
10
+ BertForTokenClassification,
11
+ )
12
+
13
+ dependencies = ['torch', 'tqdm', 'boto3', 'requests', 'regex']
14
+
15
+ # A lot of models share the same param doc. Use a decorator
16
+ # to save typing
17
+ bert_docstring = """
18
+ Params:
19
+ pretrained_model_name_or_path: either:
20
+ - a str with the name of a pre-trained model to load
21
+ . `bert-base-uncased`
22
+ . `bert-large-uncased`
23
+ . `bert-base-cased`
24
+ . `bert-large-cased`
25
+ . `bert-base-multilingual-uncased`
26
+ . `bert-base-multilingual-cased`
27
+ . `bert-base-chinese`
28
+ - a path or url to a pretrained model archive containing:
29
+ . `bert_config.json` a configuration file for the model
30
+ . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining
31
+ instance
32
+ - a path or url to a pretrained model archive containing:
33
+ . `bert_config.json` a configuration file for the model
34
+ . `model.chkpt` a TensorFlow checkpoint
35
+ from_tf: should we load the weights from a locally saved TensorFlow
36
+ checkpoint
37
+ cache_dir: an optional path to a folder in which the pre-trained models
38
+ will be cached.
39
+ state_dict: an optional state dictionnary
40
+ (collections.OrderedDict object) to use instead of Google
41
+ pre-trained models
42
+ *inputs, **kwargs: additional input for the specific Bert class
43
+ (ex: num_labels for BertForSequenceClassification)
44
+ """
45
+
46
+
47
+ def _append_from_pretrained_docstring(docstr):
48
+ def docstring_decorator(fn):
49
+ fn.__doc__ = fn.__doc__ + docstr
50
+ return fn
51
+ return docstring_decorator
52
+
53
+
54
+ def bertTokenizer(*args, **kwargs):
55
+ """
56
+ Instantiate a BertTokenizer from a pre-trained/customized vocab file
57
+ Args:
58
+ pretrained_model_name_or_path: Path to pretrained model archive
59
+ or one of pre-trained vocab configs below.
60
+ * bert-base-uncased
61
+ * bert-large-uncased
62
+ * bert-base-cased
63
+ * bert-large-cased
64
+ * bert-base-multilingual-uncased
65
+ * bert-base-multilingual-cased
66
+ * bert-base-chinese
67
+ Keyword args:
68
+ cache_dir: an optional path to a specific directory to download and cache
69
+ the pre-trained model weights.
70
+ Default: None
71
+ do_lower_case: Whether to lower case the input.
72
+ Only has an effect when do_wordpiece_only=False
73
+ Default: True
74
+ do_basic_tokenize: Whether to do basic tokenization before wordpiece.
75
+ Default: True
76
+ max_len: An artificial maximum length to truncate tokenized sequences to;
77
+ Effective maximum length is always the minimum of this
78
+ value (if specified) and the underlying BERT model's
79
+ sequence length.
80
+ Default: None
81
+ never_split: List of tokens which will never be split during tokenization.
82
+ Only has an effect when do_wordpiece_only=False
83
+ Default: ["[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]"]
84
+
85
+ Example:
86
+ >>> sentence = 'Hello, World!'
87
+ >>> tokenizer = torch.hub.load('ailzhang/pytorch-pretrained-BERT:hubconf', 'bertTokenizer', 'bert-base-cased', do_basic_tokenize=False, force_reload=False)
88
+ >>> toks = tokenizer.tokenize(sentence)
89
+ ['Hello', '##,', 'World', '##!']
90
+ >>> ids = tokenizer.convert_tokens_to_ids(toks)
91
+ [8667, 28136, 1291, 28125]
92
+ """
93
+ tokenizer = BertTokenizer.from_pretrained(*args, **kwargs)
94
+ return tokenizer
95
+
96
+
97
+ @_append_from_pretrained_docstring(bert_docstring)
98
+ def bertModel(*args, **kwargs):
99
+ """
100
+ BertModel is the basic BERT Transformer model with a layer of summed token,
101
+ position and sequence embeddings followed by a series of identical
102
+ self-attention blocks (12 for BERT-base, 24 for BERT-large).
103
+ """
104
+ model = BertModel.from_pretrained(*args, **kwargs)
105
+ return model
106
+
107
+
108
+ @_append_from_pretrained_docstring(bert_docstring)
109
+ def bertForNextSentencePrediction(*args, **kwargs):
110
+ """
111
+ BERT model with next sentence prediction head.
112
+ This module comprises the BERT model followed by the next sentence
113
+ classification head.
114
+ """
115
+ model = BertForNextSentencePrediction.from_pretrained(*args, **kwargs)
116
+ return model
117
+
118
+
119
+ @_append_from_pretrained_docstring(bert_docstring)
120
+ def bertForPreTraining(*args, **kwargs):
121
+ """
122
+ BERT model with pre-training heads.
123
+ This module comprises the BERT model followed by the two pre-training heads
124
+ - the masked language modeling head, and
125
+ - the next sentence classification head.
126
+ """
127
+ model = BertForPreTraining.from_pretrained(*args, **kwargs)
128
+ return model
129
+
130
+
131
+ @_append_from_pretrained_docstring(bert_docstring)
132
+ def bertForMaskedLM(*args, **kwargs):
133
+ """
134
+ BertForMaskedLM includes the BertModel Transformer followed by the
135
+ (possibly) pre-trained masked language modeling head.
136
+ """
137
+ model = BertForMaskedLM.from_pretrained(*args, **kwargs)
138
+ return model
139
+
140
+
141
+ @_append_from_pretrained_docstring(bert_docstring)
142
+ def bertForSequenceClassification(*args, **kwargs):
143
+ """
144
+ BertForSequenceClassification is a fine-tuning model that includes
145
+ BertModel and a sequence-level (sequence or pair of sequences) classifier
146
+ on top of the BertModel.
147
+
148
+ The sequence-level classifier is a linear layer that takes as input the
149
+ last hidden state of the first character in the input sequence
150
+ (see Figures 3a and 3b in the BERT paper).
151
+ """
152
+ model = BertForSequenceClassification.from_pretrained(*args, **kwargs)
153
+ return model
154
+
155
+
156
+ @_append_from_pretrained_docstring(bert_docstring)
157
+ def bertForMultipleChoice(*args, **kwargs):
158
+ """
159
+ BertForMultipleChoice is a fine-tuning model that includes BertModel and a
160
+ linear layer on top of the BertModel.
161
+ """
162
+ model = BertForMultipleChoice.from_pretrained(*args, **kwargs)
163
+ return model
164
+
165
+
166
+ @_append_from_pretrained_docstring(bert_docstring)
167
+ def bertForQuestionAnswering(*args, **kwargs):
168
+ """
169
+ BertForQuestionAnswering is a fine-tuning model that includes BertModel
170
+ with a token-level classifiers on top of the full sequence of last hidden
171
+ states.
172
+ """
173
+ model = BertForQuestionAnswering.from_pretrained(*args, **kwargs)
174
+ return model
175
+
176
+
177
+ @_append_from_pretrained_docstring(bert_docstring)
178
+ def bertForTokenClassification(*args, **kwargs):
179
+ """
180
+ BertForTokenClassification is a fine-tuning model that includes BertModel
181
+ and a token-level classifier on top of the BertModel.
182
+
183
+ The token-level classifier is a linear layer that takes as input the last
184
+ hidden state of the sequence.
185
+ """
186
+ model = BertForTokenClassification.from_pretrained(*args, **kwargs)
187
+ return model
dark-secrets-of-BERT-master/dark-secrets-of-BERT-master/notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb ADDED
The diff for this file is too large to render. See raw diff