Spaces:
Runtime error
Runtime error
Trim server files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- server/spacyface/.gitignore +0 -22
- server/spacyface/.gitrepo +0 -12
- server/spacyface/LICENSE +0 -201
- server/spacyface/README.md +0 -136
- server/spacyface/environment-dev.yml +0 -24
- server/spacyface/environment.yml +0 -19
- server/spacyface/img/SampleHeatmap.png +0 -0
- server/spacyface/setup.cfg +0 -2
- server/spacyface/setup.py +0 -31
- server/spacyface/spacyface/__init__.py +0 -23
- server/spacyface/spacyface/aligner.py +0 -261
- server/spacyface/spacyface/checker/__init__.py +0 -4
- server/spacyface/spacyface/checker/against_corpus.py +0 -26
- server/spacyface/spacyface/simple_spacy_token.py +0 -155
- server/spacyface/spacyface/utils/f.py +0 -103
- server/spacyface/spacyface/utils/sentence_extracting.py +0 -176
- server/spacyface/tests/EN_TEST_SENTS.py +0 -18
- server/spacyface/tests/__init__.py +0 -1
- server/spacyface/tests/test_aligner.py +0 -32
- server/spacyface/tests/wiki.test.txt +0 -0
- server/transformers/.circleci/config.yml +0 -143
- server/transformers/.circleci/deploy.sh +0 -28
- server/transformers/.coveragerc +0 -12
- server/transformers/.github/ISSUE_TEMPLATE/---new-benchmark.md +0 -22
- server/transformers/.github/ISSUE_TEMPLATE/--new-model-addition.md +0 -20
- server/transformers/.github/ISSUE_TEMPLATE/bug-report.md +0 -52
- server/transformers/.github/ISSUE_TEMPLATE/feature-request.md +0 -25
- server/transformers/.github/ISSUE_TEMPLATE/migration.md +0 -57
- server/transformers/.github/ISSUE_TEMPLATE/question-help.md +0 -29
- server/transformers/.github/stale.yml +0 -17
- server/transformers/.gitignore +0 -141
- server/transformers/.gitrepo +0 -12
- server/transformers/CONTRIBUTING.md +0 -258
- server/transformers/LICENSE +0 -202
- server/transformers/MANIFEST.in +0 -1
- server/transformers/Makefile +0 -24
- server/transformers/README.md +0 -684
- server/transformers/deploy_multi_version_doc.sh +0 -23
- server/transformers/docker/Dockerfile +0 -7
- server/transformers/docs/Makefile +0 -19
- server/transformers/docs/README.md +0 -67
- server/transformers/docs/source/_static/css/Calibre-Light.ttf +0 -0
- server/transformers/docs/source/_static/css/Calibre-Medium.otf +0 -0
- server/transformers/docs/source/_static/css/Calibre-Regular.otf +0 -0
- server/transformers/docs/source/_static/css/Calibre-Thin.otf +0 -0
- server/transformers/docs/source/_static/css/code-snippets.css +0 -12
- server/transformers/docs/source/_static/css/huggingface.css +0 -196
- server/transformers/docs/source/_static/js/custom.js +0 -79
- server/transformers/docs/source/_static/js/huggingface_logo.svg +0 -47
- server/transformers/docs/source/benchmarks.md +0 -54
server/spacyface/.gitignore
DELETED
@@ -1,22 +0,0 @@
|
|
1 |
-
.DS_Store
|
2 |
-
|
3 |
-
# Emacs specific
|
4 |
-
*~
|
5 |
-
.*~
|
6 |
-
#*
|
7 |
-
.#*
|
8 |
-
|
9 |
-
# Python
|
10 |
-
__pycache__
|
11 |
-
*.egg-info
|
12 |
-
.ipynb_checkpoints
|
13 |
-
.pytest_cache
|
14 |
-
|
15 |
-
# For holding files
|
16 |
-
.archive
|
17 |
-
|
18 |
-
# Notebooks that are not titled
|
19 |
-
Untitled*.ipynb
|
20 |
-
|
21 |
-
# For distribution on pip
|
22 |
-
dist
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/.gitrepo
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
; DO NOT EDIT (unless you know what you are doing)
|
2 |
-
;
|
3 |
-
; This subdirectory is a git "subrepo", and this file is maintained by the
|
4 |
-
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
|
5 |
-
;
|
6 |
-
[subrepo]
|
7 |
-
remote = [email protected]:bhoov/spacyface-dev.git
|
8 |
-
branch = master
|
9 |
-
commit = 1b1df2cb074876bc5a64f934f2aa2c6822d219c0
|
10 |
-
parent = 358151dfadb49f44770bb8e031bcb7e586ff858e
|
11 |
-
method = merge
|
12 |
-
cmdver = 0.4.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/LICENSE
DELETED
@@ -1,201 +0,0 @@
|
|
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 2020 Benjamin Hoover
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/README.md
DELETED
@@ -1,136 +0,0 @@
|
|
1 |
-
|
2 |
-
# Spacyface aligner
|
3 |
-
|
4 |
-
Align [Huggingface Transformer](https://github.com/huggingface/transformers) model tokenizations with linguistic metadata provided by [spaCy](https://spacy.io/)!
|
5 |
-
|
6 |
-
*Currently only supports English tokenizations*
|
7 |
-
|
8 |
-
## Getting started
|
9 |
-
|
10 |
-
### Pip
|
11 |
-
1. Run `pip install spacyface`.
|
12 |
-
2. `python -m spacy download en_core_web_sm`
|
13 |
-
|
14 |
-
### Manual (Clone and conda)
|
15 |
-
1. From the root of this project, create a new conda directory with `conda env create -f environment.yml`. This will create an environment named `spacyface`.
|
16 |
-
2. Activate this environment with `conda activate spacyface`. At this point, if you want to install the development dependencies, you can do so with `conda env update -f environment-dev.yml`
|
17 |
-
3. You will need to install spacy's `en_core_web_sm` as well. To do this, run: `python -m spacy download en_core_web_smo`
|
18 |
-
|
19 |
-
## Usage
|
20 |
-
### Basic Usage on a sentence
|
21 |
-
Every aligner can be created and used as described in the example below:
|
22 |
-
|
23 |
-
``` python
|
24 |
-
from aligner import BertAligner
|
25 |
-
|
26 |
-
alnr = BertAligner.from_pretrained("bert-base-cased")
|
27 |
-
sentence = "Do you know why they call me the Count? Because I love to count! Ah-hah-hah!"
|
28 |
-
tokens = alnr.meta_tokenize(sentence)
|
29 |
-
print("Tokens:\n\n", [(tok.token, tok.pos) for tok in tokens])
|
30 |
-
```
|
31 |
-
|
32 |
-
```
|
33 |
-
Tokens:
|
34 |
-
|
35 |
-
[('Do', 'AUX'), ('you', 'PRON'), ('know', 'VERB'), ('why', 'ADV'), ('they', 'PRON'), ('call', 'VERB'), ('me', 'PRON'), ('the', 'DET'), ('Count', 'PROPN'), ('?', 'PUNCT'), ('Because', 'SCONJ'), ('I', 'PRON'), ('love', 'VERB'), ('to', 'PART'), ('count', 'VERB'), ('!', 'PUNCT'), ('Ah', 'INTJ'), ('-', 'PUNCT'), ('ha', 'X'), ('##h', 'X'), ('-', 'PUNCT'), ('ha', 'NOUN'), ('##h', 'NOUN'), ('!', 'PUNCT')]
|
36 |
-
```
|
37 |
-
|
38 |
-
Because the information is coming directly from spaCy's `Token` class, any information that spaCy exposes about a token can be included in the huggingface token. The user only needs to modify the exposed attributes in the [SimpleSpacyToken](./aligners/simple_spacy_token) class.
|
39 |
-
|
40 |
-
This can also be extrapolated to tokenize entire English corpora with the use of a generator. An example raw corpus representing a subset of wikipedia is included in the [[./tests]] directory.
|
41 |
-
|
42 |
-
### Observing attention between linguistic features
|
43 |
-
This library also enables us to look at the attention pattern heatmaps for a particular layer and a particular head in terms of the linguistic features that belong to that layer and head.
|
44 |
-
|
45 |
-
``` python
|
46 |
-
alnr_cls = RobertaAligner
|
47 |
-
model_name = "roberta-base"
|
48 |
-
sentence = "A simple sentence for the ages."
|
49 |
-
layer = 8
|
50 |
-
heads = [7]
|
51 |
-
|
52 |
-
alnr = alnr_cls.from_pretrained(model_name)
|
53 |
-
model = AutoModel.from_pretrained(model_name, output_attentions=True)
|
54 |
-
model.eval() # Remove DropOut effect
|
55 |
-
|
56 |
-
model_input, meta_info = alnr.sentence_to_input(sentence)
|
57 |
-
|
58 |
-
_, _, atts = model(**model_input)
|
59 |
-
|
60 |
-
to_show = atts[layer][0][heads].mean(0)[1:-1, 1:-1] # Don't show special tokens for Roberta Model
|
61 |
-
|
62 |
-
deps = [t.dep for t in meta_info[1:-1]]
|
63 |
-
poss = [t.pos for t in meta_info[1:-1]]
|
64 |
-
|
65 |
-
plt.figure()
|
66 |
-
sn.set(font_scale=1.5)
|
67 |
-
sn.heatmap(to_show.detach().numpy(), xticklabels=deps, yticklabels=deps)
|
68 |
-
plt.title(f"Layer {layer} for head(s): {heads}\n\"{sentence}\"")
|
69 |
-
```
|
70 |
-
|
71 |
-
![Attention heatmap Layer 8 head 7](./img/SampleHeatmap.png)
|
72 |
-
|
73 |
-
Interestingly, we have discovered that Layer 8, head 7 has a strong affinity for a POBJ (Object of the Preposition) looking at a PREP (Preposition). Cool! We can then test this hypothesis by running example sentences that have multiple prepositions to see if it is looking at all prepositions or just the preposition related to the object.
|
74 |
-
|
75 |
-
|
76 |
-
## Background
|
77 |
-
Different transformer models use different tokenizations. At the time of this writing, many these tokenizations split larger English words into smaller tokens and use different methods of indicating that a token was once part of a larger word.
|
78 |
-
|
79 |
-
For inspection and research, it is helpful to align these tokenizations with the linguistic features of the original words of the sentence. [spaCy](https://spacy.io/) is a fantastic python library for assigning linguistic features (e.g., dependencies, parts of speech, tags, exceptions) to the words of different languages, but its method for tokenizing is vastly different from the tokenization schemes that typically operate on the sub-word and sometimes byte level. This repository aims to align spaCy tokens with the sub-word tokens needed for training and inference of the different [Huggingface Transformer](https://github.com/huggingface/transformers) models.
|
80 |
-
|
81 |
-
In short, *this repository enables the strange and varied tokenizations belonging to different transformer models to be correctly annotated with the metadata returned by spaCy's tokenization.*
|
82 |
-
|
83 |
-
Currently, the repository only supports the English language and the following huggingface pretrained models:
|
84 |
-
|
85 |
-
- Bert
|
86 |
-
- GPT2 (covers distilgpt2)
|
87 |
-
- Roberta (covers distilroberta)
|
88 |
-
- DistilBert
|
89 |
-
- TransfoXL
|
90 |
-
- XLNet
|
91 |
-
- XLM
|
92 |
-
- Albert
|
93 |
-
- CTRL
|
94 |
-
- OpenAIGPT
|
95 |
-
- XLMRoberta
|
96 |
-
|
97 |
-
At the time of release, the only model that doesn't work with the alignment is the T5 Tokenization scheme.
|
98 |
-
|
99 |
-
Originally created to ease the development of [exBERT](http://exbert.net/), these tools have been made available for others to use in their own projects as they see fit.
|
100 |
-
|
101 |
-
## Testing the aligner
|
102 |
-
A few edge case sentences that include hardcoded exceptions to the English language as well as strange punctuation have been included in [EN_TEST_SENTS.py](./tests/EN_TEST_SENTS.py). You can run these tests on the established aligners with `python -m pytest` from the root folder.
|
103 |
-
|
104 |
-
Sometimes, your application may not care about edge cases that are hard to detect. You can test an alignment on a more representative subset of the English language with the included [wikipedia subset](./tests/wiki.test.txt), or use your own text file corpus. To do this, run
|
105 |
-
|
106 |
-
``` python
|
107 |
-
from spacyface import TransfoXLAligner
|
108 |
-
from spacyface.checker import check_against_corpus
|
109 |
-
corpus = 'tests/wiki.test.txt'
|
110 |
-
alnr = TransfoXLAligner.from_pretrained('transfo-xl-wt103')
|
111 |
-
check_against_corpus(alnr, corpus)
|
112 |
-
```
|
113 |
-
|
114 |
-
and wait a few minutes to see if any sentences break.
|
115 |
-
|
116 |
-
## Notable Behavior and Exceptions
|
117 |
-
This repository makes the large assumption that there is no English "word" which is smaller than a token needed for a transformer model. This is an accurate assumption for most of the published transformer models.
|
118 |
-
|
119 |
-
It is difficult to align such completely different tokenization schemes. Namely, there are a few strange behaviors that, while not desired, are intentional to create a simplified methods to aligned different tokenization schemes. These behaviors are listed below.
|
120 |
-
|
121 |
-
- Multiple consecutive spaces in a sentence are replaced with a single space.
|
122 |
-
- Many tokenizers insert special tokens (e.g., "[CLS]", "[SEP]", "[MASK]", "\<s\>") for certain functionalities. The metadata for all these tokens is assigned to `None`.
|
123 |
-
- When a token exists as a part of a larger word, the linguistic information belonging to the larger word is bestowed on the token.
|
124 |
-
- The English language is riddled with exceptions to tokenization rules. Sometimes, a punctuation is included in the middle of what is a single token (e.g., "Mr." or "N.Y."). Other times, contractions that look nothing like the words it combines (e.g., "ain't" looks nothing like "is not" or "am not" or "are not") create difficulties for aligning. To prevent these from being an issue, this repository replaces the exceptions to the language with their original "normalized" representations.
|
125 |
-
|
126 |
-
**Specific to GPT2**
|
127 |
-
- Sometimes, GPT2 tokenization will include a space before a punctuation mark that should not have been there. For example, the tokenization of "Hello Bob." should be `["Hello", "ĠBob", "."]`, but it is instead `["Hello", "ĠBob", "Ġ."]` This has not had any notable effects on performance, but note that it is different from the way the original model was pretrained. Hidden representations may be slightly different.
|
128 |
-
|
129 |
-
### Known Issues
|
130 |
-
- A Spacy exception that is part of a `-`-delimited word (e.g. "dont-touch-me") will cause the meta tokenization to produce a different result from the tokenization strategy. See github issues for a more detailed description of this problem.
|
131 |
-
|
132 |
-
### Acknowledgements
|
133 |
-
|
134 |
-
- Benjamin Hoover (IBM Research & MIT-IBM Watson AI Lab)
|
135 |
-
- Hendrik Strobelt (IBM Research & MIT-IBM Watson AI Lab)
|
136 |
-
- Sebastian Gehrmann (Harvard NLP)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/environment-dev.yml
DELETED
@@ -1,24 +0,0 @@
|
|
1 |
-
name: spacyface
|
2 |
-
channels:
|
3 |
-
- conda-forge
|
4 |
-
dependencies:
|
5 |
-
- jupyter
|
6 |
-
- pytest
|
7 |
-
- jupyter_client
|
8 |
-
- jupyter_console
|
9 |
-
- jupyter_contrib_core
|
10 |
-
- jupyter_contrib_nbextensions
|
11 |
-
- matplotlib
|
12 |
-
|
13 |
-
name: spacyface
|
14 |
-
channels:
|
15 |
-
- conda-forge
|
16 |
-
dependencies:
|
17 |
-
- jupyter
|
18 |
-
- pytest
|
19 |
-
- jupyter_client
|
20 |
-
- jupyter_console
|
21 |
-
- jupyter_contrib_core
|
22 |
-
- jupyter_contrib_nbextensions
|
23 |
-
- matplotlib
|
24 |
-
- seaborn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/environment.yml
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
name: spacyface
|
2 |
-
channels:
|
3 |
-
- pytorch
|
4 |
-
- conda-forge
|
5 |
-
- defaults
|
6 |
-
- anaconda
|
7 |
-
dependencies:
|
8 |
-
- python=3.7
|
9 |
-
- pip>=19.0.3
|
10 |
-
- pytest
|
11 |
-
- h5py
|
12 |
-
- spacy
|
13 |
-
- regex
|
14 |
-
- numpy
|
15 |
-
- pytorch
|
16 |
-
- sacremoses
|
17 |
-
- pip:
|
18 |
-
- sentencepiece
|
19 |
-
- transformers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/img/SampleHeatmap.png
DELETED
Binary file (25.4 kB)
|
|
server/spacyface/setup.cfg
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
[metadata]
|
2 |
-
description-file = README.md
|
|
|
|
|
|
server/spacyface/setup.py
DELETED
@@ -1,31 +0,0 @@
|
|
1 |
-
from setuptools import setup, find_packages
|
2 |
-
|
3 |
-
requires = [
|
4 |
-
'transformers>=2.3.0',
|
5 |
-
'h5py>=2.10.0',
|
6 |
-
'numpy>=1.17.4',
|
7 |
-
'regex>=2020.1.8',
|
8 |
-
'spacy>=2.2.3',
|
9 |
-
'torch',
|
10 |
-
]
|
11 |
-
|
12 |
-
setup(
|
13 |
-
name="spacyface",
|
14 |
-
description="Aligner for spacy and huggingface tokenization",
|
15 |
-
packages=['spacyface'],
|
16 |
-
version='0.2.1',
|
17 |
-
license='Apache 2.0',
|
18 |
-
author="Ben Hoover",
|
19 |
-
author_email="[email protected]",
|
20 |
-
url="https://github.com/bhoov/spacyface",
|
21 |
-
keywords=["transformer", "pytorch", "spacy", "tokenize", "tokenization", "NLP", "Natural Language Processing",
|
22 |
-
"huggingface", "linguistic"],
|
23 |
-
include_package_data=True,
|
24 |
-
install_requires=requires,
|
25 |
-
classifiers=[
|
26 |
-
'Development Status :: 3 - Alpha',
|
27 |
-
'Programming Language :: Python :: 3.6',
|
28 |
-
'Programming Language :: Python :: 3.7',
|
29 |
-
],
|
30 |
-
python_requires='>=3.6, <3.8'
|
31 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/__init__.py
DELETED
@@ -1,23 +0,0 @@
|
|
1 |
-
from .aligner import (
|
2 |
-
MakeAligner,
|
3 |
-
BertAligner,
|
4 |
-
GPT2Aligner,
|
5 |
-
RobertaAligner,
|
6 |
-
DistilBertAligner,
|
7 |
-
TransfoXLAligner,
|
8 |
-
XLNetAligner,
|
9 |
-
AlbertAligner,
|
10 |
-
XLMAligner,
|
11 |
-
CTRLAligner,
|
12 |
-
OpenAIGPTAligner,
|
13 |
-
T5Aligner,
|
14 |
-
XLMRobertaAligner,
|
15 |
-
auto_aligner
|
16 |
-
|
17 |
-
)
|
18 |
-
|
19 |
-
from .simple_spacy_token import SimpleSpacyToken
|
20 |
-
|
21 |
-
__all__ = ["MakeAligner", "SimpleSpacyToken", "BertAligner", "GPT2Aligner", "RobertaAligner", "DistilBertAligner",
|
22 |
-
"TransfoXLAligner", "XLNetAligner", "AlbertAligner", "XLMAligner", "AlbertAligner",
|
23 |
-
"CTRLAligner", "OpenAIGPTAligner", "T5Aligner", "XLMRobertaAligner", "auto_aligner"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/aligner.py
DELETED
@@ -1,261 +0,0 @@
|
|
1 |
-
from typing import List, Iterable, Union
|
2 |
-
import spacy
|
3 |
-
from spacy.tokens.token import Token as SpacyToken
|
4 |
-
from spacy.tokens.doc import Doc as SpacyDoc
|
5 |
-
import torch
|
6 |
-
import regex as re
|
7 |
-
|
8 |
-
from transformers import (
|
9 |
-
AutoTokenizer,
|
10 |
-
BertTokenizer,
|
11 |
-
GPT2Tokenizer,
|
12 |
-
RobertaTokenizer,
|
13 |
-
DistilBertTokenizer,
|
14 |
-
TransfoXLTokenizer,
|
15 |
-
XLNetTokenizer,
|
16 |
-
XLMTokenizer,
|
17 |
-
AlbertTokenizer,
|
18 |
-
CTRLTokenizer,
|
19 |
-
T5Tokenizer,
|
20 |
-
XLMRobertaTokenizer,
|
21 |
-
OpenAIGPTTokenizer,
|
22 |
-
XLMRobertaTokenizer,
|
23 |
-
AutoTokenizer,
|
24 |
-
)
|
25 |
-
|
26 |
-
from .simple_spacy_token import SimpleSpacyToken
|
27 |
-
from .utils.f import flatten_, assoc, delegates, memoize
|
28 |
-
|
29 |
-
def doc_to_fixed_tokens(doc: SpacyDoc) -> List[str]:
|
30 |
-
"""Fix the tokens in a document to not have exceptions"""
|
31 |
-
return [fix_token(t) for t in doc]
|
32 |
-
|
33 |
-
def fix_token(tok: SpacyToken) -> str:
|
34 |
-
"""Determine whether a token should be represented by its text or its norm
|
35 |
-
|
36 |
-
This works to fix most instances EXCEPT when an exception is part of a word with a '-' in it.
|
37 |
-
For example, "whatve-you-done" would produce two different tokenizations:
|
38 |
-
|
39 |
-
>>> alnr = BertAligner.from_pretrained('bert-base-uncased')
|
40 |
-
>>> s = "whatve-you-dont"
|
41 |
-
>>> alnr.tokenize(s) # => ['what', '##ve', '-', 'you', '-', 'don', '##t']
|
42 |
-
>>> [t.token for t in alnr.meta_tokenize(s)] # => ['what', 'have', '-', 'you', '-', 'do', 'not']
|
43 |
-
|
44 |
-
In practice, this situation occurs so rarely that it is often not a problem for real sentences to analyze.
|
45 |
-
"""
|
46 |
-
out = tok.text if tok.text.lower() == tok.norm_ else tok.norm_
|
47 |
-
|
48 |
-
return out
|
49 |
-
|
50 |
-
def MakeAligner(pretrained_tokenizer, spacy_language_model):
|
51 |
-
"""Create an aligner from the pretrained tokenizers. Some caveats to note:
|
52 |
-
|
53 |
-
Usage:
|
54 |
-
BrandNewHuggingfaceAligner = MakeAligner(BrandNewHuggingfaceTokenizer)
|
55 |
-
"""
|
56 |
-
class Aligner(pretrained_tokenizer):
|
57 |
-
@delegates(pretrained_tokenizer.__init__)
|
58 |
-
def __init__(self, **kwargs):
|
59 |
-
super().__init__(**kwargs)
|
60 |
-
self.spacy_nlp = spacy.load(spacy_language_model)
|
61 |
-
self.meta_container = SimpleSpacyToken
|
62 |
-
|
63 |
-
def prep_sentence(self, s: str) -> str:
|
64 |
-
"""Remove contractions and multiple spaces from input sentence"""
|
65 |
-
s = re.sub(r"\s+", r" ", s).strip()
|
66 |
-
out = " ".join(self._to_normed_spacy(s))
|
67 |
-
return out
|
68 |
-
|
69 |
-
@delegates(pretrained_tokenizer.tokenize)
|
70 |
-
def tokenize(self, s: str, **kwargs) -> List[str]:
|
71 |
-
s = self.prep_sentence(s)
|
72 |
-
return super().tokenize(s, **kwargs)
|
73 |
-
|
74 |
-
def meta_tokenize(self, s: str) -> List[SimpleSpacyToken]:
|
75 |
-
"""Tokenize the sentence and return the metadata for it according to Spacy
|
76 |
-
|
77 |
-
Due to implementation differences, does not provide the exact same API as the
|
78 |
-
PreTrainedTokenizer's `tokenize` function
|
79 |
-
"""
|
80 |
-
meta_info = self._to_spacy_meta(self.prep_sentence(s))
|
81 |
-
return self._tokenize_from_spacy_meta(meta_info)
|
82 |
-
|
83 |
-
def meta_from_tokens(self, sentence: str, tokens: List[str], perform_check=True) -> List[SimpleSpacyToken]:
|
84 |
-
"""Convert existing tokens into their metadata, ignoring effects of special tokens from the tokenizer
|
85 |
-
|
86 |
-
NOTE that the sentence MUST be the same sentence that produced the tokens, otherwise,
|
87 |
-
an unpredictable error may occur. Or worse, it will act like it works when it in fact doesn't.
|
88 |
-
|
89 |
-
Parameters:
|
90 |
-
- sentence: Sentence the tokens came from
|
91 |
-
- tokens: Tokenized version of the sentence. Can be post encoding or pre-encoding
|
92 |
-
(where special tokens are added)
|
93 |
-
- perform_check: If True, check that the tokens come from the sentence. This slows down processing
|
94 |
-
and should be False if speed is more important than accuracy
|
95 |
-
"""
|
96 |
-
orig_meta = self.meta_tokenize(sentence)
|
97 |
-
|
98 |
-
new_meta = []
|
99 |
-
j = 0
|
100 |
-
|
101 |
-
# Unfortunately, this can really slow down predictions.
|
102 |
-
if perform_check:
|
103 |
-
is_encoded = self.encode(sentence) == self.convert_tokens_to_ids(tokens)
|
104 |
-
is_tokenized = self.tokenize(sentence) == tokens
|
105 |
-
assert is_encoded or is_tokenized, "Can only take tokens that come from the original sentence!"
|
106 |
-
|
107 |
-
for i, b in enumerate(tokens):
|
108 |
-
if b in self.all_special_tokens:
|
109 |
-
new_meta.append(self.meta_container(b))
|
110 |
-
else:
|
111 |
-
new_meta.append(orig_meta[j])
|
112 |
-
j += 1
|
113 |
-
|
114 |
-
return new_meta
|
115 |
-
|
116 |
-
def _to_normed_spacy(self, s: str) -> List[str]:
|
117 |
-
"""Return the normalized tokens (i.e., language exceptions replaced by a lowercased version)"""
|
118 |
-
doc = self.spacy_nlp(s)
|
119 |
-
tokens = self._doc_to_fixed_tokens(doc)
|
120 |
-
return tokens
|
121 |
-
|
122 |
-
def _to_spacy_meta(self, s: str) -> List[SimpleSpacyToken]: # list of simple spacy tokens...
|
123 |
-
"""Convert a string into a list of records containing simplified spacy information"""
|
124 |
-
doc = self.spacy_nlp(s)
|
125 |
-
out = [self.meta_container(t) for t in doc]
|
126 |
-
return out
|
127 |
-
|
128 |
-
@delegates(pretrained_tokenizer.tokenize)
|
129 |
-
def _raw_tokenize(self, s: str, **kwargs) -> List[str]:
|
130 |
-
"""This bypasses the custom tokenization for the tokenization of the original model."""
|
131 |
-
return super().tokenize(s, **kwargs)
|
132 |
-
|
133 |
-
def _to_raw_spacy(self, s: str) -> List[str]:
|
134 |
-
"""Return the raw spacy tokens of a string"""
|
135 |
-
doc = self.spacy_nlp(s)
|
136 |
-
tokens = [t.text for t in doc]
|
137 |
-
return tokens
|
138 |
-
|
139 |
-
def _tokenize_from_spacy_meta(self, spacy_meta: List[SimpleSpacyToken]) -> List[SimpleSpacyToken]:
|
140 |
-
"""Convert spacy-tokenized SimpleSpacyTokens into the appropriate tokenizer's tokens"""
|
141 |
-
out = [self._tokenize_from_meta_single(sm, i) for i, sm in enumerate(spacy_meta)]
|
142 |
-
return flatten_(out)
|
143 |
-
|
144 |
-
def _tokenize_from_meta_single(self, meta_token: SimpleSpacyToken, idx:int) -> List[SimpleSpacyToken]:
|
145 |
-
"""Split a single spacy token with metadata into tokenizer tokens.
|
146 |
-
|
147 |
-
Because the transformer's tokenizer may split each Spacy-tokenized word into multiple subwords,
|
148 |
-
output a list
|
149 |
-
|
150 |
-
For GPT2 tokenization, there is a different behavior for the tokenization of a word if it
|
151 |
-
starts the sentence vs if it occurs later in the sentence.
|
152 |
-
"""
|
153 |
-
BUFFER = "X " # GPT tokenization fusses if it thinks the token is the beginning of the sentence
|
154 |
-
|
155 |
-
def choose_norm(t):
|
156 |
-
return t['token'] if t['token'].lower() == t['norm'] else t['norm']
|
157 |
-
|
158 |
-
tok = choose_norm(meta_token)
|
159 |
-
|
160 |
-
if idx != 0:
|
161 |
-
s = BUFFER + tok # Add a buffer with guaranteed tokenization of length 1 to input
|
162 |
-
offset = 1
|
163 |
-
else:
|
164 |
-
s = tok
|
165 |
-
offset = 0
|
166 |
-
|
167 |
-
bpe_tokens = super().tokenize(s) # Can't do `self.tokenize` because it will normalize again
|
168 |
-
|
169 |
-
# Functional version that works with dictionaries
|
170 |
-
return [meta_token.assoc("token", b) for b in bpe_tokens[offset:]]
|
171 |
-
|
172 |
-
def _doc_to_fixed_tokens(self, doc: SpacyDoc) -> List[str]:
|
173 |
-
"""Extract tokens from a document, accounting for exceptions only if needed"""
|
174 |
-
tokens = doc_to_fixed_tokens(doc)
|
175 |
-
return tokens
|
176 |
-
|
177 |
-
def _maybe_conv_to_token(self, tok_or_str:Union[str, SimpleSpacyToken]):
|
178 |
-
"""Convert a token to a SimpleSpacy token if a string. Otherwise, return input unmodified
|
179 |
-
|
180 |
-
Args:
|
181 |
-
tok_or_str: The token be analyzed
|
182 |
-
|
183 |
-
Returns:
|
184 |
-
SimpleSpacyToken. If input was a string, it has been converted to this class.
|
185 |
-
"""
|
186 |
-
|
187 |
-
if isinstance(tok_or_str, SimpleSpacyToken):
|
188 |
-
return tok_or_str
|
189 |
-
return SimpleSpacyToken(self.convert_ids_to_tokens([tok_or_str])[0])
|
190 |
-
|
191 |
-
def sentence_to_input(self, sentence:str):
|
192 |
-
"""Convert sentence to the input needed for a huggingface model
|
193 |
-
|
194 |
-
Args:
|
195 |
-
sentence: Sentence to prepare to send into the model
|
196 |
-
|
197 |
-
Returns:
|
198 |
-
Tuple of (object that can be directly passed into the model, modified meta tokens)
|
199 |
-
|
200 |
-
Examples:
|
201 |
-
|
202 |
-
>>> alnr = RobertaAligner.from_pretrained('roberta-base')
|
203 |
-
>>> model = AutoModel.from_pretrained('roberta-base', output_attentions=True)
|
204 |
-
>>> model.eval() # Remove DropOut effect
|
205 |
-
>>> model_input, meta_info = alnr.sentence_to_input(sentence)
|
206 |
-
>>> last_layer_hidden_state, pooler, atts = model(**model_input)
|
207 |
-
"""
|
208 |
-
|
209 |
-
meta_tokens = self.meta_tokenize(sentence)
|
210 |
-
tokens = [tok.token for tok in meta_tokens]
|
211 |
-
ids = self.convert_tokens_to_ids(tokens)
|
212 |
-
raw_model_input = self.prepare_for_model(ids, add_special_tokens=True)
|
213 |
-
model_input = {k: torch.tensor(v).unsqueeze(0) for k,v in raw_model_input.items() if isinstance(v, List)}
|
214 |
-
|
215 |
-
meta_input = self.prepare_for_model(meta_tokens)['input_ids']
|
216 |
-
new_meta = list(map(self._maybe_conv_to_token, meta_input))
|
217 |
-
|
218 |
-
return model_input, new_meta
|
219 |
-
|
220 |
-
def check_tokenization(self, sentence:str, hard_assert=True):
|
221 |
-
tokens = self.tokenize(sentence)
|
222 |
-
meta_tokens = self.meta_tokenize(sentence)
|
223 |
-
mtokens = [m.token for m in meta_tokens]
|
224 |
-
|
225 |
-
error_str = """Meta tokenization did not match expected tokenization!
|
226 |
-
|
227 |
-
EXPECTED:
|
228 |
-
{}
|
229 |
-
|
230 |
-
META TOKENS REPORTED:
|
231 |
-
{}
|
232 |
-
|
233 |
-
"""
|
234 |
-
is_fine = mtokens == tokens
|
235 |
-
|
236 |
-
if hard_assert:
|
237 |
-
assert is_fine, error_str.format(tokens, mtokens)
|
238 |
-
else:
|
239 |
-
if not is_fine: print(error_str.format(tokens, mtokens))
|
240 |
-
|
241 |
-
return Aligner
|
242 |
-
|
243 |
-
english = "en_core_web_sm"
|
244 |
-
|
245 |
-
BertAligner = MakeAligner(BertTokenizer, english)
|
246 |
-
GPT2Aligner = MakeAligner(GPT2Tokenizer, english)
|
247 |
-
RobertaAligner = MakeAligner(RobertaTokenizer, english)
|
248 |
-
DistilBertAligner = MakeAligner(DistilBertTokenizer, english)
|
249 |
-
TransfoXLAligner = MakeAligner(TransfoXLTokenizer, english)
|
250 |
-
XLNetAligner = MakeAligner(XLNetTokenizer, english)
|
251 |
-
XLMAligner = MakeAligner(XLMTokenizer, english)
|
252 |
-
CTRLAligner = MakeAligner(CTRLTokenizer, english)
|
253 |
-
AlbertAligner = MakeAligner(AlbertTokenizer, english)
|
254 |
-
OpenAIGPTAligner= MakeAligner(OpenAIGPTTokenizer, english)
|
255 |
-
T5Aligner= MakeAligner(T5Tokenizer, english)
|
256 |
-
XLMRobertaAligner= MakeAligner(XLMRobertaTokenizer, english)
|
257 |
-
|
258 |
-
@memoize
|
259 |
-
def auto_aligner(pretrained_name_or_path):
|
260 |
-
tok_class = AutoTokenizer.from_pretrained(pretrained_name_or_path).__class__
|
261 |
-
return MakeAligner(tok_class, english).from_pretrained(pretrained_name_or_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/checker/__init__.py
DELETED
@@ -1,4 +0,0 @@
|
|
1 |
-
"""Use to verify an aligner for a particular application"""
|
2 |
-
from .against_corpus import check_against_corpus
|
3 |
-
|
4 |
-
__all__ = ["check_against_corpus"]
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/checker/against_corpus.py
DELETED
@@ -1,26 +0,0 @@
|
|
1 |
-
"""This module provides a a means to test an aligner against a desired corpus"""
|
2 |
-
|
3 |
-
from pathlib import Path
|
4 |
-
import argparse
|
5 |
-
from spacyface.utils.sentence_extracting import extract_chars
|
6 |
-
from spacyface import *
|
7 |
-
|
8 |
-
|
9 |
-
def check_against_corpus(alnr, corpus_name, hard_assert=True):
|
10 |
-
"""Go through every sentence of the corpus and see if the meta tokenization is different than base transformer tokenization
|
11 |
-
|
12 |
-
Args:
|
13 |
-
alnr: Aligner
|
14 |
-
corpus_name: Name of text file to parse
|
15 |
-
hard_assert: If True, break on first error. Otherwise, print error msg and continue
|
16 |
-
"""
|
17 |
-
src = open(corpus_name)
|
18 |
-
chunk_gen = extract_chars(src, 100000)
|
19 |
-
for c, chunk in enumerate(chunk_gen):
|
20 |
-
doc = alnr.spacy_nlp(chunk)
|
21 |
-
sents = [sent.text for sent in doc.sents]
|
22 |
-
for i, sent in enumerate(sents):
|
23 |
-
if i % 100 == 0: print(f"Chunk {c}. Sentence {i}")
|
24 |
-
alnr.check_tokenization(sent, hard_assert)
|
25 |
-
|
26 |
-
src.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/simple_spacy_token.py
DELETED
@@ -1,155 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
Describes the structure of a language token represented by Spacy-extracted metadata
|
3 |
-
|
4 |
-
"""
|
5 |
-
import h5py
|
6 |
-
import numpy as np
|
7 |
-
from spacy.tokens.token import Token as SpacyToken
|
8 |
-
from typing import Union, List, Tuple
|
9 |
-
|
10 |
-
|
11 |
-
def check_ent(tok: SpacyToken):
|
12 |
-
"""Check whether token is an entity
|
13 |
-
|
14 |
-
Default Spacy Token does not assume what kind of entity you are looking for, but
|
15 |
-
provides the following denotations:
|
16 |
-
|
17 |
-
0: No entity tag is set
|
18 |
-
1: inside an entity
|
19 |
-
2: outside an entity
|
20 |
-
3: Token begins an entity
|
21 |
-
|
22 |
-
Args:
|
23 |
-
tok: The Spacy Token
|
24 |
-
|
25 |
-
Returns:
|
26 |
-
Boolean indicating whether or not token is an entity
|
27 |
-
"""
|
28 |
-
OUT_OF_ENT = 2
|
29 |
-
NO_ENT_DEFINED = 0
|
30 |
-
return tok.ent_iob != OUT_OF_ENT and tok.ent_iob != NO_ENT_DEFINED
|
31 |
-
|
32 |
-
class SimpleSpacyToken():
|
33 |
-
"""A wrapper around a Spacy token to extract desired information
|
34 |
-
|
35 |
-
This class implements a basic functional dictionary-like wrapper around the spacy token to
|
36 |
-
make it easy to mutate and export attributes without directly changing state. Any attribute
|
37 |
-
that is not prefixed by '_' is considered a key of this class.
|
38 |
-
|
39 |
-
The design allows for the token to have no metadata by simply passing a `str` into
|
40 |
-
the constructor.
|
41 |
-
|
42 |
-
Attributes:
|
43 |
-
token: str
|
44 |
-
pos: str
|
45 |
-
dep: str
|
46 |
-
norm: str
|
47 |
-
tag: str
|
48 |
-
lemma: str
|
49 |
-
head: str
|
50 |
-
is_ent: bool
|
51 |
-
|
52 |
-
Notes:
|
53 |
-
If exporting to an HDF5 file, make sure to define what hdf5 datatype that attribute
|
54 |
-
represents by changing the corresponding tuple in 'hdf5_token_dtype'
|
55 |
-
"""
|
56 |
-
|
57 |
-
# Define how each attribute is stored in an hdf5 file
|
58 |
-
# Names MUST match attributes of this class
|
59 |
-
hdf5_token_dtype = [
|
60 |
-
("token", h5py.special_dtype(vlen=str)),
|
61 |
-
("pos", h5py.special_dtype(vlen=str)),
|
62 |
-
("dep", h5py.special_dtype(vlen=str)),
|
63 |
-
("norm", h5py.special_dtype(vlen=str)),
|
64 |
-
("tag", h5py.special_dtype(vlen=str)),
|
65 |
-
("lemma", h5py.special_dtype(vlen=str)),
|
66 |
-
("head", h5py.special_dtype(vlen=str)),
|
67 |
-
("is_ent", np.bool_),
|
68 |
-
]
|
69 |
-
|
70 |
-
def __init__(self, t:Union[SpacyToken, str]):
|
71 |
-
"""Create a simplified version of a spacy token
|
72 |
-
|
73 |
-
Args:
|
74 |
-
t: A string or Spacy Token object to wrap
|
75 |
-
|
76 |
-
Raises:
|
77 |
-
ValueError: If input is not of type SpacyToken or str
|
78 |
-
"""
|
79 |
-
self._orig_token = t
|
80 |
-
|
81 |
-
if type(t) == SpacyToken:
|
82 |
-
self.token = t.text
|
83 |
-
self.pos = t.pos_
|
84 |
-
self.dep = t.dep_
|
85 |
-
self.norm = t.norm_
|
86 |
-
self.tag = t.tag_
|
87 |
-
self.lemma = t.lemma_
|
88 |
-
self.head = t.head
|
89 |
-
self.is_ent = check_ent(t)
|
90 |
-
|
91 |
-
elif type(t) == str:
|
92 |
-
self.token = t
|
93 |
-
self.pos = None
|
94 |
-
self.dep = None
|
95 |
-
self.norm = None
|
96 |
-
self.tag = None
|
97 |
-
self.lemma = None
|
98 |
-
self.head = None
|
99 |
-
self.is_ent = None
|
100 |
-
|
101 |
-
else:
|
102 |
-
raise ValueError("Expected input of SpacyToken or str")
|
103 |
-
|
104 |
-
def pick(self, keys:List[str]):
|
105 |
-
"""Return subset of the attributes specified in 'keys' as a simple dictioniary
|
106 |
-
|
107 |
-
Args:
|
108 |
-
keys: List of keys to extract
|
109 |
-
|
110 |
-
Returns:
|
111 |
-
Dictionary of only k in keys
|
112 |
-
|
113 |
-
Raises:
|
114 |
-
KeyError: If k in 'keys' is not an attribute
|
115 |
-
|
116 |
-
"""
|
117 |
-
return {k: self[k] for k in keys}
|
118 |
-
|
119 |
-
def assoc(self, key:str, value):
|
120 |
-
"""Set the 'key' to the 'value', returning a new instance of this class.
|
121 |
-
|
122 |
-
Args:
|
123 |
-
key: Key that receives the value
|
124 |
-
value: Value to assign to the key
|
125 |
-
|
126 |
-
Returns:
|
127 |
-
A new instance of this class with the modified key:value pair
|
128 |
-
"""
|
129 |
-
out = SimpleSpacyToken(self._orig_token)
|
130 |
-
out[key] = value
|
131 |
-
return out
|
132 |
-
|
133 |
-
def __getitem__(self, key):
|
134 |
-
"""Access the key from this objects dictionary"""
|
135 |
-
return self.__dict__[key]
|
136 |
-
|
137 |
-
def __setitem__(self, key, value):
|
138 |
-
"""Assign, in place, the value to the key"""
|
139 |
-
self.__dict__[key] = value
|
140 |
-
|
141 |
-
def keys(self) -> List[str]:
|
142 |
-
"""Return a list of all attributes that don't start with '_'"""
|
143 |
-
return [k for k in self.__dict__.keys() if not k.startswith('_')]
|
144 |
-
|
145 |
-
def values(self) -> List:
|
146 |
-
"""Return a list of all values whose keys don't start with '_'"""
|
147 |
-
|
148 |
-
return [v for _, v in self.__dict__.items() if not k.startswith('_')]
|
149 |
-
|
150 |
-
def items(self) -> List[Tuple]:
|
151 |
-
"""Return a list of all items whose keys don't start with '_'"""
|
152 |
-
return [(k, v) for k,v in self.__dict__.items() if not k.startswith('_')]
|
153 |
-
|
154 |
-
def __repr__(self):
|
155 |
-
return f"SimpleSpacyToken: {self.items()}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/utils/f.py
DELETED
@@ -1,103 +0,0 @@
|
|
1 |
-
"""General programming utils, inclined toward functional programming.
|
2 |
-
|
3 |
-
If ever a function changes its input in place, it is denoted by a trailing `_`
|
4 |
-
"""
|
5 |
-
|
6 |
-
import inspect
|
7 |
-
from itertools import zip_longest
|
8 |
-
from typing import List, Set, Union, Dict
|
9 |
-
|
10 |
-
|
11 |
-
def ifnone(*xs):
|
12 |
-
"""Return the first item in 'x' that is not None"""
|
13 |
-
for x in xs:
|
14 |
-
if x is not None: return x
|
15 |
-
return None
|
16 |
-
|
17 |
-
def custom_dir(c, add): return dir(type(c)) + list(c.__dict__.keys()) + add
|
18 |
-
|
19 |
-
class GetAttr:
|
20 |
-
"""Base class for attr accesses in `self._xtra` passed down to `self.default`
|
21 |
-
|
22 |
-
Taken from article by Jeremy Howard: https://www.fast.ai/2019/08/06/delegation/
|
23 |
-
|
24 |
-
Usage:
|
25 |
-
|
26 |
-
```
|
27 |
-
class ProductPage(GetAttr):
|
28 |
-
def __init__(self, page, price, cost):
|
29 |
-
self.page,self.price,self.cost = page,price,cost
|
30 |
-
self.default = page
|
31 |
-
```
|
32 |
-
"""
|
33 |
-
@property
|
34 |
-
def _xtra(self): return [o for o in dir(self.default) if not o.startswith('_')]
|
35 |
-
def __getattr__(self,k):
|
36 |
-
if k in self._xtra: return getattr(self.default, k)
|
37 |
-
raise AttributeError(k)
|
38 |
-
def __dir__(self): return custom_dir(self, self._xtra)
|
39 |
-
|
40 |
-
# Can i delegate many different functions?
|
41 |
-
# Can i add a new docstring to the existing docstring of the delgated function? Or at least point to the function delegated?
|
42 |
-
def delegates(to=None, keep=False):
|
43 |
-
""" Decorator: replace `**kwargs` in signature with params from `to`.
|
44 |
-
|
45 |
-
Taken from article by Jeremy Howard: https://www.fast.ai/2019/08/06/delegation/
|
46 |
-
"""
|
47 |
-
|
48 |
-
def _f(f):
|
49 |
-
if to is None: to_f,from_f = f.__base__.__init__,f.__init__
|
50 |
-
else: to_f,from_f = to,f
|
51 |
-
sig = inspect.signature(from_f)
|
52 |
-
sigd = dict(sig.parameters)
|
53 |
-
k = sigd.pop('kwargs')
|
54 |
-
s2 = {k:v for k,v in inspect.signature(to_f).parameters.items()
|
55 |
-
if v.default != inspect.Parameter.empty and k not in sigd}
|
56 |
-
sigd.update(s2)
|
57 |
-
if keep: sigd['kwargs'] = k
|
58 |
-
from_f.__signature__ = sig.replace(parameters=sigd.values())
|
59 |
-
return f
|
60 |
-
return _f
|
61 |
-
|
62 |
-
def pick(keys:Union[List, Set], obj:Dict) -> Dict:
|
63 |
-
""" Return a NEW object containing `keys` from the original `obj` """
|
64 |
-
return {k: obj[k] for k in keys}
|
65 |
-
|
66 |
-
def memoize(f):
|
67 |
-
"""Memoize a function.
|
68 |
-
|
69 |
-
Use lookup table when the same inputs are passed to the function instead of running that function again
|
70 |
-
"""
|
71 |
-
memo = {}
|
72 |
-
def helper(*x):
|
73 |
-
if x not in memo:
|
74 |
-
memo[x] = f(*x)
|
75 |
-
return memo[x]
|
76 |
-
return helper
|
77 |
-
|
78 |
-
def assoc(k, v, orig):
|
79 |
-
"""Given an original dictionary orig, return a cloned dictionary with `k` set to `v`"""
|
80 |
-
out = orig.copy()
|
81 |
-
out[k] = v
|
82 |
-
return out
|
83 |
-
|
84 |
-
def make_unique(f):
|
85 |
-
"""The input function will only run and return if it hasn't seen its argument before.
|
86 |
-
|
87 |
-
Otherwise, it will return `None`.
|
88 |
-
"""
|
89 |
-
s = set()
|
90 |
-
def helper(x):
|
91 |
-
if x in s:
|
92 |
-
return None
|
93 |
-
s.add(x)
|
94 |
-
return f(x)
|
95 |
-
|
96 |
-
return helper
|
97 |
-
|
98 |
-
def flatten_(items, seqtypes=(list, tuple)):
|
99 |
-
"""Flattten an arbitrarily nested list IN PLACE"""
|
100 |
-
for i, x in enumerate(items):
|
101 |
-
while i < len(items) and isinstance(items[i], seqtypes):
|
102 |
-
items[i:i+1] = items[i]
|
103 |
-
return items
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/spacyface/utils/sentence_extracting.py
DELETED
@@ -1,176 +0,0 @@
|
|
1 |
-
"""Extractor functions to retrieve sentences by character chunks from a file
|
2 |
-
|
3 |
-
This script contains the logic that allows the user to process and filter
|
4 |
-
sentences of the original corpus. By default, this considers a minimum sentence
|
5 |
-
length, and removes newlines and multiple consecutive spaces.
|
6 |
-
|
7 |
-
Configuration for existing functionality is at the top of the file. Feel free to
|
8 |
-
add new processing and/or filter functions. The "process_line" and "filter_line"
|
9 |
-
functions contain the pipeline for processing the scripts as needed.
|
10 |
-
|
11 |
-
"""
|
12 |
-
import regex as re
|
13 |
-
import argparse
|
14 |
-
from pathlib import Path
|
15 |
-
from functools import partial
|
16 |
-
from typing import Union
|
17 |
-
|
18 |
-
MIN_LINE_LENGTH = 8 # words
|
19 |
-
|
20 |
-
def parse_args():
|
21 |
-
parser = argparse.ArgumentParser()
|
22 |
-
parser.add_argument("-f", "--file", help="Path to .txt file to analyze and annotate")
|
23 |
-
parser.add_argument("-o", "--outdir", help="Path of directory in which to store the analyzed sentences as a .pckl")
|
24 |
-
|
25 |
-
|
26 |
-
args = parser.parse_args()
|
27 |
-
return args
|
28 |
-
|
29 |
-
# ============================================================
|
30 |
-
# Helper functions
|
31 |
-
# ============================================================
|
32 |
-
# String -> String
|
33 |
-
def replace_newlines(s:str) -> str:
|
34 |
-
return re.sub(r"\n+", r" ", s)
|
35 |
-
|
36 |
-
# String -> String
|
37 |
-
def replace_multispace(s:str) -> str:
|
38 |
-
return re.sub(r"\s+", r" ", s)
|
39 |
-
|
40 |
-
def is_short_sentence(s:str, min_len=8) -> str:
|
41 |
-
"""Returns True if the sentence has less than `min_len` number of words"""
|
42 |
-
return len(s.split(' ')) < min_len
|
43 |
-
|
44 |
-
def contains_char(char:str, s:str) -> str:
|
45 |
-
return char in s
|
46 |
-
|
47 |
-
# ============================================================
|
48 |
-
# Compilation functions
|
49 |
-
# ============================================================
|
50 |
-
|
51 |
-
def process_line(line:str) -> str:
|
52 |
-
""""Replaces newlines with spaces and removes multiple consecutive spaces from a chunk of file.
|
53 |
-
|
54 |
-
Args:
|
55 |
-
line: Chunk of text
|
56 |
-
|
57 |
-
Returns:
|
58 |
-
Input that has been stripped of newlines and multiple consecutive spaces.
|
59 |
-
"""
|
60 |
-
s = replace_multispace(replace_newlines(line))
|
61 |
-
return s
|
62 |
-
|
63 |
-
def filter_line(line:str) -> bool:
|
64 |
-
"""Returns True if the sentence passes the MIN_LINE_LENGTH configuration
|
65 |
-
|
66 |
-
Redefine this function with desired helper functions, returning true if you want to keep the line
|
67 |
-
"""
|
68 |
-
fails = is_short_sentence(line, MIN_LINE_LENGTH)
|
69 |
-
|
70 |
-
return not fails
|
71 |
-
|
72 |
-
# ============================================================
|
73 |
-
# Main Logic
|
74 |
-
# ============================================================
|
75 |
-
|
76 |
-
def read_outcomes(chars:str) -> Union[str, None]:
|
77 |
-
"""From a chunk of characters, decide whether to return the processed characters or Nothing.
|
78 |
-
|
79 |
-
If the input is the empty string "", raise StopIteration
|
80 |
-
|
81 |
-
Args:
|
82 |
-
chars: Chunk of text to process
|
83 |
-
|
84 |
-
Returns:
|
85 |
-
The processed chunk of text or nothing if the characters do not pass the filtering
|
86 |
-
|
87 |
-
Raises:
|
88 |
-
StopIteration: If the input is the empty string "", raise StopIteration
|
89 |
-
"""
|
90 |
-
|
91 |
-
if chars == '': raise StopIteration
|
92 |
-
line = process_line(chars)
|
93 |
-
if filter_line(line): return line
|
94 |
-
return None
|
95 |
-
|
96 |
-
def get_chars(n:int, f) -> Union[str, None]:
|
97 |
-
"""Extract `n` chars from opened file `f`
|
98 |
-
|
99 |
-
Args:
|
100 |
-
n: Number of characters to read from the opened file
|
101 |
-
f: Opened file from the return of `open(fname)`
|
102 |
-
|
103 |
-
Returns:
|
104 |
-
The processed chunk of text or nothing if the characters do not pass the filtering
|
105 |
-
|
106 |
-
Raises:
|
107 |
-
This function does not raise any errors of its own, but can pass up the StopIteration exception
|
108 |
-
from read_outcomes
|
109 |
-
"""
|
110 |
-
chars = f.read(n)
|
111 |
-
return read_outcomes(chars)
|
112 |
-
|
113 |
-
def get_line(f):
|
114 |
-
"""Given an open file, get the next line and process it. Handles 3 scenarios:
|
115 |
-
|
116 |
-
1. StopIteration indicates the opened file has reached the end
|
117 |
-
2. Return a processed line if it passes the filter
|
118 |
-
3. If line does not pass the filter line, return None
|
119 |
-
"""
|
120 |
-
line = f.readline()
|
121 |
-
return read_outcomes(line)
|
122 |
-
|
123 |
-
def read_on(reader, f):
|
124 |
-
"""Read from an open file `f` according to the function `reader`
|
125 |
-
|
126 |
-
Args:
|
127 |
-
reader: A unary function of signature (f: _io.TextIOWrapper) -> str
|
128 |
-
f: An opened file, as returned by `open(fname)`
|
129 |
-
|
130 |
-
Yields:
|
131 |
-
A generator that returns lines defined by `reader` until the end of the file is reached.
|
132 |
-
"""
|
133 |
-
while True:
|
134 |
-
try:
|
135 |
-
line = reader(f)
|
136 |
-
except StopIteration:
|
137 |
-
break
|
138 |
-
|
139 |
-
if line is not None:
|
140 |
-
yield line
|
141 |
-
|
142 |
-
|
143 |
-
def extract_chars(infile, n=10000):
|
144 |
-
"""Extract `n` characters in batches from opened `infile`"""
|
145 |
-
reader = partial(get_chars, n)
|
146 |
-
return read_on(reader, infile)
|
147 |
-
|
148 |
-
def extract_lines(infile):
|
149 |
-
"""Given a file, yield the processed lines from that file"""
|
150 |
-
with open(infile, 'r') as src:
|
151 |
-
return read_on(get_line, src)
|
152 |
-
|
153 |
-
def extract_sentences_to_file(infile, outfname:str):
|
154 |
-
"""Extract sentences from a file into a new file indicated by `outfname`."""
|
155 |
-
out = open(outfname, 'x')
|
156 |
-
|
157 |
-
linegen = extract_lines(infile)
|
158 |
-
|
159 |
-
for line in linegen:
|
160 |
-
out.write(line + "\n")
|
161 |
-
|
162 |
-
out.close()
|
163 |
-
|
164 |
-
def main(infile, outdir):
|
165 |
-
"""Main function for creating the outdir and saving the processed sentences to that file"""
|
166 |
-
outfname = Path(infile).stem + '.txt'
|
167 |
-
outdir = Path(outdir)
|
168 |
-
outdir.mkdir(parents=True, exist_ok=True)
|
169 |
-
outfile = outdir / outfname
|
170 |
-
out_path = extract_sentences_to_file(infile, outfile)
|
171 |
-
|
172 |
-
return out_path
|
173 |
-
|
174 |
-
if __name__ == "__main__":
|
175 |
-
args = parse_args()
|
176 |
-
main(args.file, args.outdir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/tests/EN_TEST_SENTS.py
DELETED
@@ -1,18 +0,0 @@
|
|
1 |
-
"""A collection of english test sentences to use when testing the aligners"""
|
2 |
-
|
3 |
-
SPACY_EN_TEST_SENTS = [
|
4 |
-
'the LIFE',
|
5 |
-
'the LIFEST',
|
6 |
-
'the LIFESTPHSESDF',
|
7 |
-
'the LI FE ST',
|
8 |
-
"I can't understand for the LIFE of me why we Aren't going home",
|
9 |
-
"There is nothing I can say or do... that will <MAKE> me do what YOU want!!",
|
10 |
-
"This ain't going to mess me up, Ain't it?",
|
11 |
-
"It's tonsa fun in the whatve whatve@you@don't U.K.",
|
12 |
-
"It's tonsa fun in the whatve whatve_you_dont U.K.",
|
13 |
-
]
|
14 |
-
|
15 |
-
BROKEN_EN_TEST_SENTS = [
|
16 |
-
"It's tonsa fun in the whatve whatve-you-dont U.K.",
|
17 |
-
"It's tonsa fun in the whatve whatve-you-done U.K.",
|
18 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/tests/__init__.py
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
"""Temporary init. This is not meant to be a package"""
|
|
|
|
server/spacyface/tests/test_aligner.py
DELETED
@@ -1,32 +0,0 @@
|
|
1 |
-
from spacyface import *
|
2 |
-
import pytest
|
3 |
-
|
4 |
-
def load_sample_en_sents():
|
5 |
-
from .EN_TEST_SENTS import SPACY_EN_TEST_SENTS
|
6 |
-
return SPACY_EN_TEST_SENTS
|
7 |
-
|
8 |
-
sentences = load_sample_en_sents()
|
9 |
-
|
10 |
-
@pytest.mark.parametrize("model_name,alnr_class",
|
11 |
-
[('bert-base-uncased', BertAligner),
|
12 |
-
('bert-base-cased', BertAligner),
|
13 |
-
('gpt2', GPT2Aligner),
|
14 |
-
('roberta-base', RobertaAligner),
|
15 |
-
('distilbert-base-uncased', DistilBertAligner),
|
16 |
-
('transfo-xl-wt103', TransfoXLAligner),
|
17 |
-
('xlnet-base-cased', XLNetAligner),
|
18 |
-
('xlm-mlm-en-2048', XLMAligner),
|
19 |
-
('ctrl', CTRLAligner),
|
20 |
-
('albert-base-v1', AlbertAligner),
|
21 |
-
('openai-gpt', OpenAIGPTAligner),
|
22 |
-
('xlm-roberta-base', XLMRobertaAligner),
|
23 |
-
# ('t5-small', T5Aligner), # This does not currently work
|
24 |
-
])
|
25 |
-
def test_aligner(model_name, alnr_class):
|
26 |
-
"""NOTE: Will be obsolete when the aligner is able to work with transformer auto model"""
|
27 |
-
a = alnr_class.from_pretrained(model_name)
|
28 |
-
|
29 |
-
for s in sentences:
|
30 |
-
mtokens = [m['token'] for m in a.meta_tokenize(s)]
|
31 |
-
tokens = a.tokenize(s)
|
32 |
-
assert tokens == mtokens, f"{tokens} \n {mtokens}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/spacyface/tests/wiki.test.txt
DELETED
The diff for this file is too large to render.
See raw diff
|
|
server/transformers/.circleci/config.yml
DELETED
@@ -1,143 +0,0 @@
|
|
1 |
-
version: 2
|
2 |
-
jobs:
|
3 |
-
run_tests_torch_and_tf:
|
4 |
-
working_directory: ~/transformers
|
5 |
-
docker:
|
6 |
-
- image: circleci/python:3.5
|
7 |
-
environment:
|
8 |
-
OMP_NUM_THREADS: 1
|
9 |
-
resource_class: xlarge
|
10 |
-
parallelism: 1
|
11 |
-
steps:
|
12 |
-
- checkout
|
13 |
-
- run: sudo pip install .[sklearn,tf,torch,testing]
|
14 |
-
- run: sudo pip install codecov pytest-cov
|
15 |
-
- run: python -m pytest -n 8 --dist=loadfile -s -v ./tests/ --cov
|
16 |
-
- run: codecov
|
17 |
-
run_all_tests_torch_and_tf:
|
18 |
-
working_directory: ~/transformers
|
19 |
-
docker:
|
20 |
-
- image: circleci/python:3.5
|
21 |
-
environment:
|
22 |
-
OMP_NUM_THREADS: 1
|
23 |
-
RUN_SLOW: yes
|
24 |
-
RUN_CUSTOM_TOKENIZERS: yes
|
25 |
-
resource_class: xlarge
|
26 |
-
parallelism: 1
|
27 |
-
steps:
|
28 |
-
- checkout
|
29 |
-
- run: sudo pip install .[mecab,sklearn,tf,torch,testing]
|
30 |
-
- run: python -m pytest -n 8 --dist=loadfile -s -v ./tests/
|
31 |
-
run_tests_torch:
|
32 |
-
working_directory: ~/transformers
|
33 |
-
docker:
|
34 |
-
- image: circleci/python:3.7
|
35 |
-
environment:
|
36 |
-
OMP_NUM_THREADS: 1
|
37 |
-
resource_class: xlarge
|
38 |
-
parallelism: 1
|
39 |
-
steps:
|
40 |
-
- checkout
|
41 |
-
- run: sudo pip install .[sklearn,torch,testing]
|
42 |
-
- run: sudo pip install codecov pytest-cov
|
43 |
-
- run: python -m pytest -n 8 --dist=loadfile -s -v ./tests/ --cov
|
44 |
-
- run: codecov
|
45 |
-
run_tests_tf:
|
46 |
-
working_directory: ~/transformers
|
47 |
-
docker:
|
48 |
-
- image: circleci/python:3.7
|
49 |
-
environment:
|
50 |
-
OMP_NUM_THREADS: 1
|
51 |
-
resource_class: xlarge
|
52 |
-
parallelism: 1
|
53 |
-
steps:
|
54 |
-
- checkout
|
55 |
-
- run: sudo pip install .[sklearn,tf,testing]
|
56 |
-
- run: sudo pip install codecov pytest-cov
|
57 |
-
- run: python -m pytest -n 8 --dist=loadfile -s -v ./tests/ --cov
|
58 |
-
- run: codecov
|
59 |
-
run_tests_custom_tokenizers:
|
60 |
-
working_directory: ~/transformers
|
61 |
-
docker:
|
62 |
-
- image: circleci/python:3.5
|
63 |
-
environment:
|
64 |
-
RUN_CUSTOM_TOKENIZERS: yes
|
65 |
-
steps:
|
66 |
-
- checkout
|
67 |
-
- run: sudo pip install .[mecab,testing]
|
68 |
-
- run: python -m pytest -sv ./tests/test_tokenization_bert_japanese.py
|
69 |
-
run_examples_torch:
|
70 |
-
working_directory: ~/transformers
|
71 |
-
docker:
|
72 |
-
- image: circleci/python:3.5
|
73 |
-
environment:
|
74 |
-
OMP_NUM_THREADS: 1
|
75 |
-
resource_class: xlarge
|
76 |
-
parallelism: 1
|
77 |
-
steps:
|
78 |
-
- checkout
|
79 |
-
- run: sudo pip install .[sklearn,torch,testing]
|
80 |
-
- run: sudo pip install -r examples/requirements.txt
|
81 |
-
- run: python -m pytest -n 8 --dist=loadfile -s -v ./examples/
|
82 |
-
deploy_doc:
|
83 |
-
working_directory: ~/transformers
|
84 |
-
docker:
|
85 |
-
- image: circleci/python:3.5
|
86 |
-
steps:
|
87 |
-
- add_ssh_keys:
|
88 |
-
fingerprints:
|
89 |
-
- "5b:7a:95:18:07:8c:aa:76:4c:60:35:88:ad:60:56:71"
|
90 |
-
- checkout
|
91 |
-
- run: sudo pip install .[tf,torch,docs]
|
92 |
-
- run: ./.circleci/deploy.sh
|
93 |
-
check_code_quality:
|
94 |
-
working_directory: ~/transformers
|
95 |
-
docker:
|
96 |
-
- image: circleci/python:3.6
|
97 |
-
resource_class: medium
|
98 |
-
parallelism: 1
|
99 |
-
steps:
|
100 |
-
- checkout
|
101 |
-
# we need a version of isort with https://github.com/timothycrosley/isort/pull/1000
|
102 |
-
- run: sudo pip install git+git://github.com/timothycrosley/isort.git@e63ae06ec7d70b06df9e528357650281a3d3ec22#egg=isort
|
103 |
-
- run: sudo pip install .[tf,torch,quality]
|
104 |
-
- run: black --check --line-length 119 --target-version py35 examples templates tests src utils
|
105 |
-
- run: isort --check-only --recursive examples templates tests src utils
|
106 |
-
- run: flake8 examples templates tests src utils
|
107 |
-
check_repository_consistency:
|
108 |
-
working_directory: ~/transformers
|
109 |
-
docker:
|
110 |
-
- image: circleci/python:3.5
|
111 |
-
resource_class: small
|
112 |
-
parallelism: 1
|
113 |
-
steps:
|
114 |
-
- checkout
|
115 |
-
- run: sudo pip install requests
|
116 |
-
- run: python ./utils/link_tester.py
|
117 |
-
workflow_filters: &workflow_filters
|
118 |
-
filters:
|
119 |
-
branches:
|
120 |
-
only:
|
121 |
-
- master
|
122 |
-
workflows:
|
123 |
-
version: 2
|
124 |
-
build_and_test:
|
125 |
-
jobs:
|
126 |
-
- check_code_quality
|
127 |
-
- check_repository_consistency
|
128 |
-
- run_examples_torch
|
129 |
-
- run_tests_custom_tokenizers
|
130 |
-
- run_tests_torch_and_tf
|
131 |
-
- run_tests_torch
|
132 |
-
- run_tests_tf
|
133 |
-
- deploy_doc: *workflow_filters
|
134 |
-
run_slow_tests:
|
135 |
-
triggers:
|
136 |
-
- schedule:
|
137 |
-
cron: "0 4 * * 1"
|
138 |
-
filters:
|
139 |
-
branches:
|
140 |
-
only:
|
141 |
-
- master
|
142 |
-
jobs:
|
143 |
-
- run_all_tests_torch_and_tf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.circleci/deploy.sh
DELETED
@@ -1,28 +0,0 @@
|
|
1 |
-
cd docs
|
2 |
-
|
3 |
-
function deploy_doc(){
|
4 |
-
echo "Creating doc at commit $1 and pushing to folder $2"
|
5 |
-
git checkout $1
|
6 |
-
if [ ! -z "$2" ]
|
7 |
-
then
|
8 |
-
if [ -d "$dir/$2" ]; then
|
9 |
-
echo "Directory" $2 "already exists"
|
10 |
-
else
|
11 |
-
echo "Pushing version" $2
|
12 |
-
make clean && make html && scp -r -oStrictHostKeyChecking=no _build/html $doc:$dir/$2
|
13 |
-
fi
|
14 |
-
else
|
15 |
-
echo "Pushing master"
|
16 |
-
make clean && make html && scp -r -oStrictHostKeyChecking=no _build/html/* $doc:$dir
|
17 |
-
fi
|
18 |
-
}
|
19 |
-
|
20 |
-
deploy_doc "master"
|
21 |
-
deploy_doc "b33a385" v1.0.0
|
22 |
-
deploy_doc "fe02e45" v1.1.0
|
23 |
-
deploy_doc "89fd345" v1.2.0
|
24 |
-
deploy_doc "fc9faa8" v2.0.0
|
25 |
-
deploy_doc "3ddce1d" v2.1.1
|
26 |
-
deploy_doc "3616209" v2.2.0
|
27 |
-
deploy_doc "d0f8b9a" v2.3.0
|
28 |
-
deploy_doc "6664ea9" v2.4.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.coveragerc
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
[run]
|
2 |
-
source=transformers
|
3 |
-
omit =
|
4 |
-
# skip convertion scripts from testing for now
|
5 |
-
*/convert_*
|
6 |
-
*/__main__.py
|
7 |
-
[report]
|
8 |
-
exclude_lines =
|
9 |
-
pragma: no cover
|
10 |
-
raise
|
11 |
-
except
|
12 |
-
register_parameter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/---new-benchmark.md
DELETED
@@ -1,22 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "\U0001F5A5 New benchmark"
|
3 |
-
about: Benchmark a part of this library and share your results
|
4 |
-
title: "[Benchmark]"
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# 🖥 Benchmarking `transformers`
|
11 |
-
|
12 |
-
## Benchmark
|
13 |
-
|
14 |
-
Which part of `transformers` did you benchmark?
|
15 |
-
|
16 |
-
## Set-up
|
17 |
-
|
18 |
-
What did you run your benchmarks on? Please include details, such as: CPU, GPU? If using multiple GPUs, which parallelization did you use?
|
19 |
-
|
20 |
-
## Results
|
21 |
-
|
22 |
-
Put your results here!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/--new-model-addition.md
DELETED
@@ -1,20 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "\U0001F31F New model addition"
|
3 |
-
about: Submit a proposal/request to implement a new Transformer-based model
|
4 |
-
title: ''
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# 🌟 New model addition
|
11 |
-
|
12 |
-
## Model description
|
13 |
-
|
14 |
-
<!-- Important information -->
|
15 |
-
|
16 |
-
## Open source status
|
17 |
-
|
18 |
-
* [ ] the model implementation is available: (give details)
|
19 |
-
* [ ] the model weights are available: (give details)
|
20 |
-
* [ ] who are the authors: (mention them, if possible by @gh-username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/bug-report.md
DELETED
@@ -1,52 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "\U0001F41B Bug Report"
|
3 |
-
about: Submit a bug report to help us improve transformers
|
4 |
-
title: ''
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# 🐛 Bug
|
11 |
-
|
12 |
-
## Information
|
13 |
-
|
14 |
-
Model I am using (Bert, XLNet ...):
|
15 |
-
|
16 |
-
Language I am using the model on (English, Chinese ...):
|
17 |
-
|
18 |
-
The problem arises when using:
|
19 |
-
* [ ] the official example scripts: (give details below)
|
20 |
-
* [ ] my own modified scripts: (give details below)
|
21 |
-
|
22 |
-
The tasks I am working on is:
|
23 |
-
* [ ] an official GLUE/SQUaD task: (give the name)
|
24 |
-
* [ ] my own task or dataset: (give details below)
|
25 |
-
|
26 |
-
## To reproduce
|
27 |
-
|
28 |
-
Steps to reproduce the behavior:
|
29 |
-
|
30 |
-
1.
|
31 |
-
2.
|
32 |
-
3.
|
33 |
-
|
34 |
-
<!-- If you have code snippets, error messages, stack traces please provide them here as well.
|
35 |
-
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
|
36 |
-
Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.-->
|
37 |
-
|
38 |
-
## Expected behavior
|
39 |
-
|
40 |
-
<!-- A clear and concise description of what you would expect to happen. -->
|
41 |
-
|
42 |
-
## Environment info
|
43 |
-
<!-- You can run the command `python transformers-cli env` and copy-and-paste its output below.
|
44 |
-
Don't forget to fill out the missing fields in that output! -->
|
45 |
-
|
46 |
-
- `transformers` version:
|
47 |
-
- Platform:
|
48 |
-
- Python version:
|
49 |
-
- PyTorch version (GPU?):
|
50 |
-
- Tensorflow version (GPU?):
|
51 |
-
- Using GPU in script?:
|
52 |
-
- Using distributed or parallel set-up in script?:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/feature-request.md
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "\U0001F680 Feature request"
|
3 |
-
about: Submit a proposal/request for a new transformers feature
|
4 |
-
title: ''
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# 🚀 Feature request
|
11 |
-
|
12 |
-
<!-- A clear and concise description of the feature proposal.
|
13 |
-
Please provide a link to the paper and code in case they exist. -->
|
14 |
-
|
15 |
-
## Motivation
|
16 |
-
|
17 |
-
<!-- Please outline the motivation for the proposal. Is your feature request
|
18 |
-
related to a problem? e.g., I'm always frustrated when [...]. If this is related
|
19 |
-
to another GitHub issue, please link here too. -->
|
20 |
-
|
21 |
-
## Your contribution
|
22 |
-
|
23 |
-
<!-- Is there any way that you could help, e.g. by submitting a PR?
|
24 |
-
Make sure to read the CONTRIBUTING.MD readme:
|
25 |
-
https://github.com/huggingface/transformers/blob/master/CONTRIBUTING.md -->
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/migration.md
DELETED
@@ -1,57 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "\U0001F4DA Migration from pytorch-pretrained-bert or pytorch-transformers"
|
3 |
-
about: Report a problem when migrating from pytorch-pretrained-bert or pytorch-transformers to transformers
|
4 |
-
title: ''
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# 📚 Migration
|
11 |
-
|
12 |
-
## Information
|
13 |
-
|
14 |
-
<!-- Important information -->
|
15 |
-
|
16 |
-
Model I am using (Bert, XLNet ...):
|
17 |
-
|
18 |
-
Language I am using the model on (English, Chinese ...):
|
19 |
-
|
20 |
-
The problem arises when using:
|
21 |
-
* [ ] the official example scripts: (give details below)
|
22 |
-
* [ ] my own modified scripts: (give details below)
|
23 |
-
|
24 |
-
The tasks I am working on is:
|
25 |
-
* [ ] an official GLUE/SQUaD task: (give the name)
|
26 |
-
* [ ] my own task or dataset: (give details below)
|
27 |
-
|
28 |
-
## Details
|
29 |
-
|
30 |
-
<!-- A clear and concise description of the migration issue.
|
31 |
-
If you have code snippets, please provide it here as well.
|
32 |
-
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
|
33 |
-
Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
|
34 |
-
-->
|
35 |
-
|
36 |
-
## Environment info
|
37 |
-
<!-- You can run the command `python transformers-cli env` and copy-and-paste its output below.
|
38 |
-
Don't forget to fill out the missing fields in that output! -->
|
39 |
-
|
40 |
-
- `transformers` version:
|
41 |
-
- Platform:
|
42 |
-
- Python version:
|
43 |
-
- PyTorch version (GPU?):
|
44 |
-
- Tensorflow version (GPU?):
|
45 |
-
- Using GPU in script?:
|
46 |
-
- Using distributed or parallel set-up in script?:
|
47 |
-
|
48 |
-
<!-- IMPORTANT: which version of the former library do you use? -->
|
49 |
-
* `pytorch-transformers` or `pytorch-pretrained-bert` version (or branch):
|
50 |
-
|
51 |
-
|
52 |
-
## Checklist
|
53 |
-
|
54 |
-
- [ ] I have read the migration guide in the readme.
|
55 |
-
([pytorch-transformers](https://github.com/huggingface/transformers#migrating-from-pytorch-transformers-to-transformers);
|
56 |
-
[pytorch-pretrained-bert](https://github.com/huggingface/transformers#migrating-from-pytorch-pretrained-bert-to-transformers))
|
57 |
-
- [ ] I checked if a related official extension example runs on my machine.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/ISSUE_TEMPLATE/question-help.md
DELETED
@@ -1,29 +0,0 @@
|
|
1 |
-
---
|
2 |
-
name: "❓ Questions & Help"
|
3 |
-
about: Post your general questions on Stack Overflow tagged huggingface-transformers
|
4 |
-
title: ''
|
5 |
-
labels: ''
|
6 |
-
assignees: ''
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
# ❓ Questions & Help
|
11 |
-
|
12 |
-
<!-- The GitHub issue tracker is primarly intended for bugs, feature requests,
|
13 |
-
new models and benchmarks, and migration questions. For all other questions,
|
14 |
-
we direct you to Stack Overflow (SO) where a whole community of PyTorch and
|
15 |
-
Tensorflow enthusiast can help you out. Make sure to tag your question with the
|
16 |
-
right deep learning framework as well as the huggingface-transformers tag:
|
17 |
-
https://stackoverflow.com/questions/tagged/huggingface-transformers
|
18 |
-
|
19 |
-
If your question wasn't answered after a period of time on Stack Overflow, you
|
20 |
-
can always open a question on GitHub. You should then link to the SO question
|
21 |
-
that you posted.
|
22 |
-
-->
|
23 |
-
|
24 |
-
## Details
|
25 |
-
<!-- Description of your issue -->
|
26 |
-
|
27 |
-
<!-- You should first ask your question on SO, and only if
|
28 |
-
you didn't get an answer ask it here on GitHub. -->
|
29 |
-
**A link to original question on Stack Overflow**:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.github/stale.yml
DELETED
@@ -1,17 +0,0 @@
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.gitignore
DELETED
@@ -1,141 +0,0 @@
|
|
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 |
-
# Pycharm
|
122 |
-
.idea
|
123 |
-
|
124 |
-
# TF code
|
125 |
-
tensorflow_code
|
126 |
-
|
127 |
-
# Models
|
128 |
-
models
|
129 |
-
proc_data
|
130 |
-
|
131 |
-
# examples
|
132 |
-
runs
|
133 |
-
examples/runs
|
134 |
-
|
135 |
-
# data
|
136 |
-
/data
|
137 |
-
serialization_dir
|
138 |
-
|
139 |
-
# emacs
|
140 |
-
*.*~
|
141 |
-
debug.env
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/.gitrepo
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
; DO NOT EDIT (unless you know what you are doing)
|
2 |
-
;
|
3 |
-
; This subdirectory is a git "subrepo", and this file is maintained by the
|
4 |
-
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
|
5 |
-
;
|
6 |
-
[subrepo]
|
7 |
-
remote = https://github.com/bhoov/transformers.git
|
8 |
-
branch = exbert-mods
|
9 |
-
commit = a0b899d114c1891dc685ce448077efab4a386348
|
10 |
-
parent = 8235ef04d0dca4d47c9106f70c0bd8681895fb8f
|
11 |
-
method = merge
|
12 |
-
cmdver = 0.4.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/CONTRIBUTING.md
DELETED
@@ -1,258 +0,0 @@
|
|
1 |
-
# How to contribute to transformers?
|
2 |
-
|
3 |
-
Everyone is welcome to contribute, and we value everybody's contribution. Code
|
4 |
-
is thus not the only way to help the community. Answering questions, helping
|
5 |
-
others, reaching out and improving the documentations are immensely valuable to
|
6 |
-
the community.
|
7 |
-
|
8 |
-
It also helps us if you spread the word: reference the library from blog posts
|
9 |
-
on the awesome projects it made possible, shout out on Twitter every time it has
|
10 |
-
helped you, or simply star the repo to say "thank you".
|
11 |
-
|
12 |
-
## You can contribute in so many ways!
|
13 |
-
|
14 |
-
There are 4 ways you can contribute to transformers:
|
15 |
-
* Fixing outstanding issues with the existing code;
|
16 |
-
* Implementing new models;
|
17 |
-
* Contributing to the examples or to the documentation;
|
18 |
-
* Submitting issues related to bugs or desired new features.
|
19 |
-
|
20 |
-
*All are equally valuable to the community.*
|
21 |
-
|
22 |
-
## Submitting a new issue or feature request
|
23 |
-
|
24 |
-
Do your best to follow these guidelines when submitting an issue or a feature
|
25 |
-
request. It will make it easier for us to come back to you quickly and with good
|
26 |
-
feedback.
|
27 |
-
|
28 |
-
### Did you find a bug?
|
29 |
-
|
30 |
-
The transformers are robust and reliable thanks to the users who notify us of
|
31 |
-
the problems they encounter. So thank you for reporting an issue.
|
32 |
-
|
33 |
-
First, we would really appreciate it if you could **make sure the bug was not
|
34 |
-
already reported** (use the search bar on Github under Issues).
|
35 |
-
|
36 |
-
Did not find it? :( So we can act quickly on it, please follow these steps:
|
37 |
-
|
38 |
-
* Include your **OS type and version**, the versions of **Python**, **PyTorch** and
|
39 |
-
**Tensorflow** when applicable;
|
40 |
-
* A short, self-contained, code snippet that allows us to reproduce the bug in
|
41 |
-
less than 30s;
|
42 |
-
* Provide the *full* traceback if an exception is raised.
|
43 |
-
|
44 |
-
To get the OS and software versions automatically, you can run the following command:
|
45 |
-
|
46 |
-
```bash
|
47 |
-
python transformers-cli env
|
48 |
-
```
|
49 |
-
|
50 |
-
### Do you want to implement a new model?
|
51 |
-
|
52 |
-
Awesome! Please provide the following information:
|
53 |
-
|
54 |
-
* Short description of the model and link to the paper;
|
55 |
-
* Link to the implementation if it is open-source;
|
56 |
-
* Link to the model weights if they are available.
|
57 |
-
|
58 |
-
If you are willing to contribute the model yourself, let us know so we can best
|
59 |
-
guide you.
|
60 |
-
|
61 |
-
We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them in the [`templates`](./templates) folder.
|
62 |
-
|
63 |
-
### Do you want a new feature (that is not a model)?
|
64 |
-
|
65 |
-
A world-class feature request addresses the following points:
|
66 |
-
|
67 |
-
1. Motivation first:
|
68 |
-
* Is it related to a problem/frustration with the library? If so, please explain
|
69 |
-
why. Providing a code snippet that demonstrates the problem is best.
|
70 |
-
* Is it related to something you would need for a project? We'd love to hear
|
71 |
-
about it!
|
72 |
-
* Is it something you worked on and think could benefit the community?
|
73 |
-
Awesome! Tell us what problem it solved for you.
|
74 |
-
2. Write a *full paragraph* describing the feature;
|
75 |
-
3. Provide a **code snippet** that demonstrates its future use;
|
76 |
-
4. In case this is related to a paper, please attach a link;
|
77 |
-
5. Attach any additional information (drawings, screenshots, etc.) you think may help.
|
78 |
-
|
79 |
-
If your issue is well written we're already 80% of the way there by the time you
|
80 |
-
post it.
|
81 |
-
|
82 |
-
We have added **templates** to guide you in the process of adding a new example script for training or testing the models in the library. You can find them in the [`templates`](./templates) folder.
|
83 |
-
|
84 |
-
## Start contributing! (Pull Requests)
|
85 |
-
|
86 |
-
Before writing code, we strongly advise you to search through the exising PRs or
|
87 |
-
issues to make sure that nobody is already working on the same thing. If you are
|
88 |
-
unsure, it is always a good idea to open an issue to get some feedback.
|
89 |
-
|
90 |
-
You will need basic `git` proficiency to be able to contribute to
|
91 |
-
`transformers`. `git` is not the easiest tool to use but it has the greatest
|
92 |
-
manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
|
93 |
-
Git](https://git-scm.com/book/en/v2) is a very good reference.
|
94 |
-
|
95 |
-
Follow these steps to start contributing:
|
96 |
-
|
97 |
-
1. Fork the [repository](https://github.com/huggingface/transformers) by
|
98 |
-
clicking on the 'Fork' button on the repository's page. This creates a copy of the code
|
99 |
-
under your GitHub user account.
|
100 |
-
|
101 |
-
2. Clone your fork to your local disk, and add the base repository as a remote:
|
102 |
-
|
103 |
-
```bash
|
104 |
-
$ git clone [email protected]:<your Github handle>/transformers.git
|
105 |
-
$ cd transformers
|
106 |
-
$ git remote add upstream https://github.com/huggingface/transformers.git
|
107 |
-
```
|
108 |
-
|
109 |
-
3. Create a new branch to hold your development changes:
|
110 |
-
|
111 |
-
```bash
|
112 |
-
$ git checkout -b a-descriptive-name-for-my-changes
|
113 |
-
```
|
114 |
-
|
115 |
-
**do not** work on the `master` branch.
|
116 |
-
|
117 |
-
4. Set up a development environment by running the following command in a virtual environment:
|
118 |
-
|
119 |
-
```bash
|
120 |
-
$ pip install -e ".[dev]"
|
121 |
-
```
|
122 |
-
|
123 |
-
(If transformers was already installed in the virtual environment, remove
|
124 |
-
it with `pip uninstall transformers` before reinstalling it in editable
|
125 |
-
mode with the `-e` flag.)
|
126 |
-
|
127 |
-
Right now, we need an unreleased version of `isort` to avoid a
|
128 |
-
[bug](https://github.com/timothycrosley/isort/pull/1000):
|
129 |
-
|
130 |
-
```bash
|
131 |
-
$ pip install -U git+git://github.com/timothycrosley/isort.git@e63ae06ec7d70b06df9e528357650281a3d3ec22#egg=isort
|
132 |
-
```
|
133 |
-
|
134 |
-
5. Develop the features on your branch.
|
135 |
-
|
136 |
-
As you work on the features, you should make sure that the test suite
|
137 |
-
passes:
|
138 |
-
|
139 |
-
```bash
|
140 |
-
$ make test
|
141 |
-
```
|
142 |
-
|
143 |
-
`transformers` relies on `black` and `isort` to format its source code
|
144 |
-
consistently. After you make changes, format them with:
|
145 |
-
|
146 |
-
```bash
|
147 |
-
$ make style
|
148 |
-
```
|
149 |
-
|
150 |
-
`transformers` also uses `flake8` to check for coding mistakes. Quality
|
151 |
-
control runs in CI, however you can also run the same checks with:
|
152 |
-
|
153 |
-
```bash
|
154 |
-
$ make quality
|
155 |
-
```
|
156 |
-
|
157 |
-
Once you're happy with your changes, add changed files using `git add` and
|
158 |
-
make a commit with `git commit` to record your changes locally:
|
159 |
-
|
160 |
-
```bash
|
161 |
-
$ git add modified_file.py
|
162 |
-
$ git commit
|
163 |
-
```
|
164 |
-
|
165 |
-
Please write [good commit
|
166 |
-
messages](https://chris.beams.io/posts/git-commit/).
|
167 |
-
|
168 |
-
It is a good idea to sync your copy of the code with the original
|
169 |
-
repository regularly. This way you can quickly account for changes:
|
170 |
-
|
171 |
-
```bash
|
172 |
-
$ git fetch upstream
|
173 |
-
$ git rebase upstream/master
|
174 |
-
```
|
175 |
-
|
176 |
-
Push the changes to your account using:
|
177 |
-
|
178 |
-
```bash
|
179 |
-
$ git push -u origin a-descriptive-name-for-my-changes
|
180 |
-
```
|
181 |
-
|
182 |
-
6. Once you are satisfied (**and the checklist below is happy too**), go to the
|
183 |
-
webpage of your fork on GitHub. Click on 'Pull request' to send your changes
|
184 |
-
to the project maintainers for review.
|
185 |
-
|
186 |
-
7. It's ok if maintainers ask you for changes. It happens to core contributors
|
187 |
-
too! So everyone can see the changes in the Pull request, work in your local
|
188 |
-
branch and push the changes to your fork. They will automatically appear in
|
189 |
-
the pull request.
|
190 |
-
|
191 |
-
|
192 |
-
### Checklist
|
193 |
-
|
194 |
-
1. The title of your pull request should be a summary of its contribution;
|
195 |
-
2. If your pull request adresses an issue, please mention the issue number in
|
196 |
-
the pull request description to make sure they are linked (and people
|
197 |
-
consulting the issue know you are working on it);
|
198 |
-
3. To indicate a work in progress please prefix the title with `[WIP]`. These
|
199 |
-
are useful to avoid duplicated work, and to differentiate it from PRs ready
|
200 |
-
to be merged;
|
201 |
-
4. Make sure pre-existing tests still pass;
|
202 |
-
5. Add high-coverage tests. No quality test, no merge;
|
203 |
-
6. All public methods must have informative docstrings;
|
204 |
-
|
205 |
-
|
206 |
-
### Tests
|
207 |
-
|
208 |
-
You can run 🤗 Transformers tests with `unittest` or `pytest`.
|
209 |
-
|
210 |
-
We like `pytest` and `pytest-xdist` because it's faster. From the root of the
|
211 |
-
repository, here's how to run tests with `pytest` for the library:
|
212 |
-
|
213 |
-
```bash
|
214 |
-
$ python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
215 |
-
```
|
216 |
-
|
217 |
-
and for the examples:
|
218 |
-
|
219 |
-
```bash
|
220 |
-
$ pip install -r examples/requirements.txt # only needed the first time
|
221 |
-
$ python -m pytest -n auto --dist=loadfile -s -v ./examples/
|
222 |
-
```
|
223 |
-
|
224 |
-
In fact, that's how `make test` and `make test-examples` are implemented!
|
225 |
-
|
226 |
-
You can specify a smaller set of tests in order to test only the feature
|
227 |
-
you're working on.
|
228 |
-
|
229 |
-
By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to
|
230 |
-
`yes` to run them. This will download many gigabytes of models — make sure you
|
231 |
-
have enough disk space and a good Internet connection, or a lot of patience!
|
232 |
-
|
233 |
-
```bash
|
234 |
-
$ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
235 |
-
$ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/
|
236 |
-
```
|
237 |
-
|
238 |
-
Likewise, set the `RUN_CUSTOM_TOKENIZERS` environment variable to `yes` to run
|
239 |
-
tests for custom tokenizers, which don't run by default either.
|
240 |
-
|
241 |
-
🤗 Transformers uses `pytest` as a test runner only. It doesn't use any
|
242 |
-
`pytest`-specific features in the test suite itself.
|
243 |
-
|
244 |
-
This means `unittest` is fully supported. Here's how to run tests with
|
245 |
-
`unittest`:
|
246 |
-
|
247 |
-
```bash
|
248 |
-
$ python -m unittest discover -s tests -t . -v
|
249 |
-
$ python -m unittest discover -s examples -t examples -v
|
250 |
-
```
|
251 |
-
|
252 |
-
|
253 |
-
### Style guide
|
254 |
-
|
255 |
-
For documentation strings, `transformers` follows the [google
|
256 |
-
style](https://google.github.io/styleguide/pyguide.html).
|
257 |
-
|
258 |
-
#### This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/master/CONTRIBUTING.md)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/LICENSE
DELETED
@@ -1,202 +0,0 @@
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/MANIFEST.in
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
include LICENSE
|
|
|
|
server/transformers/Makefile
DELETED
@@ -1,24 +0,0 @@
|
|
1 |
-
.PHONY: quality style test test-examples
|
2 |
-
|
3 |
-
# Check that source code meets quality standards
|
4 |
-
|
5 |
-
quality:
|
6 |
-
black --check --line-length 119 --target-version py35 examples templates tests src utils
|
7 |
-
isort --check-only --recursive examples templates tests src utils
|
8 |
-
flake8 examples templates tests src utils
|
9 |
-
|
10 |
-
# Format source code automatically
|
11 |
-
|
12 |
-
style:
|
13 |
-
black --line-length 119 --target-version py35 examples templates tests src utils
|
14 |
-
isort --recursive examples templates tests src utils
|
15 |
-
|
16 |
-
# Run tests for the library
|
17 |
-
|
18 |
-
test:
|
19 |
-
python -m pytest -n auto --dist=loadfile -s -v ./tests/
|
20 |
-
|
21 |
-
# Run tests for examples
|
22 |
-
|
23 |
-
test-examples:
|
24 |
-
python -m pytest -n auto --dist=loadfile -s -v ./examples/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/README.md
DELETED
@@ -1,684 +0,0 @@
|
|
1 |
-
<p align="center">
|
2 |
-
<br>
|
3 |
-
<img src="https://raw.githubusercontent.com/huggingface/transformers/master/docs/source/imgs/transformers_logo_name.png" width="400"/>
|
4 |
-
<br>
|
5 |
-
<p>
|
6 |
-
<p align="center">
|
7 |
-
<a href="https://circleci.com/gh/huggingface/transformers">
|
8 |
-
<img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master">
|
9 |
-
</a>
|
10 |
-
<a href="https://github.com/huggingface/transformers/blob/master/LICENSE">
|
11 |
-
<img alt="GitHub" src="https://img.shields.io/github/license/huggingface/transformers.svg?color=blue">
|
12 |
-
</a>
|
13 |
-
<a href="https://huggingface.co/transformers/index.html">
|
14 |
-
<img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/transformers/index.html.svg?down_color=red&down_message=offline&up_message=online">
|
15 |
-
</a>
|
16 |
-
<a href="https://github.com/huggingface/transformers/releases">
|
17 |
-
<img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg">
|
18 |
-
</a>
|
19 |
-
</p>
|
20 |
-
|
21 |
-
<h3 align="center">
|
22 |
-
<p>State-of-the-art Natural Language Processing for TensorFlow 2.0 and PyTorch
|
23 |
-
</h3>
|
24 |
-
|
25 |
-
🤗 Transformers (formerly known as `pytorch-transformers` and `pytorch-pretrained-bert`) provides state-of-the-art general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet, CTRL...) for Natural Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between TensorFlow 2.0 and PyTorch.
|
26 |
-
|
27 |
-
### Features
|
28 |
-
|
29 |
-
- As easy to use as pytorch-transformers
|
30 |
-
- As powerful and concise as Keras
|
31 |
-
- High performance on NLU and NLG tasks
|
32 |
-
- Low barrier to entry for educators and practitioners
|
33 |
-
|
34 |
-
State-of-the-art NLP for everyone
|
35 |
-
- Deep learning researchers
|
36 |
-
- Hands-on practitioners
|
37 |
-
- AI/ML/NLP teachers and educators
|
38 |
-
|
39 |
-
Lower compute costs, smaller carbon footprint
|
40 |
-
- Researchers can share trained models instead of always retraining
|
41 |
-
- Practitioners can reduce compute time and production costs
|
42 |
-
- 10 architectures with over 30 pretrained models, some in more than 100 languages
|
43 |
-
|
44 |
-
Choose the right framework for every part of a model's lifetime
|
45 |
-
- Train state-of-the-art models in 3 lines of code
|
46 |
-
- Deep interoperability between TensorFlow 2.0 and PyTorch models
|
47 |
-
- Move a single model between TF2.0/PyTorch frameworks at will
|
48 |
-
- Seamlessly pick the right framework for training, evaluation, production
|
49 |
-
|
50 |
-
|
51 |
-
| Section | Description |
|
52 |
-
|-|-|
|
53 |
-
| [Installation](#installation) | How to install the package |
|
54 |
-
| [Model architectures](#model-architectures) | Architectures (with pretrained weights) |
|
55 |
-
| [Online demo](#online-demo) | Experimenting with this repo’s text generation capabilities |
|
56 |
-
| [Quick tour: Usage](#quick-tour) | Tokenizers & models usage: Bert and GPT-2 |
|
57 |
-
| [Quick tour: TF 2.0 and PyTorch ](#Quick-tour-TF-20-training-and-PyTorch-interoperability) | Train a TF 2.0 model in 10 lines of code, load it in PyTorch |
|
58 |
-
| [Quick tour: pipelines](#quick-tour-of-pipelines) | Using Pipelines: Wrapper around tokenizer and models to use finetuned models |
|
59 |
-
| [Quick tour: Fine-tuning/usage scripts](#quick-tour-of-the-fine-tuningusage-scripts) | Using provided scripts: GLUE, SQuAD and Text generation |
|
60 |
-
| [Quick tour: Share your models ](#Quick-tour-of-model-sharing) | Upload and share your fine-tuned models with the community |
|
61 |
-
| [Migrating from pytorch-transformers to transformers](#Migrating-from-pytorch-transformers-to-transformers) | Migrating your code from pytorch-transformers to transformers |
|
62 |
-
| [Migrating from pytorch-pretrained-bert to pytorch-transformers](#Migrating-from-pytorch-pretrained-bert-to-transformers) | Migrating your code from pytorch-pretrained-bert to transformers |
|
63 |
-
| [Documentation][(v2.4.0)](https://huggingface.co/transformers/v2.4.0)[(v2.3.0)](https://huggingface.co/transformers/v2.3.0)[(v2.2.0/v2.2.1/v2.2.2)](https://huggingface.co/transformers/v2.2.0) [(v2.1.1)](https://huggingface.co/transformers/v2.1.1) [(v2.0.0)](https://huggingface.co/transformers/v2.0.0) [(v1.2.0)](https://huggingface.co/transformers/v1.2.0) [(v1.1.0)](https://huggingface.co/transformers/v1.1.0) [(v1.0.0)](https://huggingface.co/transformers/v1.0.0) [(master)](https://huggingface.co/transformers) | Full API documentation and more |
|
64 |
-
|
65 |
-
## Installation
|
66 |
-
|
67 |
-
This repo is tested on Python 3.5+, PyTorch 1.0.0+ and TensorFlow 2.0.0-rc1
|
68 |
-
|
69 |
-
You should install 🤗 Transformers in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
|
70 |
-
|
71 |
-
Create a virtual environment with the version of Python you're going to use and activate it.
|
72 |
-
|
73 |
-
Now, if you want to use 🤗 Transformers, you can install it with pip. If you'd like to play with the examples, you must install it from source.
|
74 |
-
|
75 |
-
### With pip
|
76 |
-
|
77 |
-
First you need to install one of, or both, TensorFlow 2.0 and PyTorch.
|
78 |
-
Please refer to [TensorFlow installation page](https://www.tensorflow.org/install/pip#tensorflow-2.0-rc-is-available) and/or [PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform.
|
79 |
-
|
80 |
-
When TensorFlow 2.0 and/or PyTorch has been installed, 🤗 Transformers can be installed using pip as follows:
|
81 |
-
|
82 |
-
```bash
|
83 |
-
pip install transformers
|
84 |
-
```
|
85 |
-
|
86 |
-
### From source
|
87 |
-
|
88 |
-
Here also, you first need to install one of, or both, TensorFlow 2.0 and PyTorch.
|
89 |
-
Please refer to [TensorFlow installation page](https://www.tensorflow.org/install/pip#tensorflow-2.0-rc-is-available) and/or [PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform.
|
90 |
-
|
91 |
-
When TensorFlow 2.0 and/or PyTorch has been installed, you can install from source by cloning the repository and running:
|
92 |
-
|
93 |
-
```bash
|
94 |
-
git clone https://github.com/huggingface/transformers
|
95 |
-
cd transformers
|
96 |
-
pip install .
|
97 |
-
```
|
98 |
-
|
99 |
-
When you update the repository, you should upgrade the transformers installation and its dependencies as follows:
|
100 |
-
|
101 |
-
```bash
|
102 |
-
git pull
|
103 |
-
pip install --upgrade .
|
104 |
-
```
|
105 |
-
|
106 |
-
### Run the examples
|
107 |
-
|
108 |
-
Examples are included in the repository but are not shipped with the library.
|
109 |
-
|
110 |
-
Therefore, in order to run the latest versions of the examples, you need to install from source, as described above.
|
111 |
-
|
112 |
-
Look at the [README](https://github.com/huggingface/transformers/blob/master/examples/README.md) for how to run examples.
|
113 |
-
|
114 |
-
### Tests
|
115 |
-
|
116 |
-
A series of tests are included for the library and for some example scripts. Library tests can be found in the [tests folder](https://github.com/huggingface/transformers/tree/master/tests) and examples tests in the [examples folder](https://github.com/huggingface/transformers/tree/master/examples).
|
117 |
-
|
118 |
-
Depending on which framework is installed (TensorFlow 2.0 and/or PyTorch), the irrelevant tests will be skipped. Ensure that both frameworks are installed if you want to execute all tests.
|
119 |
-
|
120 |
-
Here's the easiest way to run tests for the library:
|
121 |
-
|
122 |
-
```bash
|
123 |
-
pip install -e ".[testing]"
|
124 |
-
make test
|
125 |
-
```
|
126 |
-
|
127 |
-
and for the examples:
|
128 |
-
|
129 |
-
```bash
|
130 |
-
pip install -e ".[testing]"
|
131 |
-
pip install -r examples/requirements.txt
|
132 |
-
make test-examples
|
133 |
-
```
|
134 |
-
|
135 |
-
For details, refer to the [contributing guide](https://github.com/huggingface/transformers/blob/master/CONTRIBUTING.md#tests).
|
136 |
-
|
137 |
-
### Do you want to run a Transformer model on a mobile device?
|
138 |
-
|
139 |
-
You should check out our [`swift-coreml-transformers`](https://github.com/huggingface/swift-coreml-transformers) repo.
|
140 |
-
|
141 |
-
It contains a set of tools to convert PyTorch or TensorFlow 2.0 trained Transformer models (currently contains `GPT-2`, `DistilGPT-2`, `BERT`, and `DistilBERT`) to CoreML models that run on iOS devices.
|
142 |
-
|
143 |
-
At some point in the future, you'll be able to seamlessly move from pre-training or fine-tuning models to productizing them in CoreML, or prototype a model or an app in CoreML then research its hyperparameters or architecture from TensorFlow 2.0 and/or PyTorch. Super exciting!
|
144 |
-
|
145 |
-
## Model architectures
|
146 |
-
|
147 |
-
🤗 Transformers currently provides the following NLU/NLG architectures:
|
148 |
-
|
149 |
-
1. **[BERT](https://github.com/google-research/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
|
150 |
-
2. **[GPT](https://github.com/openai/finetune-transformer-lm)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
|
151 |
-
3. **[GPT-2](https://blog.openai.com/better-language-models/)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
|
152 |
-
4. **[Transformer-XL](https://github.com/kimiyoung/transformer-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
|
153 |
-
5. **[XLNet](https://github.com/zihangdai/xlnet/)** (from Google/CMU) released with the paper [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
|
154 |
-
6. **[XLM](https://github.com/facebookresearch/XLM/)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
|
155 |
-
7. **[RoBERTa](https://github.com/pytorch/fairseq/tree/master/examples/roberta)** (from Facebook), released together with the paper a [Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
|
156 |
-
8. **[DistilBERT](https://github.com/huggingface/transformers/tree/master/examples/distillation)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers/tree/master/examples/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/master/examples/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/master/examples/distillation) and a German version of DistilBERT.
|
157 |
-
9. **[CTRL](https://github.com/salesforce/ctrl/)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
|
158 |
-
10. **[CamemBERT](https://camembert-model.fr)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
|
159 |
-
11. **[ALBERT](https://github.com/google-research/ALBERT)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
|
160 |
-
12. **[T5](https://github.com/google-research/text-to-text-transfer-transformer)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
|
161 |
-
13. **[XLM-RoBERTa](https://github.com/pytorch/fairseq/tree/master/examples/xlmr)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
|
162 |
-
14. **[MMBT](https://github.com/facebookresearch/mmbt/)** (from Facebook), released together with the paper a [Supervised Multimodal Bitransformers for Classifying Images and Text](https://arxiv.org/pdf/1909.02950.pdf) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.
|
163 |
-
15. **[FlauBERT](https://github.com/getalp/Flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
|
164 |
-
16. **[Other community models](https://huggingface.co/models)**, contributed by the [community](https://huggingface.co/users).
|
165 |
-
17. Want to contribute a new model? We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them in the [`templates`](./templates) folder of the repository. Be sure to check the [contributing guidelines](./CONTRIBUTING.md) and contact the maintainers or open an issue to collect feedbacks before starting your PR.
|
166 |
-
|
167 |
-
These implementations have been tested on several datasets (see the example scripts) and should match the performances of the original implementations (e.g. ~93 F1 on SQuAD for BERT Whole-Word-Masking, ~88 F1 on RocStories for OpenAI GPT, ~18.3 perplexity on WikiText 103 for Transformer-XL, ~0.916 Peason R coefficient on STS-B for XLNet). You can find more details on the performances in the Examples section of the [documentation](https://huggingface.co/transformers/examples.html).
|
168 |
-
|
169 |
-
## Online demo
|
170 |
-
|
171 |
-
**[Write With Transformer](https://transformer.huggingface.co)**, built by the Hugging Face team at transformer.huggingface.co, is the official demo of this repo’s text generation capabilities.
|
172 |
-
You can use it to experiment with completions generated by `GPT2Model`, `TransfoXLModel`, and `XLNetModel`.
|
173 |
-
|
174 |
-
> “🦄 Write with transformer is to writing what calculators are to calculus.”
|
175 |
-
|
176 |
-
![write_with_transformer](https://transformer.huggingface.co/front/assets/thumbnail-large.png)
|
177 |
-
|
178 |
-
## Quick tour
|
179 |
-
|
180 |
-
Let's do a very quick overview of the model architectures in 🤗 Transformers. Detailed examples for each model architecture (Bert, GPT, GPT-2, Transformer-XL, XLNet and XLM) can be found in the [full documentation](https://huggingface.co/transformers/).
|
181 |
-
|
182 |
-
```python
|
183 |
-
import torch
|
184 |
-
from transformers import *
|
185 |
-
|
186 |
-
# Transformers has a unified API
|
187 |
-
# for 10 transformer architectures and 30 pretrained weights.
|
188 |
-
# Model | Tokenizer | Pretrained weights shortcut
|
189 |
-
MODELS = [(BertModel, BertTokenizer, 'bert-base-uncased'),
|
190 |
-
(OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),
|
191 |
-
(GPT2Model, GPT2Tokenizer, 'gpt2'),
|
192 |
-
(CTRLModel, CTRLTokenizer, 'ctrl'),
|
193 |
-
(TransfoXLModel, TransfoXLTokenizer, 'transfo-xl-wt103'),
|
194 |
-
(XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),
|
195 |
-
(XLMModel, XLMTokenizer, 'xlm-mlm-enfr-1024'),
|
196 |
-
(DistilBertModel, DistilBertTokenizer, 'distilbert-base-uncased'),
|
197 |
-
(RobertaModel, RobertaTokenizer, 'roberta-base'),
|
198 |
-
(XLMRobertaModel, XLMRobertaTokenizer, 'xlm-roberta-base'),
|
199 |
-
]
|
200 |
-
|
201 |
-
# To use TensorFlow 2.0 versions of the models, simply prefix the class names with 'TF', e.g. `TFRobertaModel` is the TF 2.0 counterpart of the PyTorch model `RobertaModel`
|
202 |
-
|
203 |
-
# Let's encode some text in a sequence of hidden-states using each model:
|
204 |
-
for model_class, tokenizer_class, pretrained_weights in MODELS:
|
205 |
-
# Load pretrained model/tokenizer
|
206 |
-
tokenizer = tokenizer_class.from_pretrained(pretrained_weights)
|
207 |
-
model = model_class.from_pretrained(pretrained_weights)
|
208 |
-
|
209 |
-
# Encode text
|
210 |
-
input_ids = torch.tensor([tokenizer.encode("Here is some text to encode", add_special_tokens=True)]) # Add special tokens takes care of adding [CLS], [SEP], <s>... tokens in the right way for each model.
|
211 |
-
with torch.no_grad():
|
212 |
-
last_hidden_states = model(input_ids)[0] # Models outputs are now tuples
|
213 |
-
|
214 |
-
# Each architecture is provided with several class for fine-tuning on down-stream tasks, e.g.
|
215 |
-
BERT_MODEL_CLASSES = [BertModel, BertForPreTraining, BertForMaskedLM, BertForNextSentencePrediction,
|
216 |
-
BertForSequenceClassification, BertForTokenClassification, BertForQuestionAnswering]
|
217 |
-
|
218 |
-
# All the classes for an architecture can be initiated from pretrained weights for this architecture
|
219 |
-
# Note that additional weights added for fine-tuning are only initialized
|
220 |
-
# and need to be trained on the down-stream task
|
221 |
-
pretrained_weights = 'bert-base-uncased'
|
222 |
-
tokenizer = BertTokenizer.from_pretrained(pretrained_weights)
|
223 |
-
for model_class in BERT_MODEL_CLASSES:
|
224 |
-
# Load pretrained model/tokenizer
|
225 |
-
model = model_class.from_pretrained(pretrained_weights)
|
226 |
-
|
227 |
-
# Models can return full list of hidden-states & attentions weights at each layer
|
228 |
-
model = model_class.from_pretrained(pretrained_weights,
|
229 |
-
output_hidden_states=True,
|
230 |
-
output_attentions=True)
|
231 |
-
input_ids = torch.tensor([tokenizer.encode("Let's see all hidden-states and attentions on this text")])
|
232 |
-
all_hidden_states, all_attentions = model(input_ids)[-2:]
|
233 |
-
|
234 |
-
# Models are compatible with Torchscript
|
235 |
-
model = model_class.from_pretrained(pretrained_weights, torchscript=True)
|
236 |
-
traced_model = torch.jit.trace(model, (input_ids,))
|
237 |
-
|
238 |
-
# Simple serialization for models and tokenizers
|
239 |
-
model.save_pretrained('./directory/to/save/') # save
|
240 |
-
model = model_class.from_pretrained('./directory/to/save/') # re-load
|
241 |
-
tokenizer.save_pretrained('./directory/to/save/') # save
|
242 |
-
tokenizer = BertTokenizer.from_pretrained('./directory/to/save/') # re-load
|
243 |
-
|
244 |
-
# SOTA examples for GLUE, SQUAD, text generation...
|
245 |
-
```
|
246 |
-
|
247 |
-
## Quick tour TF 2.0 training and PyTorch interoperability
|
248 |
-
|
249 |
-
Let's do a quick example of how a TensorFlow 2.0 model can be trained in 12 lines of code with 🤗 Transformers and then loaded in PyTorch for fast inspection/tests.
|
250 |
-
|
251 |
-
```python
|
252 |
-
import tensorflow as tf
|
253 |
-
import tensorflow_datasets
|
254 |
-
from transformers import *
|
255 |
-
|
256 |
-
# Load dataset, tokenizer, model from pretrained model/vocabulary
|
257 |
-
tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
|
258 |
-
model = TFBertForSequenceClassification.from_pretrained('bert-base-cased')
|
259 |
-
data = tensorflow_datasets.load('glue/mrpc')
|
260 |
-
|
261 |
-
# Prepare dataset for GLUE as a tf.data.Dataset instance
|
262 |
-
train_dataset = glue_convert_examples_to_features(data['train'], tokenizer, max_length=128, task='mrpc')
|
263 |
-
valid_dataset = glue_convert_examples_to_features(data['validation'], tokenizer, max_length=128, task='mrpc')
|
264 |
-
train_dataset = train_dataset.shuffle(100).batch(32).repeat(2)
|
265 |
-
valid_dataset = valid_dataset.batch(64)
|
266 |
-
|
267 |
-
# Prepare training: Compile tf.keras model with optimizer, loss and learning rate schedule
|
268 |
-
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)
|
269 |
-
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
270 |
-
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
|
271 |
-
model.compile(optimizer=optimizer, loss=loss, metrics=[metric])
|
272 |
-
|
273 |
-
# Train and evaluate using tf.keras.Model.fit()
|
274 |
-
history = model.fit(train_dataset, epochs=2, steps_per_epoch=115,
|
275 |
-
validation_data=valid_dataset, validation_steps=7)
|
276 |
-
|
277 |
-
# Load the TensorFlow model in PyTorch for inspection
|
278 |
-
model.save_pretrained('./save/')
|
279 |
-
pytorch_model = BertForSequenceClassification.from_pretrained('./save/', from_tf=True)
|
280 |
-
|
281 |
-
# Quickly test a few predictions - MRPC is a paraphrasing task, let's see if our model learned the task
|
282 |
-
sentence_0 = "This research was consistent with his findings."
|
283 |
-
sentence_1 = "His findings were compatible with this research."
|
284 |
-
sentence_2 = "His findings were not compatible with this research."
|
285 |
-
inputs_1 = tokenizer.encode_plus(sentence_0, sentence_1, add_special_tokens=True, return_tensors='pt')
|
286 |
-
inputs_2 = tokenizer.encode_plus(sentence_0, sentence_2, add_special_tokens=True, return_tensors='pt')
|
287 |
-
|
288 |
-
pred_1 = pytorch_model(inputs_1['input_ids'], token_type_ids=inputs_1['token_type_ids'])[0].argmax().item()
|
289 |
-
pred_2 = pytorch_model(inputs_2['input_ids'], token_type_ids=inputs_2['token_type_ids'])[0].argmax().item()
|
290 |
-
|
291 |
-
print("sentence_1 is", "a paraphrase" if pred_1 else "not a paraphrase", "of sentence_0")
|
292 |
-
print("sentence_2 is", "a paraphrase" if pred_2 else "not a paraphrase", "of sentence_0")
|
293 |
-
```
|
294 |
-
|
295 |
-
## Quick tour of the fine-tuning/usage scripts
|
296 |
-
|
297 |
-
**Important**
|
298 |
-
Before running the fine-tuning scripts, please read the
|
299 |
-
[instructions](#run-the-examples) on how to
|
300 |
-
setup your environment to run the examples.
|
301 |
-
|
302 |
-
The library comprises several example scripts with SOTA performances for NLU and NLG tasks:
|
303 |
-
|
304 |
-
- `run_glue.py`: an example fine-tuning Bert, XLNet and XLM on nine different GLUE tasks (*sequence-level classification*)
|
305 |
-
- `run_squad.py`: an example fine-tuning Bert, XLNet and XLM on the question answering dataset SQuAD 2.0 (*token-level classification*)
|
306 |
-
- `run_generation.py`: an example using GPT, GPT-2, CTRL, Transformer-XL and XLNet for conditional language generation
|
307 |
-
- other model-specific examples (see the documentation).
|
308 |
-
|
309 |
-
Here are three quick usage examples for these scripts:
|
310 |
-
|
311 |
-
### `run_glue.py`: Fine-tuning on GLUE tasks for sequence classification
|
312 |
-
|
313 |
-
The [General Language Understanding Evaluation (GLUE) benchmark](https://gluebenchmark.com/) is a collection of nine sentence- or sentence-pair language understanding tasks for evaluating and analyzing natural language understanding systems.
|
314 |
-
|
315 |
-
Before running anyone of these GLUE tasks you should download the
|
316 |
-
[GLUE data](https://gluebenchmark.com/tasks) by running
|
317 |
-
[this script](https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e)
|
318 |
-
and unpack it to some directory `$GLUE_DIR`.
|
319 |
-
|
320 |
-
You should also install the additional packages required by the examples:
|
321 |
-
|
322 |
-
```shell
|
323 |
-
pip install -r ./examples/requirements.txt
|
324 |
-
```
|
325 |
-
|
326 |
-
```shell
|
327 |
-
export GLUE_DIR=/path/to/glue
|
328 |
-
export TASK_NAME=MRPC
|
329 |
-
|
330 |
-
python ./examples/run_glue.py \
|
331 |
-
--model_type bert \
|
332 |
-
--model_name_or_path bert-base-uncased \
|
333 |
-
--task_name $TASK_NAME \
|
334 |
-
--do_train \
|
335 |
-
--do_eval \
|
336 |
-
--do_lower_case \
|
337 |
-
--data_dir $GLUE_DIR/$TASK_NAME \
|
338 |
-
--max_seq_length 128 \
|
339 |
-
--per_gpu_eval_batch_size=8 \
|
340 |
-
--per_gpu_train_batch_size=8 \
|
341 |
-
--learning_rate 2e-5 \
|
342 |
-
--num_train_epochs 3.0 \
|
343 |
-
--output_dir /tmp/$TASK_NAME/
|
344 |
-
```
|
345 |
-
|
346 |
-
where task name can be one of CoLA, SST-2, MRPC, STS-B, QQP, MNLI, QNLI, RTE, WNLI.
|
347 |
-
|
348 |
-
The dev set results will be present within the text file 'eval_results.txt' in the specified output_dir. In case of MNLI, since there are two separate dev sets, matched and mismatched, there will be a separate output folder called '/tmp/MNLI-MM/' in addition to '/tmp/MNLI/'.
|
349 |
-
|
350 |
-
#### Fine-tuning XLNet model on the STS-B regression task
|
351 |
-
|
352 |
-
This example code fine-tunes XLNet on the STS-B corpus using parallel training on a server with 4 V100 GPUs.
|
353 |
-
Parallel training is a simple way to use several GPUs (but is slower and less flexible than distributed training, see below).
|
354 |
-
|
355 |
-
```shell
|
356 |
-
export GLUE_DIR=/path/to/glue
|
357 |
-
|
358 |
-
python ./examples/run_glue.py \
|
359 |
-
--model_type xlnet \
|
360 |
-
--model_name_or_path xlnet-large-cased \
|
361 |
-
--do_train \
|
362 |
-
--do_eval \
|
363 |
-
--task_name=sts-b \
|
364 |
-
--data_dir=${GLUE_DIR}/STS-B \
|
365 |
-
--output_dir=./proc_data/sts-b-110 \
|
366 |
-
--max_seq_length=128 \
|
367 |
-
--per_gpu_eval_batch_size=8 \
|
368 |
-
--per_gpu_train_batch_size=8 \
|
369 |
-
--gradient_accumulation_steps=1 \
|
370 |
-
--max_steps=1200 \
|
371 |
-
--model_name=xlnet-large-cased \
|
372 |
-
--overwrite_output_dir \
|
373 |
-
--overwrite_cache \
|
374 |
-
--warmup_steps=120
|
375 |
-
```
|
376 |
-
|
377 |
-
On this machine we thus have a batch size of 32, please increase `gradient_accumulation_steps` to reach the same batch size if you have a smaller machine. These hyper-parameters should result in a Pearson correlation coefficient of `+0.917` on the development set.
|
378 |
-
|
379 |
-
#### Fine-tuning Bert model on the MRPC classification task
|
380 |
-
|
381 |
-
This example code fine-tunes the Bert Whole Word Masking model on the Microsoft Research Paraphrase Corpus (MRPC) corpus using distributed training on 8 V100 GPUs to reach a F1 > 92.
|
382 |
-
|
383 |
-
```bash
|
384 |
-
python -m torch.distributed.launch --nproc_per_node 8 ./examples/run_glue.py \
|
385 |
-
--model_type bert \
|
386 |
-
--model_name_or_path bert-large-uncased-whole-word-masking \
|
387 |
-
--task_name MRPC \
|
388 |
-
--do_train \
|
389 |
-
--do_eval \
|
390 |
-
--do_lower_case \
|
391 |
-
--data_dir $GLUE_DIR/MRPC/ \
|
392 |
-
--max_seq_length 128 \
|
393 |
-
--per_gpu_eval_batch_size=8 \
|
394 |
-
--per_gpu_train_batch_size=8 \
|
395 |
-
--learning_rate 2e-5 \
|
396 |
-
--num_train_epochs 3.0 \
|
397 |
-
--output_dir /tmp/mrpc_output/ \
|
398 |
-
--overwrite_output_dir \
|
399 |
-
--overwrite_cache \
|
400 |
-
```
|
401 |
-
|
402 |
-
Training with these hyper-parameters gave us the following results:
|
403 |
-
|
404 |
-
```bash
|
405 |
-
acc = 0.8823529411764706
|
406 |
-
acc_and_f1 = 0.901702786377709
|
407 |
-
eval_loss = 0.3418912578906332
|
408 |
-
f1 = 0.9210526315789473
|
409 |
-
global_step = 174
|
410 |
-
loss = 0.07231863956341798
|
411 |
-
```
|
412 |
-
|
413 |
-
### `run_squad.py`: Fine-tuning on SQuAD for question-answering
|
414 |
-
|
415 |
-
This example code fine-tunes BERT on the SQuAD dataset using distributed training on 8 V100 GPUs and Bert Whole Word Masking uncased model to reach a F1 > 93 on SQuAD:
|
416 |
-
|
417 |
-
```bash
|
418 |
-
python -m torch.distributed.launch --nproc_per_node=8 ./examples/run_squad.py \
|
419 |
-
--model_type bert \
|
420 |
-
--model_name_or_path bert-large-uncased-whole-word-masking \
|
421 |
-
--do_train \
|
422 |
-
--do_eval \
|
423 |
-
--do_lower_case \
|
424 |
-
--train_file $SQUAD_DIR/train-v1.1.json \
|
425 |
-
--predict_file $SQUAD_DIR/dev-v1.1.json \
|
426 |
-
--learning_rate 3e-5 \
|
427 |
-
--num_train_epochs 2 \
|
428 |
-
--max_seq_length 384 \
|
429 |
-
--doc_stride 128 \
|
430 |
-
--output_dir ../models/wwm_uncased_finetuned_squad/ \
|
431 |
-
--per_gpu_eval_batch_size=3 \
|
432 |
-
--per_gpu_train_batch_size=3 \
|
433 |
-
```
|
434 |
-
|
435 |
-
Training with these hyper-parameters gave us the following results:
|
436 |
-
|
437 |
-
```bash
|
438 |
-
python $SQUAD_DIR/evaluate-v1.1.py $SQUAD_DIR/dev-v1.1.json ../models/wwm_uncased_finetuned_squad/predictions.json
|
439 |
-
{"exact_match": 86.91579943235573, "f1": 93.1532499015869}
|
440 |
-
```
|
441 |
-
|
442 |
-
This is the model provided as `bert-large-uncased-whole-word-masking-finetuned-squad`.
|
443 |
-
|
444 |
-
### `run_generation.py`: Text generation with GPT, GPT-2, CTRL, Transformer-XL and XLNet
|
445 |
-
|
446 |
-
A conditional generation script is also included to generate text from a prompt.
|
447 |
-
The generation script includes the [tricks](https://github.com/rusiaaman/XLNet-gen#methodology) proposed by Aman Rusia to get high-quality generation with memory models like Transformer-XL and XLNet (include a predefined text to make short inputs longer).
|
448 |
-
|
449 |
-
Here is how to run the script with the small version of OpenAI GPT-2 model:
|
450 |
-
|
451 |
-
```shell
|
452 |
-
python ./examples/run_generation.py \
|
453 |
-
--model_type=gpt2 \
|
454 |
-
--length=20 \
|
455 |
-
--model_name_or_path=gpt2 \
|
456 |
-
```
|
457 |
-
|
458 |
-
and from the Salesforce CTRL model:
|
459 |
-
```shell
|
460 |
-
python ./examples/run_generation.py \
|
461 |
-
--model_type=ctrl \
|
462 |
-
--length=20 \
|
463 |
-
--model_name_or_path=ctrl \
|
464 |
-
--temperature=0 \
|
465 |
-
--repetition_penalty=1.2 \
|
466 |
-
```
|
467 |
-
|
468 |
-
## Quick tour of model sharing
|
469 |
-
|
470 |
-
Starting with `v2.2.2`, you can now upload and share your fine-tuned models with the community, using the <abbr title="Command-line interface">CLI</abbr> that's built-in to the library.
|
471 |
-
|
472 |
-
**First, create an account on [https://huggingface.co/join](https://huggingface.co/join)**. Then:
|
473 |
-
|
474 |
-
```shell
|
475 |
-
transformers-cli login
|
476 |
-
# log in using the same credentials as on huggingface.co
|
477 |
-
```
|
478 |
-
Upload your model:
|
479 |
-
```shell
|
480 |
-
transformers-cli upload ./path/to/pretrained_model/
|
481 |
-
|
482 |
-
# ^^ Upload folder containing weights/tokenizer/config
|
483 |
-
# saved via `.save_pretrained()`
|
484 |
-
|
485 |
-
transformers-cli upload ./config.json [--filename folder/foobar.json]
|
486 |
-
|
487 |
-
# ^^ Upload a single file
|
488 |
-
# (you can optionally override its filename, which can be nested inside a folder)
|
489 |
-
```
|
490 |
-
|
491 |
-
Your model will then be accessible through its identifier, a concatenation of your username and the folder name above:
|
492 |
-
```python
|
493 |
-
"username/pretrained_model"
|
494 |
-
```
|
495 |
-
|
496 |
-
Anyone can load it from code:
|
497 |
-
```python
|
498 |
-
tokenizer = AutoTokenizer.from_pretrained("username/pretrained_model")
|
499 |
-
model = AutoModel.from_pretrained("username/pretrained_model")
|
500 |
-
```
|
501 |
-
|
502 |
-
Finally, list all your files on S3:
|
503 |
-
```shell
|
504 |
-
transformers-cli s3 ls
|
505 |
-
# List all your S3 objects.
|
506 |
-
```
|
507 |
-
|
508 |
-
You can also delete files:
|
509 |
-
|
510 |
-
```shell
|
511 |
-
transformers-cli s3 rm …
|
512 |
-
```
|
513 |
-
|
514 |
-
## Quick tour of pipelines
|
515 |
-
|
516 |
-
New in version `v2.3`: `Pipeline` are high-level objects which automatically handle tokenization, running your data through a transformers model
|
517 |
-
and outputting the result in a structured object.
|
518 |
-
|
519 |
-
You can create `Pipeline` objects for the following down-stream tasks:
|
520 |
-
|
521 |
-
- `feature-extraction`: Generates a tensor representation for the input sequence
|
522 |
-
- `ner`: Generates named entity mapping for each word in the input sequence.
|
523 |
-
- `sentiment-analysis`: Gives the polarity (positive / negative) of the whole input sequence.
|
524 |
-
- `text-classification`: Initialize a `TextClassificationPipeline` directly, or see `sentiment-analysis` for an example.
|
525 |
-
- `question-answering`: Provided some context and a question refering to the context, it will extract the answer to the question in the context.
|
526 |
-
- `fill-mask`: Takes an input sequence containing a masked token (e.g. `<mask>`) and return list of most probable filled sequences, with their probabilities.
|
527 |
-
|
528 |
-
```python
|
529 |
-
from transformers import pipeline
|
530 |
-
|
531 |
-
# Allocate a pipeline for sentiment-analysis
|
532 |
-
nlp = pipeline('sentiment-analysis')
|
533 |
-
nlp('We are very happy to include pipeline into the transformers repository.')
|
534 |
-
>>> {'label': 'POSITIVE', 'score': 0.99893874}
|
535 |
-
|
536 |
-
# Allocate a pipeline for question-answering
|
537 |
-
nlp = pipeline('question-answering')
|
538 |
-
nlp({
|
539 |
-
'question': 'What is the name of the repository ?',
|
540 |
-
'context': 'Pipeline have been included in the huggingface/transformers repository'
|
541 |
-
})
|
542 |
-
>>> {'score': 0.28756016668193496, 'start': 35, 'end': 59, 'answer': 'huggingface/transformers'}
|
543 |
-
```
|
544 |
-
|
545 |
-
## Migrating from pytorch-transformers to transformers
|
546 |
-
|
547 |
-
Here is a quick summary of what you should take care of when migrating from `pytorch-transformers` to `transformers`.
|
548 |
-
|
549 |
-
### Positional order of some models' keywords inputs (`attention_mask`, `token_type_ids`...) changed
|
550 |
-
|
551 |
-
To be able to use Torchscript (see #1010, #1204 and #1195) the specific order of some models **keywords inputs** (`attention_mask`, `token_type_ids`...) has been changed.
|
552 |
-
|
553 |
-
If you used to call the models with keyword names for keyword arguments, e.g. `model(inputs_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)`, this should not cause any change.
|
554 |
-
|
555 |
-
If you used to call the models with positional inputs for keyword arguments, e.g. `model(inputs_ids, attention_mask, token_type_ids)`, you may have to double check the exact order of input arguments.
|
556 |
-
|
557 |
-
|
558 |
-
## Migrating from pytorch-pretrained-bert to transformers
|
559 |
-
|
560 |
-
Here is a quick summary of what you should take care of when migrating from `pytorch-pretrained-bert` to `transformers`.
|
561 |
-
|
562 |
-
### Models always output `tuples`
|
563 |
-
|
564 |
-
The main breaking change when migrating from `pytorch-pretrained-bert` to `transformers` is that every model's forward method always outputs a `tuple` with various elements depending on the model and the configuration parameters.
|
565 |
-
|
566 |
-
The exact content of the tuples for each model is detailed in the models' docstrings and the [documentation](https://huggingface.co/transformers/).
|
567 |
-
|
568 |
-
In pretty much every case, you will be fine by taking the first element of the output as the output you previously used in `pytorch-pretrained-bert`.
|
569 |
-
|
570 |
-
Here is a `pytorch-pretrained-bert` to `transformers` conversion example for a `BertForSequenceClassification` classification model:
|
571 |
-
|
572 |
-
```python
|
573 |
-
# Let's load our model
|
574 |
-
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
|
575 |
-
|
576 |
-
# If you used to have this line in pytorch-pretrained-bert:
|
577 |
-
loss = model(input_ids, labels=labels)
|
578 |
-
|
579 |
-
# Now just use this line in transformers to extract the loss from the output tuple:
|
580 |
-
outputs = model(input_ids, labels=labels)
|
581 |
-
loss = outputs[0]
|
582 |
-
|
583 |
-
# In transformers you can also have access to the logits:
|
584 |
-
loss, logits = outputs[:2]
|
585 |
-
|
586 |
-
# And even the attention weights if you configure the model to output them (and other outputs too, see the docstrings and documentation)
|
587 |
-
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', output_attentions=True)
|
588 |
-
outputs = model(input_ids, labels=labels)
|
589 |
-
loss, logits, attentions = outputs
|
590 |
-
```
|
591 |
-
|
592 |
-
### Using hidden states
|
593 |
-
|
594 |
-
By enabling the configuration option `output_hidden_states`, it was possible to retrieve the last hidden states of the encoder. In `pytorch-transformers` as well as `transformers` the return value has changed slightly: `all_hidden_states` now also includes the hidden state of the embeddings in addition to those of the encoding layers. This allows users to easily access the embeddings final state.
|
595 |
-
|
596 |
-
### Serialization
|
597 |
-
|
598 |
-
Breaking change in the `from_pretrained()` method:
|
599 |
-
|
600 |
-
1. Models are now set in evaluation mode by default when instantiated with the `from_pretrained()` method. To train them, don't forget to set them back in training mode (`model.train()`) to activate the dropout modules.
|
601 |
-
|
602 |
-
2. The additional `*input` and `**kwargs` arguments supplied to the `from_pretrained()` method used to be directly passed to the underlying model's class `__init__()` method. They are now used to update the model configuration attribute instead, which can break derived model classes built based on the previous `BertForSequenceClassification` examples. We are working on a way to mitigate this breaking change in [#866](https://github.com/huggingface/transformers/pull/866) by forwarding the the model's `__init__()` method (i) the provided positional arguments and (ii) the keyword arguments which do not match any configuration class attributes.
|
603 |
-
|
604 |
-
Also, while not a breaking change, the serialization methods have been standardized and you probably should switch to the new method `save_pretrained(save_directory)` if you were using any other serialization method before.
|
605 |
-
|
606 |
-
Here is an example:
|
607 |
-
|
608 |
-
```python
|
609 |
-
### Let's load a model and tokenizer
|
610 |
-
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
|
611 |
-
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
612 |
-
|
613 |
-
### Do some stuff to our model and tokenizer
|
614 |
-
# Ex: add new tokens to the vocabulary and embeddings of our model
|
615 |
-
tokenizer.add_tokens(['[SPECIAL_TOKEN_1]', '[SPECIAL_TOKEN_2]'])
|
616 |
-
model.resize_token_embeddings(len(tokenizer))
|
617 |
-
# Train our model
|
618 |
-
train(model)
|
619 |
-
|
620 |
-
### Now let's save our model and tokenizer to a directory
|
621 |
-
model.save_pretrained('./my_saved_model_directory/')
|
622 |
-
tokenizer.save_pretrained('./my_saved_model_directory/')
|
623 |
-
|
624 |
-
### Reload the model and the tokenizer
|
625 |
-
model = BertForSequenceClassification.from_pretrained('./my_saved_model_directory/')
|
626 |
-
tokenizer = BertTokenizer.from_pretrained('./my_saved_model_directory/')
|
627 |
-
```
|
628 |
-
|
629 |
-
### Optimizers: BertAdam & OpenAIAdam are now AdamW, schedules are standard PyTorch schedules
|
630 |
-
|
631 |
-
The two optimizers previously included, `BertAdam` and `OpenAIAdam`, have been replaced by a single `AdamW` optimizer which has a few differences:
|
632 |
-
|
633 |
-
- it only implements weights decay correction,
|
634 |
-
- schedules are now externals (see below),
|
635 |
-
- gradient clipping is now also external (see below).
|
636 |
-
|
637 |
-
The new optimizer `AdamW` matches PyTorch `Adam` optimizer API and let you use standard PyTorch or apex methods for the schedule and clipping.
|
638 |
-
|
639 |
-
The schedules are now standard [PyTorch learning rate schedulers](https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate) and not part of the optimizer anymore.
|
640 |
-
|
641 |
-
Here is a conversion examples from `BertAdam` with a linear warmup and decay schedule to `AdamW` and the same schedule:
|
642 |
-
|
643 |
-
```python
|
644 |
-
# Parameters:
|
645 |
-
lr = 1e-3
|
646 |
-
max_grad_norm = 1.0
|
647 |
-
num_training_steps = 1000
|
648 |
-
num_warmup_steps = 100
|
649 |
-
warmup_proportion = float(num_warmup_steps) / float(num_training_steps) # 0.1
|
650 |
-
|
651 |
-
### Previously BertAdam optimizer was instantiated like this:
|
652 |
-
optimizer = BertAdam(model.parameters(), lr=lr, schedule='warmup_linear', warmup=warmup_proportion, t_total=num_training_steps)
|
653 |
-
### and used like this:
|
654 |
-
for batch in train_data:
|
655 |
-
loss = model(batch)
|
656 |
-
loss.backward()
|
657 |
-
optimizer.step()
|
658 |
-
|
659 |
-
### In Transformers, optimizer and schedules are splitted and instantiated like this:
|
660 |
-
optimizer = AdamW(model.parameters(), lr=lr, correct_bias=False) # To reproduce BertAdam specific behavior set correct_bias=False
|
661 |
-
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps) # PyTorch scheduler
|
662 |
-
### and used like this:
|
663 |
-
for batch in train_data:
|
664 |
-
model.train()
|
665 |
-
loss = model(batch)
|
666 |
-
loss.backward()
|
667 |
-
torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm) # Gradient clipping is not in AdamW anymore (so you can use amp without issue)
|
668 |
-
optimizer.step()
|
669 |
-
scheduler.step()
|
670 |
-
optimizer.zero_grad()
|
671 |
-
```
|
672 |
-
|
673 |
-
## Citation
|
674 |
-
|
675 |
-
We now have a paper you can cite for the 🤗 Transformers library:
|
676 |
-
```
|
677 |
-
@article{Wolf2019HuggingFacesTS,
|
678 |
-
title={HuggingFace's Transformers: State-of-the-art Natural Language Processing},
|
679 |
-
author={Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and R'emi Louf and Morgan Funtowicz and Jamie Brew},
|
680 |
-
journal={ArXiv},
|
681 |
-
year={2019},
|
682 |
-
volume={abs/1910.03771}
|
683 |
-
}
|
684 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/deploy_multi_version_doc.sh
DELETED
@@ -1,23 +0,0 @@
|
|
1 |
-
cd docs
|
2 |
-
|
3 |
-
function deploy_doc(){
|
4 |
-
echo "Creating doc at commit $1 and pushing to folder $2"
|
5 |
-
git checkout $1
|
6 |
-
if [ ! -z "$2" ]
|
7 |
-
then
|
8 |
-
echo "Pushing version" $2
|
9 |
-
make clean && make html && scp -r -oStrictHostKeyChecking=no _build/html $doc:$dir/$2
|
10 |
-
else
|
11 |
-
echo "Pushing master"
|
12 |
-
make clean && make html && scp -r -oStrictHostKeyChecking=no _build/html/* $doc:$dir
|
13 |
-
fi
|
14 |
-
}
|
15 |
-
|
16 |
-
deploy_doc "master"
|
17 |
-
deploy_doc "b33a385" v1.0.0
|
18 |
-
deploy_doc "fe02e45" v1.1.0
|
19 |
-
deploy_doc "89fd345" v1.2.0
|
20 |
-
deploy_doc "fc9faa8" v2.0.0
|
21 |
-
deploy_doc "3ddce1d" v2.1.1
|
22 |
-
deploy_doc "f2f3294" v2.2.0
|
23 |
-
deploy_doc "d0f8b9a" v2.3.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docker/Dockerfile
DELETED
@@ -1,7 +0,0 @@
|
|
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 transformers
|
6 |
-
|
7 |
-
WORKDIR /workspace
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/Makefile
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
# Minimal makefile for Sphinx documentation
|
2 |
-
#
|
3 |
-
|
4 |
-
# You can set these variables from the command line.
|
5 |
-
SPHINXOPTS =
|
6 |
-
SPHINXBUILD = sphinx-build
|
7 |
-
SOURCEDIR = source
|
8 |
-
BUILDDIR = _build
|
9 |
-
|
10 |
-
# Put it first so that "make" without argument is like "make help".
|
11 |
-
help:
|
12 |
-
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
13 |
-
|
14 |
-
.PHONY: help Makefile
|
15 |
-
|
16 |
-
# Catch-all target: route all unknown targets to Sphinx using the new
|
17 |
-
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
18 |
-
%: Makefile
|
19 |
-
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/README.md
DELETED
@@ -1,67 +0,0 @@
|
|
1 |
-
# Generating the documentation
|
2 |
-
|
3 |
-
To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
|
4 |
-
you can install them with the following command, at the root of the code repository:
|
5 |
-
|
6 |
-
```bash
|
7 |
-
pip install -e ".[docs]"
|
8 |
-
```
|
9 |
-
|
10 |
-
## Packages installed
|
11 |
-
|
12 |
-
Here's an overview of all the packages installed. If you ran the previous command installing all packages from
|
13 |
-
`requirements.txt`, you do not need to run the following commands.
|
14 |
-
|
15 |
-
Building it requires the package `sphinx` that you can
|
16 |
-
install using:
|
17 |
-
|
18 |
-
```bash
|
19 |
-
pip install -U sphinx
|
20 |
-
```
|
21 |
-
|
22 |
-
You would also need the custom installed [theme](https://github.com/readthedocs/sphinx_rtd_theme) by
|
23 |
-
[Read The Docs](https://readthedocs.org/). You can install it using the following command:
|
24 |
-
|
25 |
-
```bash
|
26 |
-
pip install sphinx_rtd_theme
|
27 |
-
```
|
28 |
-
|
29 |
-
The third necessary package is the `recommonmark` package to accept Markdown as well as Restructured text:
|
30 |
-
|
31 |
-
```bash
|
32 |
-
pip install recommonmark
|
33 |
-
```
|
34 |
-
|
35 |
-
## Building the documentation
|
36 |
-
|
37 |
-
Make sure that there is a symlink from the `example` file (in /examples) inside the source folder. Run the following
|
38 |
-
command to generate it:
|
39 |
-
|
40 |
-
```bash
|
41 |
-
ln -s ../../examples/README.md examples.md
|
42 |
-
```
|
43 |
-
|
44 |
-
Once you have setup `sphinx`, you can build the documentation by running the following command in the `/docs` folder:
|
45 |
-
|
46 |
-
```bash
|
47 |
-
make html
|
48 |
-
```
|
49 |
-
|
50 |
-
---
|
51 |
-
**NOTE**
|
52 |
-
|
53 |
-
If you are adding/removing elements from the toc-tree or from any structural item, it is recommended to clean the build
|
54 |
-
directory before rebuilding. Run the following command to clean and build:
|
55 |
-
|
56 |
-
```bash
|
57 |
-
make clean && make html
|
58 |
-
```
|
59 |
-
|
60 |
-
---
|
61 |
-
|
62 |
-
It should build the static app that will be available under `/docs/_build/html`
|
63 |
-
|
64 |
-
## Adding a new element to the tree (toc-tree)
|
65 |
-
|
66 |
-
Accepted files are reStructuredText (.rst) and Markdown (.md). Create a file with its extension and put it
|
67 |
-
in the source directory. You can then link it to the toc-tree by putting the filename without the extension.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/source/_static/css/Calibre-Light.ttf
DELETED
Binary file (62.5 kB)
|
|
server/transformers/docs/source/_static/css/Calibre-Medium.otf
DELETED
Binary file (47.9 kB)
|
|
server/transformers/docs/source/_static/css/Calibre-Regular.otf
DELETED
Binary file (49.9 kB)
|
|
server/transformers/docs/source/_static/css/Calibre-Thin.otf
DELETED
Binary file (46.7 kB)
|
|
server/transformers/docs/source/_static/css/code-snippets.css
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
|
2 |
-
.highlight .c1, .highlight .sd{
|
3 |
-
color: #999
|
4 |
-
}
|
5 |
-
|
6 |
-
.highlight .nn, .highlight .k, .highlight .s1, .highlight .nb, .highlight .bp, .highlight .kc {
|
7 |
-
color: #FB8D68;
|
8 |
-
}
|
9 |
-
|
10 |
-
.highlight .kn, .highlight .nv, .highlight .s2, .highlight .ow {
|
11 |
-
color: #6670FF;
|
12 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/source/_static/css/huggingface.css
DELETED
@@ -1,196 +0,0 @@
|
|
1 |
-
/* The literal code blocks */
|
2 |
-
.rst-content tt.literal, .rst-content tt.literal, .rst-content code.literal {
|
3 |
-
color: #6670FF;
|
4 |
-
}
|
5 |
-
|
6 |
-
/* To keep the logo centered */
|
7 |
-
.wy-side-scroll {
|
8 |
-
width: auto;
|
9 |
-
font-size: 20px;
|
10 |
-
}
|
11 |
-
|
12 |
-
/* The div that holds the Hugging Face logo */
|
13 |
-
.HuggingFaceDiv {
|
14 |
-
width: 100%
|
15 |
-
}
|
16 |
-
|
17 |
-
/* The research field on top of the toc tree */
|
18 |
-
.wy-side-nav-search{
|
19 |
-
background-color: #6670FF;
|
20 |
-
}
|
21 |
-
|
22 |
-
/* The toc tree */
|
23 |
-
.wy-nav-side{
|
24 |
-
background-color: #6670FF;
|
25 |
-
}
|
26 |
-
|
27 |
-
/* The selected items in the toc tree */
|
28 |
-
.wy-menu-vertical li.current{
|
29 |
-
background-color: #A6B0FF;
|
30 |
-
}
|
31 |
-
|
32 |
-
/* When a list item that does belong to the selected block from the toc tree is hovered */
|
33 |
-
.wy-menu-vertical li.current a:hover{
|
34 |
-
background-color: #B6C0FF;
|
35 |
-
}
|
36 |
-
|
37 |
-
/* When a list item that does NOT belong to the selected block from the toc tree is hovered. */
|
38 |
-
.wy-menu-vertical li a:hover{
|
39 |
-
background-color: #A7AFFB;
|
40 |
-
}
|
41 |
-
|
42 |
-
/* The text items on the toc tree */
|
43 |
-
.wy-menu-vertical a {
|
44 |
-
color: #FFFFDD;
|
45 |
-
font-family: Calibre-Light, sans-serif;
|
46 |
-
}
|
47 |
-
.wy-menu-vertical header, .wy-menu-vertical p.caption{
|
48 |
-
color: white;
|
49 |
-
font-family: Calibre-Light, sans-serif;
|
50 |
-
}
|
51 |
-
|
52 |
-
/* The color inside the selected toc tree block */
|
53 |
-
.wy-menu-vertical li.toctree-l2 a, .wy-menu-vertical li.toctree-l3 a, .wy-menu-vertical li.toctree-l4 a {
|
54 |
-
color: black;
|
55 |
-
}
|
56 |
-
|
57 |
-
/* Inside the depth-2 selected toc tree block */
|
58 |
-
.wy-menu-vertical li.toctree-l2.current>a {
|
59 |
-
background-color: #B6C0FF
|
60 |
-
}
|
61 |
-
.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a {
|
62 |
-
background-color: #C6D0FF
|
63 |
-
}
|
64 |
-
|
65 |
-
/* Inside the depth-3 selected toc tree block */
|
66 |
-
.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{
|
67 |
-
background-color: #D6E0FF
|
68 |
-
}
|
69 |
-
|
70 |
-
/* Inside code snippets */
|
71 |
-
.rst-content dl:not(.docutils) dt{
|
72 |
-
font-size: 15px;
|
73 |
-
}
|
74 |
-
|
75 |
-
/* Links */
|
76 |
-
a {
|
77 |
-
color: #6670FF;
|
78 |
-
}
|
79 |
-
|
80 |
-
/* Content bars */
|
81 |
-
.rst-content dl:not(.docutils) dt {
|
82 |
-
background-color: rgba(251, 141, 104, 0.1);
|
83 |
-
border-right: solid 2px #FB8D68;
|
84 |
-
border-left: solid 2px #FB8D68;
|
85 |
-
color: #FB8D68;
|
86 |
-
font-family: Calibre-Light, sans-serif;
|
87 |
-
border-top: none;
|
88 |
-
font-style: normal !important;
|
89 |
-
}
|
90 |
-
|
91 |
-
/* Expand button */
|
92 |
-
.wy-menu-vertical li.toctree-l2 span.toctree-expand,
|
93 |
-
.wy-menu-vertical li.on a span.toctree-expand, .wy-menu-vertical li.current>a span.toctree-expand,
|
94 |
-
.wy-menu-vertical li.toctree-l3 span.toctree-expand{
|
95 |
-
color: black;
|
96 |
-
}
|
97 |
-
|
98 |
-
/* Max window size */
|
99 |
-
.wy-nav-content{
|
100 |
-
max-width: 1200px;
|
101 |
-
}
|
102 |
-
|
103 |
-
/* Mobile header */
|
104 |
-
.wy-nav-top{
|
105 |
-
background-color: #6670FF;
|
106 |
-
}
|
107 |
-
|
108 |
-
|
109 |
-
/* Source spans */
|
110 |
-
.rst-content .viewcode-link, .rst-content .viewcode-back{
|
111 |
-
color: #6670FF;
|
112 |
-
font-size: 110%;
|
113 |
-
letter-spacing: 2px;
|
114 |
-
text-transform: uppercase;
|
115 |
-
}
|
116 |
-
|
117 |
-
/* It would be better for table to be visible without horizontal scrolling */
|
118 |
-
.wy-table-responsive table td, .wy-table-responsive table th{
|
119 |
-
white-space: normal;
|
120 |
-
}
|
121 |
-
|
122 |
-
.footer {
|
123 |
-
margin-top: 20px;
|
124 |
-
}
|
125 |
-
|
126 |
-
.footer__Social {
|
127 |
-
display: flex;
|
128 |
-
flex-direction: row;
|
129 |
-
}
|
130 |
-
|
131 |
-
.footer__CustomImage {
|
132 |
-
margin: 2px 5px 0 0;
|
133 |
-
}
|
134 |
-
|
135 |
-
/* class and method names in doc */
|
136 |
-
.rst-content dl:not(.docutils) tt.descname, .rst-content dl:not(.docutils) tt.descclassname, .rst-content dl:not(.docutils) tt.descname, .rst-content dl:not(.docutils) code.descname, .rst-content dl:not(.docutils) tt.descclassname, .rst-content dl:not(.docutils) code.descclassname{
|
137 |
-
font-family: Calibre, sans-serif;
|
138 |
-
font-size: 20px !important;
|
139 |
-
}
|
140 |
-
|
141 |
-
/* class name in doc*/
|
142 |
-
.rst-content dl:not(.docutils) tt.descname, .rst-content dl:not(.docutils) tt.descname, .rst-content dl:not(.docutils) code.descname{
|
143 |
-
margin-right: 10px;
|
144 |
-
font-family: Calibre-Medium, sans-serif;
|
145 |
-
}
|
146 |
-
|
147 |
-
/* Method and class parameters */
|
148 |
-
.sig-param{
|
149 |
-
line-height: 23px;
|
150 |
-
}
|
151 |
-
|
152 |
-
/* Class introduction "class" string at beginning */
|
153 |
-
.rst-content dl:not(.docutils) .property{
|
154 |
-
font-size: 18px;
|
155 |
-
color: black;
|
156 |
-
}
|
157 |
-
|
158 |
-
|
159 |
-
/* FONTS */
|
160 |
-
body{
|
161 |
-
font-family: Calibre, sans-serif;
|
162 |
-
font-size: 16px;
|
163 |
-
}
|
164 |
-
|
165 |
-
h1 {
|
166 |
-
font-family: Calibre-Thin, sans-serif;
|
167 |
-
font-size: 70px;
|
168 |
-
}
|
169 |
-
|
170 |
-
h2, .rst-content .toctree-wrapper p.caption, h3, h4, h5, h6, legend{
|
171 |
-
font-family: Calibre-Medium, sans-serif;
|
172 |
-
}
|
173 |
-
|
174 |
-
@font-face {
|
175 |
-
font-family: Calibre-Medium;
|
176 |
-
src: url(./Calibre-Medium.otf);
|
177 |
-
font-weight:400;
|
178 |
-
}
|
179 |
-
|
180 |
-
@font-face {
|
181 |
-
font-family: Calibre;
|
182 |
-
src: url(./Calibre-Regular.otf);
|
183 |
-
font-weight:400;
|
184 |
-
}
|
185 |
-
|
186 |
-
@font-face {
|
187 |
-
font-family: Calibre-Light;
|
188 |
-
src: url(./Calibre-Light.ttf);
|
189 |
-
font-weight:400;
|
190 |
-
}
|
191 |
-
|
192 |
-
@font-face {
|
193 |
-
font-family: Calibre-Thin;
|
194 |
-
src: url(./Calibre-Thin.otf);
|
195 |
-
font-weight:400;
|
196 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/source/_static/js/custom.js
DELETED
@@ -1,79 +0,0 @@
|
|
1 |
-
function addIcon() {
|
2 |
-
const huggingFaceLogo = "https://huggingface.co/landing/assets/transformers-docs/huggingface_logo.svg";
|
3 |
-
const image = document.createElement("img");
|
4 |
-
image.setAttribute("src", huggingFaceLogo);
|
5 |
-
|
6 |
-
const div = document.createElement("div");
|
7 |
-
div.appendChild(image);
|
8 |
-
div.style.textAlign = 'center';
|
9 |
-
div.style.paddingTop = '30px';
|
10 |
-
div.style.backgroundColor = '#6670FF';
|
11 |
-
|
12 |
-
const scrollDiv = document.querySelector(".wy-side-scroll");
|
13 |
-
scrollDiv.prepend(div);
|
14 |
-
}
|
15 |
-
|
16 |
-
function addCustomFooter() {
|
17 |
-
const customFooter = document.createElement("div");
|
18 |
-
const questionOrIssue = document.createElement("div");
|
19 |
-
questionOrIssue.innerHTML = "Stuck? Read our <a href='https://medium.com/huggingface'>Blog posts</a> or <a href='https://github.com/huggingface/transformers'>Create an issue</a>";
|
20 |
-
customFooter.appendChild(questionOrIssue);
|
21 |
-
customFooter.classList.add("footer");
|
22 |
-
|
23 |
-
const social = document.createElement("div");
|
24 |
-
social.classList.add("footer__Social");
|
25 |
-
|
26 |
-
const imageDetails = [
|
27 |
-
{ link: "https://huggingface.co", imageLink: "https://huggingface.co/landing/assets/transformers-docs/website.svg" },
|
28 |
-
{ link: "https://twitter.com/huggingface", imageLink: "https://huggingface.co/landing/assets/transformers-docs/twitter.svg" },
|
29 |
-
{ link: "https://github.com/huggingface", imageLink: "https://huggingface.co/landing/assets/transformers-docs/github.svg" },
|
30 |
-
{ link: "https://www.linkedin.com/company/huggingface/", imageLink: "https://huggingface.co/landing/assets/transformers-docs/linkedin.svg" }
|
31 |
-
];
|
32 |
-
|
33 |
-
imageDetails.forEach(imageLinks => {
|
34 |
-
const link = document.createElement("a");
|
35 |
-
const image = document.createElement("img");
|
36 |
-
image.src = imageLinks.imageLink;
|
37 |
-
link.href = imageLinks.link;
|
38 |
-
image.style.width = "30px";
|
39 |
-
image.classList.add("footer__CustomImage");
|
40 |
-
link.appendChild(image);
|
41 |
-
social.appendChild(link);
|
42 |
-
});
|
43 |
-
|
44 |
-
customFooter.appendChild(social);
|
45 |
-
document.querySelector("footer").appendChild(customFooter);
|
46 |
-
}
|
47 |
-
|
48 |
-
function addGithubButton() {
|
49 |
-
const div = `
|
50 |
-
<div class="github-repo">
|
51 |
-
<a
|
52 |
-
class="github-button"
|
53 |
-
href="https://github.com/huggingface/transformers" data-size="large" data-show-count="true" aria-label="Star huggingface/pytorch-transformers on GitHub">
|
54 |
-
Star
|
55 |
-
</a>
|
56 |
-
</div>
|
57 |
-
`;
|
58 |
-
document.querySelector(".wy-side-nav-search .icon-home").insertAdjacentHTML('afterend', div);
|
59 |
-
}
|
60 |
-
|
61 |
-
/*!
|
62 |
-
* github-buttons v2.2.10
|
63 |
-
* (c) 2019 なつき
|
64 |
-
* @license BSD-2-Clause
|
65 |
-
*/
|
66 |
-
/**
|
67 |
-
* modified to run programmatically
|
68 |
-
*/
|
69 |
-
function parseGithubButtons (){"use strict";var e=window.document,t=e.location,o=window.encodeURIComponent,r=window.decodeURIComponent,n=window.Math,a=window.HTMLElement,i=window.XMLHttpRequest,l="https://unpkg.com/[email protected]/dist/buttons.html",c=i&&i.prototype&&"withCredentials"in i.prototype,d=c&&a&&a.prototype.attachShadow&&!a.prototype.attachShadow.prototype,s=function(e,t,o){e.addEventListener?e.addEventListener(t,o):e.attachEvent("on"+t,o)},u=function(e,t,o){e.removeEventListener?e.removeEventListener(t,o):e.detachEvent("on"+t,o)},h=function(e,t,o){var r=function(n){return u(e,t,r),o(n)};s(e,t,r)},f=function(e,t,o){var r=function(n){if(t.test(e.readyState))return u(e,"readystatechange",r),o(n)};s(e,"readystatechange",r)},p=function(e){return function(t,o,r){var n=e.createElement(t);if(o)for(var a in o){var i=o[a];null!=i&&(null!=n[a]?n[a]=i:n.setAttribute(a,i))}if(r)for(var l=0,c=r.length;l<c;l++){var d=r[l];n.appendChild("string"==typeof d?e.createTextNode(d):d)}return n}},g=p(e),b=function(e){var t;return function(){t||(t=1,e.apply(this,arguments))}},m="body{margin:0}a{color:#24292e;text-decoration:none;outline:0}.octicon{display:inline-block;vertical-align:text-top;fill:currentColor}.widget{ display:inline-block;overflow:hidden;font-family:-apple-system, BlinkMacSystemFont, \"Segoe UI\", Helvetica, Arial, sans-serif;font-size:0;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn,.social-count{display:inline-block;height:14px;padding:2px 5px;font-size:11px;font-weight:600;line-height:14px;vertical-align:bottom;cursor:pointer;border:1px solid #c5c9cc;border-radius:0.25em}.btn{background-color:#eff3f6;background-image:-webkit-linear-gradient(top, #fafbfc, #eff3f6 90%);background-image:-moz-linear-gradient(top, #fafbfc, #eff3f6 90%);background-image:linear-gradient(180deg, #fafbfc, #eff3f6 90%);background-position:-1px -1px;background-repeat:repeat-x;background-size:110% 110%;border-color:rgba(27,31,35,0.2);-ms-filter:\"progid:DXImageTransform.Microsoft.Gradient(startColorstr='#FFFAFBFC', endColorstr='#FFEEF2F5')\";*filter:progid:DXImageTransform.Microsoft.Gradient(startColorstr='#FFFAFBFC', endColorstr='#FFEEF2F5')}.btn:active{background-color:#e9ecef;background-image:none;border-color:#a5a9ac;border-color:rgba(27,31,35,0.35);box-shadow:inset 0 0.15em 0.3em rgba(27,31,35,0.15)}.btn:focus,.btn:hover{background-color:#e6ebf1;background-image:-webkit-linear-gradient(top, #f0f3f6, #e6ebf1 90%);background-image:-moz-linear-gradient(top, #f0f3f6, #e6ebf1 90%);background-image:linear-gradient(180deg, #f0f3f6, #e6ebf1 90%);border-color:#a5a9ac;border-color:rgba(27,31,35,0.35);-ms-filter:\"progid:DXImageTransform.Microsoft.Gradient(startColorstr='#FFF0F3F6', endColorstr='#FFE5EAF0')\";*filter:progid:DXImageTransform.Microsoft.Gradient(startColorstr='#FFF0F3F6', endColorstr='#FFE5EAF0')}.social-count{position:relative;margin-left:5px;background-color:#fff}.social-count:focus,.social-count:hover{color:#0366d6}.social-count b,.social-count i{position:absolute;top:50%;left:0;display:block;width:0;height:0;margin:-4px 0 0 -4px;border:solid transparent;border-width:4px 4px 4px 0;_line-height:0;_border-top-color:red !important;_border-bottom-color:red !important;_border-left-color:red !important;_filter:chroma(color=red)}.social-count b{border-right-color:#c5c9cc}.social-count i{margin-left:-3px;border-right-color:#fff}.lg .btn,.lg .social-count{height:16px;padding:5px 10px;font-size:12px;line-height:16px}.lg .social-count{margin-left:6px}.lg .social-count b,.lg .social-count i{margin:-5px 0 0 -5px;border-width:5px 5px 5px 0}.lg .social-count i{margin-left:-4px}\n",v={"mark-github":{width:16,height:16,path:'<path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/>'},eye:{width:16,height:16,path:'<path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/>'},star:{width:14,height:16,path:'<path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/>'},"repo-forked":{width:10,height:16,path:'<path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/>'},"issue-opened":{width:14,height:16,path:'<path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/>'},"cloud-download":{width:16,height:16,path:'<path fill-rule="evenodd" d="M9 12h2l-3 3-3-3h2V7h2v5zm3-8c0-.44-.91-3-4.5-3C5.08 1 3 2.92 3 5 1.02 5 0 6.52 0 8c0 1.53 1 3 3 3h3V9.7H3C1.38 9.7 1.3 8.28 1.3 8c0-.17.05-1.7 1.7-1.7h1.3V5c0-1.39 1.56-2.7 3.2-2.7 2.55 0 3.13 1.55 3.2 1.8v1.2H12c.81 0 2.7.22 2.7 2.2 0 2.09-2.25 2.2-2.7 2.2h-2V11h2c2.08 0 4-1.16 4-3.5C16 5.06 14.08 4 12 4z"/>'}},w={},x=function(e,t,o){var r=p(e.ownerDocument),n=e.appendChild(r("style",{type:"text/css"}));n.styleSheet?n.styleSheet.cssText=m:n.appendChild(e.ownerDocument.createTextNode(m));var a,l,d=r("a",{className:"btn",href:t.href,target:"_blank",innerHTML:(a=t["data-icon"],l=/^large$/i.test(t["data-size"])?16:14,a=(""+a).toLowerCase().replace(/^octicon-/,""),{}.hasOwnProperty.call(v,a)||(a="mark-github"),'<svg version="1.1" width="'+l*v[a].width/v[a].height+'" height="'+l+'" viewBox="0 0 '+v[a].width+" "+v[a].height+'" class="octicon octicon-'+a+'" aria-hidden="true">'+v[a].path+"</svg>"),"aria-label":t["aria-label"]||void 0},[" ",r("span",{},[t["data-text"]||""])]);/\.github\.com$/.test("."+d.hostname)?/^https?:\/\/((gist\.)?github\.com\/[^\/?#]+\/[^\/?#]+\/archive\/|github\.com\/[^\/?#]+\/[^\/?#]+\/releases\/download\/|codeload\.github\.com\/)/.test(d.href)&&(d.target="_top"):(d.href="#",d.target="_self");var u,h,g,x,y=e.appendChild(r("div",{className:"widget"+(/^large$/i.test(t["data-size"])?" lg":"")},[d]));/^(true|1)$/i.test(t["data-show-count"])&&"github.com"===d.hostname&&(u=d.pathname.replace(/^(?!\/)/,"/").match(/^\/([^\/?#]+)(?:\/([^\/?#]+)(?:\/(?:(subscription)|(fork)|(issues)|([^\/?#]+)))?)?(?:[\/?#]|$)/))&&!u[6]?(u[2]?(h="/repos/"+u[1]+"/"+u[2],u[3]?(x="subscribers_count",g="watchers"):u[4]?(x="forks_count",g="network"):u[5]?(x="open_issues_count",g="issues"):(x="stargazers_count",g="stargazers")):(h="/users/"+u[1],g=x="followers"),function(e,t){var o=w[e]||(w[e]=[]);if(!(o.push(t)>1)){var r=b(function(){for(delete w[e];t=o.shift();)t.apply(null,arguments)});if(c){var n=new i;s(n,"abort",r),s(n,"error",r),s(n,"load",function(){var e;try{e=JSON.parse(n.responseText)}catch(e){return void r(e)}r(200!==n.status,e)}),n.open("GET",e),n.send()}else{var a=this||window;a._=function(e){a._=null,r(200!==e.meta.status,e.data)};var l=p(a.document)("script",{async:!0,src:e+(/\?/.test(e)?"&":"?")+"callback=_"}),d=function(){a._&&a._({meta:{}})};s(l,"load",d),s(l,"error",d),l.readyState&&f(l,/de|m/,d),a.document.getElementsByTagName("head")[0].appendChild(l)}}}.call(this,"https://api.github.com"+h,function(e,t){if(!e){var n=t[x];y.appendChild(r("a",{className:"social-count",href:t.html_url+"/"+g,target:"_blank","aria-label":n+" "+x.replace(/_count$/,"").replace("_"," ").slice(0,n<2?-1:void 0)+" on GitHub"},[r("b"),r("i"),r("span",{},[(""+n).replace(/\B(?=(\d{3})+(?!\d))/g,",")])]))}o&&o(y)})):o&&o(y)},y=window.devicePixelRatio||1,C=function(e){return(y>1?n.ceil(n.round(e*y)/y*2)/2:n.ceil(e))||0},F=function(e,t){e.style.width=t[0]+"px",e.style.height=t[1]+"px"},k=function(t,r){if(null!=t&&null!=r)if(t.getAttribute&&(t=function(e){for(var t={href:e.href,title:e.title,"aria-label":e.getAttribute("aria-label")},o=["icon","text","size","show-count"],r=0,n=o.length;r<n;r++){var a="data-"+o[r];t[a]=e.getAttribute(a)}return null==t["data-text"]&&(t["data-text"]=e.textContent||e.innerText),t}(t)),d){var a=g("span",{title:t.title||void 0});x(a.attachShadow({mode:"closed"}),t,function(){r(a)})}else{var i=g("iframe",{src:"javascript:0",title:t.title||void 0,allowtransparency:!0,scrolling:"no",frameBorder:0});F(i,[0,0]),i.style.border="none";var c=function(){var a,d=i.contentWindow;try{a=d.document.body}catch(t){return void e.body.appendChild(i.parentNode.removeChild(i))}u(i,"load",c),x.call(d,a,t,function(e){var a=function(e){var t=e.offsetWidth,o=e.offsetHeight;if(e.getBoundingClientRect){var r=e.getBoundingClientRect();t=n.max(t,C(r.width)),o=n.max(o,C(r.height))}return[t,o]}(e);i.parentNode.removeChild(i),h(i,"load",function(){F(i,a)}),i.src=l+"#"+(i.name=function(e){var t=[];for(var r in e){var n=e[r];null!=n&&t.push(o(r)+"="+o(n))}return t.join("&")}(t)),r(i)})};s(i,"load",c),e.body.appendChild(i)}};t.protocol+"//"+t.host+t.pathname===l?x(e.body,function(e){for(var t={},o=e.split("&"),n=0,a=o.length;n<a;n++){var i=o[n];if(""!==i){var l=i.split("=");t[r(l[0])]=null!=l[1]?r(l.slice(1).join("=")):void 0}}return t}(window.name||t.hash.replace(/^#/,""))):function(t){if(/m/.test(e.readyState)||!/g/.test(e.readyState)&&!e.documentElement.doScroll)setTimeout(t);else if(e.addEventListener){var o=b(t);h(e,"DOMContentLoaded",o),h(window,"load",o)}else f(e,/m/,t)}(function(){for(var t=e.querySelectorAll?e.querySelectorAll("a.github-button"):function(){for(var t=[],o=e.getElementsByTagName("a"),r=0,n=o.length;r<n;r++)~(" "+o[r].className+" ").replace(/[ \t\n\f\r]+/g," ").indexOf(" github-button ")&&t.push(o[r]);return t}(),o=0,r=t.length;o<r;o++)!function(e){k(e,function(t){e.parentNode.replaceChild(t,e)})}(t[o])})};
|
70 |
-
|
71 |
-
|
72 |
-
function onLoad() {
|
73 |
-
addIcon();
|
74 |
-
addCustomFooter();
|
75 |
-
addGithubButton();
|
76 |
-
parseGithubButtons();
|
77 |
-
}
|
78 |
-
|
79 |
-
window.addEventListener("load", onLoad);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/transformers/docs/source/_static/js/huggingface_logo.svg
DELETED
server/transformers/docs/source/benchmarks.md
DELETED
@@ -1,54 +0,0 @@
|
|
1 |
-
# Benchmarks
|
2 |
-
|
3 |
-
This section is dedicated to the Benchmarks done by the library, both by maintainers, contributors and users. These
|
4 |
-
benchmark will help keep track of the preformance improvements that are brought to our models across versions.
|
5 |
-
|
6 |
-
## Benchmarking all models for inference
|
7 |
-
|
8 |
-
As of version 2.1 we have benchmarked all models for inference, across many different settings: using PyTorch, with
|
9 |
-
and without TorchScript, using TensorFlow, with and without XLA. All of those tests were done across CPUs (except for
|
10 |
-
TensorFlow XLA) and GPUs.
|
11 |
-
|
12 |
-
The approach is detailed in the [following blogpost](https://medium.com/huggingface/benchmarking-transformers-pytorch-and-tensorflow-e2917fb891c2)
|
13 |
-
|
14 |
-
The results are available [here](https://docs.google.com/spreadsheets/d/1sryqufw2D0XlUH4sq3e9Wnxu5EAQkaohzrJbd5HdQ_w/edit?usp=sharing).
|
15 |
-
|
16 |
-
## TF2 with mixed precision, XLA, Distribution (@tlkh)
|
17 |
-
|
18 |
-
This work was done by [Timothy Liu](https://github.com/tlkh).
|
19 |
-
|
20 |
-
There are very positive results to be gained from the various TensorFlow 2.0 features:
|
21 |
-
|
22 |
-
- Automatic Mixed Precision (AMP)
|
23 |
-
- XLA compiler
|
24 |
-
- Distribution strategies (multi-GPU)
|
25 |
-
|
26 |
-
The benefits are listed here (tested on CoLA, MRPC, SST-2):
|
27 |
-
|
28 |
-
- AMP: Between 1.4x to 1.6x decrease in overall time without change in batch size
|
29 |
-
- AMP+XLA: Up to 2.5x decrease in overall time on SST-2 (larger dataset)
|
30 |
-
- Distribution: Between 1.4x to 3.4x decrease in overall time on 4xV100
|
31 |
-
- Combined: Up to 5.7x decrease in overall training time, or 9.1x training throughput
|
32 |
-
|
33 |
-
The model quality (measured by the validation accuracy) fluctuates slightly. Taking an average of 4 training runs
|
34 |
-
on a single GPU gives the following results:
|
35 |
-
|
36 |
-
- CoLA: AMP results in slighter lower acc (0.820 vs 0.824)
|
37 |
-
- MRPC: AMP results in lower acc (0.823 vs 0.835)
|
38 |
-
- SST-2: AMP results in slighter lower acc (0.918 vs 0.922)
|
39 |
-
|
40 |
-
However, in a distributed setting with 4xV100 (4x batch size), AMP can yield in better results:
|
41 |
-
|
42 |
-
CoLA: AMP results in higher acc (0.828 vs 0.812)
|
43 |
-
MRPC: AMP results in lower acc (0.817 vs 0.827)
|
44 |
-
SST-2: AMP results in slightly lower acc (0.926 vs 0.929)
|
45 |
-
|
46 |
-
The benchmark script is available [here](https://github.com/NVAITC/benchmarking/blob/master/tf2/bert_dist.py).
|
47 |
-
|
48 |
-
Note: on some tasks (e.g. MRPC), the dataset is too small. The overhead due to the model compilation with XLA as well
|
49 |
-
as the distribution strategy setup does not speed things up. The XLA compile time is also the reason why although throughput
|
50 |
-
can increase a lot (e.g. 2.7x for single GPU), overall (end-to-end) training speed-up is not as fast (as low as 1.4x)
|
51 |
-
|
52 |
-
The benefits as seen on SST-2 (larger dataset) is much clear.
|
53 |
-
|
54 |
-
All results can be seen on this [Google Sheet](https://docs.google.com/spreadsheets/d/1538MN224EzjbRL239sqSiUy6YY-rAjHyXhTzz_Zptls/edit#gid=960868445).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|