algorithmexplorer01 commited on
Commit
6f38d12
1 Parent(s): faacacf

Upload 9 files

Browse files
Files changed (9) hide show
  1. LICENSE +201 -0
  2. README.md +3 -1
  3. config.json +33 -0
  4. configuration_bert.py +134 -0
  5. gitattributes +35 -0
  6. modeling_bert.py +1024 -0
  7. tokenizer.json +0 -0
  8. tokenizer_config.json +3 -0
  9. vocab.txt +0 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 OctopusMind Authors. All rights reserved.
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.
README.md CHANGED
@@ -1,3 +1,5 @@
1
  ---
2
  license: apache-2.0
3
- ---
 
 
 
1
  ---
2
  license: apache-2.0
3
+ language:
4
+ - zh
5
+ ---
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "OctopusMind/longbert-8k-zh",
3
+ "architectures": [
4
+ "LongBertModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "OctopusMind/longbert-8k-zh--configuration_bert.LongBertConfig",
8
+ "AutoModel": "OctopusMind/longbert-8k-zh--modeling_bert.LongBertModel"
9
+ },
10
+ "attention_probs_dropout_prob": 0.1,
11
+ "directionality": "bidi",
12
+ "hidden_act": "gelu",
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 768,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 3072,
17
+ "layer_norm_eps": 1e-12,
18
+ "max_position_embeddings": 8192,
19
+ "model_type": "bert",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "pad_token_id": 0,
23
+ "pooler_fc_size": 768,
24
+ "pooler_num_attention_heads": 12,
25
+ "pooler_num_fc_layers": 3,
26
+ "pooler_size_per_head": 128,
27
+ "pooler_type": "first_token_transform",
28
+ "position_embedding_type": "alibi",
29
+ "torch_dtype": "float32",
30
+ "use_cache": true,
31
+ "vocab_size": 21128,
32
+ "emb_pooler": "mean"
33
+ }
configuration_bert.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ # Copyright (c) 2023 octopus mind. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ BERT model configuration"""
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class LongBertConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`LongBertModel`]. It is used to
28
+ instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the BERT
30
+ [bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 30522):
38
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
40
+ hidden_size (`int`, *optional*, defaults to 768):
41
+ Dimensionality of the encoder layers and the pooler layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 12):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 12):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ intermediate_size (`int`, *optional*, defaults to 3072):
47
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
48
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
51
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
52
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
53
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
54
+ The dropout ratio for the attention probabilities.
55
+ max_position_embeddings (`int`, *optional*, defaults to 512):
56
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
57
+ just in case (e.g., 512 or 1024 or 2048).
58
+ type_vocab_size (`int`, *optional*, defaults to 2):
59
+ The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
63
+ The epsilon used by the layer normalization layers.
64
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
65
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
66
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
67
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
68
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
69
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
70
+ is_decoder (`bool`, *optional*, defaults to `False`):
71
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`.
75
+ classifier_dropout (`float`, *optional*):
76
+ The dropout ratio for the classification head.
77
+ feed_forward_type (`str`, *optional*, defaults to `"original"`):
78
+ The type of feed forward layer to use in the bert layers.
79
+ Can be one of GLU variants, e.g. `"reglu"`, `"geglu"`
80
+ emb_pooler (`str`, *optional*, defaults to `None`):
81
+ The function to use for pooling the last layer embeddings to get the sentence embeddings.
82
+ Should be one of `None`, `"mean"`.
83
+ attn_implementation (`str`, *optional*, defaults to `"torch"`):
84
+ The implementation of the self-attention layer. Can be one of:
85
+ - `None` for the original implementation,
86
+ - `torch` for the PyTorch SDPA implementation,
87
+
88
+ """
89
+ model_type = "bert"
90
+
91
+ def __init__(
92
+ self,
93
+ vocab_size=21128,
94
+ hidden_size=768,
95
+ num_hidden_layers=12,
96
+ num_attention_heads=12,
97
+ intermediate_size=3072,
98
+ hidden_act="gelu",
99
+ hidden_dropout_prob=0.1,
100
+ attention_probs_dropout_prob=0.1,
101
+ max_position_embeddings=8192,
102
+ type_vocab_size=2,
103
+ initializer_range=0.02,
104
+ layer_norm_eps=1e-12,
105
+ pad_token_id=0,
106
+ position_embedding_type="absolute",
107
+ use_cache=True,
108
+ classifier_dropout=None,
109
+ feed_forward_type="original",
110
+ emb_pooler=None,
111
+ attn_implementation='torch',
112
+ **kwargs,
113
+ ):
114
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
115
+
116
+ self.vocab_size = vocab_size
117
+ self.hidden_size = hidden_size
118
+ self.num_hidden_layers = num_hidden_layers
119
+ self.num_attention_heads = num_attention_heads
120
+ self.hidden_act = hidden_act
121
+ self.intermediate_size = intermediate_size
122
+ self.hidden_dropout_prob = hidden_dropout_prob
123
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
124
+ self.max_position_embeddings = max_position_embeddings
125
+ self.type_vocab_size = type_vocab_size
126
+ self.initializer_range = initializer_range
127
+ self.layer_norm_eps = layer_norm_eps
128
+ self.position_embedding_type = position_embedding_type
129
+ self.use_cache = use_cache
130
+ self.classifier_dropout = classifier_dropout
131
+ self.feed_forward_type = feed_forward_type
132
+ self.emb_pooler = emb_pooler
133
+ self.attn_implementation = attn_implementation
134
+
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
modeling_bert.py ADDED
@@ -0,0 +1,1024 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License
13
+ import math
14
+ import os
15
+ import numpy as np
16
+ import warnings
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+ from transformers import AutoTokenizer
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.modeling_outputs import (
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ BaseModelOutputWithPoolingAndCrossAttentions
28
+ )
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
31
+ from transformers.utils import (
32
+ ModelOutput,
33
+ logging)
34
+ from .configuration_bert import LongBertConfig
35
+
36
+ try:
37
+ from torch.nn.functional import scaled_dot_product_attention
38
+ except ImportError:
39
+ scaled_dot_product_attention = None
40
+ logger = logging.get_logger(__name__)
41
+
42
+ try:
43
+ from tqdm.autonotebook import trange
44
+
45
+ has_tqdm = True
46
+ except ImportError:
47
+ has_tqdm = False
48
+
49
+
50
+ def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
51
+ """Load tf checkpoints in a pytorch model."""
52
+ try:
53
+ import re
54
+
55
+ import numpy as np
56
+ import tensorflow as tf
57
+ except ImportError:
58
+ logger.error(
59
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
60
+ "https://www.tensorflow.org/install/ for installation instructions."
61
+ )
62
+ raise
63
+ tf_path = os.path.abspath(tf_checkpoint_path)
64
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
65
+ # Load weights from TF model
66
+ init_vars = tf.train.list_variables(tf_path)
67
+ names = []
68
+ arrays = []
69
+ for name, shape in init_vars:
70
+ logger.info(f"Loading TF weight {name} with shape {shape}")
71
+ array = tf.train.load_variable(tf_path, name)
72
+ names.append(name)
73
+ arrays.append(array)
74
+
75
+ for name, array in zip(names, arrays):
76
+ name = name.split("/")
77
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
78
+ # which are not required for using pretrained model
79
+ if any(
80
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
81
+ for n in name
82
+ ):
83
+ logger.info(f"Skipping {'/'.join(name)}")
84
+ continue
85
+ pointer = model
86
+ for m_name in name:
87
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
88
+ scope_names = re.split(r"_(\d+)", m_name)
89
+ else:
90
+ scope_names = [m_name]
91
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
92
+ pointer = getattr(pointer, "weight")
93
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
94
+ pointer = getattr(pointer, "bias")
95
+ elif scope_names[0] == "output_weights":
96
+ pointer = getattr(pointer, "weight")
97
+ elif scope_names[0] == "squad":
98
+ pointer = getattr(pointer, "classifier")
99
+ else:
100
+ try:
101
+ pointer = getattr(pointer, scope_names[0])
102
+ except AttributeError:
103
+ logger.info(f"Skipping {'/'.join(name)}")
104
+ continue
105
+ if len(scope_names) >= 2:
106
+ num = int(scope_names[1])
107
+ pointer = pointer[num]
108
+ if m_name[-11:] == "_embeddings":
109
+ pointer = getattr(pointer, "weight")
110
+ elif m_name == "kernel":
111
+ array = np.transpose(array)
112
+ try:
113
+ if pointer.shape != array.shape:
114
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
115
+ except AssertionError as e:
116
+ e.args += (pointer.shape, array.shape)
117
+ raise
118
+ logger.info(f"Initialize PyTorch weight {name}")
119
+ pointer.data = torch.from_numpy(array)
120
+ return model
121
+
122
+
123
+ class LongBertEmbeddings(nn.Module):
124
+ """Construct the embeddings from word, position and token_type embeddings."""
125
+
126
+ def __init__(self, config):
127
+ super().__init__()
128
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
129
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
130
+
131
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
132
+ # any TensorFlow checkpoint file
133
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
134
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
135
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
136
+
137
+ def forward(
138
+ self,
139
+ input_ids: Optional[torch.LongTensor] = None,
140
+ token_type_ids: Optional[torch.LongTensor] = None,
141
+ inputs_embeds: Optional[torch.FloatTensor] = None
142
+ ) -> torch.Tensor:
143
+ if input_ids is not None:
144
+ input_shape = input_ids.size()
145
+ else:
146
+ input_shape = inputs_embeds.size()[:-1]
147
+
148
+ seq_length = input_shape[1]
149
+
150
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
151
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
152
+ # issue #5664
153
+ if token_type_ids is None:
154
+ if hasattr(self, "token_type_ids"):
155
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
156
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
157
+ token_type_ids = buffered_token_type_ids_expanded
158
+ else:
159
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
160
+
161
+ if inputs_embeds is None:
162
+ inputs_embeds = self.word_embeddings(input_ids)
163
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
164
+
165
+ embeddings = inputs_embeds + token_type_embeddings
166
+ embeddings = self.LayerNorm(embeddings)
167
+ embeddings = self.dropout(embeddings)
168
+ return embeddings
169
+
170
+
171
+ class LongBertSelfAttention(nn.Module):
172
+ def __init__(self, config, position_embedding_type=None):
173
+ super().__init__()
174
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
175
+ raise ValueError(
176
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
177
+ f"heads ({config.num_attention_heads})"
178
+ )
179
+
180
+ self.num_attention_heads = config.num_attention_heads
181
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
182
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
183
+
184
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
185
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
186
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
187
+
188
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
189
+ self.position_embedding_type = position_embedding_type or getattr(
190
+ config, "position_embedding_type", "alibi"
191
+ )
192
+ self.is_decoder = config.is_decoder
193
+
194
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
195
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
196
+ x = x.view(new_x_shape)
197
+ return x.permute(0, 2, 1, 3)
198
+
199
+ def forward(
200
+ self,
201
+ hidden_states: torch.Tensor,
202
+ attention_mask: Optional[torch.FloatTensor] = None,
203
+ head_mask: Optional[torch.FloatTensor] = None,
204
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
205
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
206
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
207
+ output_attentions: Optional[bool] = False,
208
+ bias: Optional[torch.FloatTensor] = None,
209
+ ) -> Tuple[torch.Tensor]:
210
+ mixed_query_layer = self.query(hidden_states)
211
+
212
+ # If this is instantiated as a cross-attention module, the keys
213
+ # and values come from an encoder; the attention mask needs to be
214
+ # such that the encoder's padding tokens are not attended to.
215
+ is_cross_attention = encoder_hidden_states is not None
216
+
217
+ if is_cross_attention and past_key_value is not None:
218
+ # reuse k,v, cross_attentions
219
+ key_layer = past_key_value[0]
220
+ value_layer = past_key_value[1]
221
+ attention_mask = encoder_attention_mask
222
+ elif is_cross_attention:
223
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
224
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
225
+ attention_mask = encoder_attention_mask
226
+ elif past_key_value is not None:
227
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
228
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
229
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
230
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
231
+ else:
232
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
233
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
234
+
235
+ query_layer = self.transpose_for_scores(mixed_query_layer)
236
+
237
+ use_cache = past_key_value is not None
238
+ if self.is_decoder:
239
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
240
+ # Further calls to cross_attention layer can then reuse all cross-attention
241
+ # key/value_states (first "if" case)
242
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
243
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
244
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
245
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
246
+ past_key_value = (key_layer, value_layer)
247
+
248
+ # Take the dot product between "query" and "key" to get the raw attention scores.
249
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
250
+
251
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
252
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
253
+ if use_cache:
254
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
255
+ -1, 1
256
+ )
257
+ else:
258
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
259
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
260
+ distance = position_ids_l - position_ids_r
261
+
262
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
263
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
264
+
265
+ if self.position_embedding_type == "relative_key":
266
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
267
+ attention_scores = attention_scores + relative_position_scores
268
+ elif self.position_embedding_type == "relative_key_query":
269
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
270
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
271
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
272
+
273
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
274
+ if attention_mask is not None:
275
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
276
+ attention_scores = attention_scores + attention_mask
277
+
278
+ # Normalize the attention scores to probabilities.
279
+ attention_probs = nn.functional.softmax(attention_scores + bias, dim=-1)
280
+
281
+ # This is actually dropping out entire tokens to attend to, which might
282
+ # seem a bit unusual, but is taken from the original Transformer paper.
283
+ attention_probs = self.dropout(attention_probs)
284
+
285
+ # Mask heads if we want to
286
+ if head_mask is not None:
287
+ attention_probs = attention_probs * head_mask
288
+
289
+ context_layer = torch.matmul(attention_probs, value_layer)
290
+
291
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
292
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
293
+ context_layer = context_layer.view(new_context_layer_shape)
294
+
295
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
296
+
297
+ if self.is_decoder:
298
+ outputs = outputs + (past_key_value,)
299
+ return outputs
300
+
301
+
302
+ class LongBertSelfOutput(nn.Module):
303
+ def __init__(self, config):
304
+ super().__init__()
305
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
306
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
307
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
308
+
309
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
310
+ hidden_states = self.dense(hidden_states)
311
+ hidden_states = self.dropout(hidden_states)
312
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
313
+ return hidden_states
314
+
315
+
316
+ class LongBertAttention(nn.Module):
317
+ def __init__(self, config, position_embedding_type=None):
318
+ super().__init__()
319
+ self.self = LongBertSelfAttention(config, position_embedding_type=position_embedding_type)
320
+ self.output = LongBertSelfOutput(config)
321
+ self.pruned_heads = set()
322
+
323
+ def prune_heads(self, heads):
324
+ if len(heads) == 0:
325
+ return
326
+ heads, index = find_pruneable_heads_and_indices(
327
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
328
+ )
329
+
330
+ # Prune linear layers
331
+ self.self.query = prune_linear_layer(self.self.query, index)
332
+ self.self.key = prune_linear_layer(self.self.key, index)
333
+ self.self.value = prune_linear_layer(self.self.value, index)
334
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
335
+
336
+ # Update hyper params and store pruned heads
337
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
338
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
339
+ self.pruned_heads = self.pruned_heads.union(heads)
340
+
341
+ def forward(
342
+ self,
343
+ hidden_states: torch.Tensor,
344
+ attention_mask: Optional[torch.FloatTensor] = None,
345
+ head_mask: Optional[torch.FloatTensor] = None,
346
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
347
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
348
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
349
+ output_attentions: Optional[bool] = False,
350
+ bias: Optional[torch.FloatTensor] = None,
351
+ ) -> Tuple[torch.Tensor]:
352
+ self_outputs = self.self(
353
+ hidden_states,
354
+ attention_mask,
355
+ head_mask,
356
+ encoder_hidden_states,
357
+ encoder_attention_mask,
358
+ past_key_value,
359
+ output_attentions,
360
+ bias,
361
+ )
362
+ attention_output = self.output(self_outputs[0], hidden_states)
363
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
364
+ return outputs
365
+
366
+
367
+ class LongBertIntermediate(nn.Module):
368
+ def __init__(self, config):
369
+ super().__init__()
370
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
371
+ if isinstance(config.hidden_act, str):
372
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
373
+ else:
374
+ self.intermediate_act_fn = config.hidden_act
375
+
376
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
377
+ hidden_states = self.dense(hidden_states)
378
+ hidden_states = self.intermediate_act_fn(hidden_states)
379
+ return hidden_states
380
+
381
+
382
+ class LongBertOutput(nn.Module):
383
+ def __init__(self, config):
384
+ super().__init__()
385
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
386
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
387
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
388
+
389
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
390
+ hidden_states = self.dense(hidden_states)
391
+ hidden_states = self.dropout(hidden_states)
392
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
393
+ return hidden_states
394
+
395
+
396
+ class LongBertLayer(nn.Module):
397
+ def __init__(self, config):
398
+ super().__init__()
399
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
400
+ self.seq_len_dim = 1
401
+ self.attention = LongBertAttention(config)
402
+ self.is_decoder = config.is_decoder
403
+ self.add_cross_attention = config.add_cross_attention
404
+ if self.add_cross_attention:
405
+ if not self.is_decoder:
406
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
407
+ self.crossattention = LongBertAttention(config, position_embedding_type="absolute")
408
+ self.intermediate = LongBertIntermediate(config)
409
+ self.output = LongBertOutput(config)
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.FloatTensor] = None,
415
+ head_mask: Optional[torch.FloatTensor] = None,
416
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
417
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
418
+ bias: Optional[torch.FloatTensor] = None,
419
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
420
+ output_attentions: Optional[bool] = False,
421
+ ) -> Tuple[torch.Tensor]:
422
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
423
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
424
+ self_attention_outputs = self.attention(
425
+ hidden_states,
426
+ attention_mask,
427
+ head_mask,
428
+ output_attentions=output_attentions,
429
+ past_key_value=self_attn_past_key_value,
430
+ bias=bias,
431
+ )
432
+ attention_output = self_attention_outputs[0]
433
+
434
+ # if decoder, the last output is tuple of self-attn cache
435
+ if self.is_decoder:
436
+ outputs = self_attention_outputs[1:-1]
437
+ present_key_value = self_attention_outputs[-1]
438
+ else:
439
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
440
+
441
+ cross_attn_present_key_value = None
442
+ if self.is_decoder and encoder_hidden_states is not None:
443
+ if not hasattr(self, "crossattention"):
444
+ raise ValueError(
445
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
446
+ " by setting `config.add_cross_attention=True`"
447
+ )
448
+
449
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
450
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
451
+ cross_attention_outputs = self.crossattention(
452
+ attention_output,
453
+ attention_mask,
454
+ head_mask,
455
+ encoder_hidden_states,
456
+ encoder_attention_mask,
457
+ cross_attn_past_key_value,
458
+ output_attentions,
459
+ )
460
+ attention_output = cross_attention_outputs[0]
461
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
462
+
463
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
464
+ cross_attn_present_key_value = cross_attention_outputs[-1]
465
+ present_key_value = present_key_value + cross_attn_present_key_value
466
+
467
+ layer_output = apply_chunking_to_forward(
468
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
469
+ )
470
+ outputs = (layer_output,) + outputs
471
+
472
+ # if decoder, return the attn key/values as the last output
473
+ if self.is_decoder:
474
+ outputs = outputs + (present_key_value,)
475
+
476
+ return outputs
477
+
478
+ def feed_forward_chunk(self, attention_output):
479
+ intermediate_output = self.intermediate(attention_output)
480
+ layer_output = self.output(intermediate_output, attention_output)
481
+ return layer_output
482
+
483
+
484
+ class LongBertEncoder(nn.Module):
485
+ def __init__(self, config):
486
+ super().__init__()
487
+ self.config = config
488
+ self.layer = nn.ModuleList([LongBertLayer(config) for _ in range(config.num_hidden_layers)])
489
+ self.gradient_checkpointing = False
490
+ self.num_attention_heads = config.num_attention_heads
491
+ self.register_buffer(
492
+ "alibi",
493
+ self.rebuild_alibi_tensor(size=config.max_position_embeddings),
494
+ persistent=False,
495
+ )
496
+
497
+ def rebuild_alibi_tensor(
498
+ self, size: int, device: Optional[Union[torch.device, str]] = None
499
+ ):
500
+ # Alibi
501
+ # Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
502
+ # In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
503
+ # of the logits, which makes the math work out *after* applying causal masking. If no causal masking
504
+ # will be applied, it is necessary to construct the diagonal mask.
505
+ n_heads = self.num_attention_heads
506
+
507
+ def _get_alibi_head_slopes(n_heads: int) -> List[float]:
508
+ def get_slopes_power_of_2(n):
509
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
510
+ ratio = start
511
+ return [start * ratio ** i for i in range(n)]
512
+
513
+ if math.log2(n_heads).is_integer():
514
+ return get_slopes_power_of_2(
515
+ n_heads
516
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
517
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
518
+ closest_power_of_2 = 2 ** math.floor(
519
+ math.log2(n_heads)
520
+ ) # when the number of heads is not a power of 2, we use this workaround.
521
+ return (
522
+ get_slopes_power_of_2(closest_power_of_2)
523
+ + _get_alibi_head_slopes(2 * closest_power_of_2)[0::2][
524
+ : n_heads - closest_power_of_2
525
+ ]
526
+ )
527
+
528
+ context_position = torch.arange(size, device=device)[:, None]
529
+ memory_position = torch.arange(size, device=device)[None, :]
530
+ relative_position = torch.abs(memory_position - context_position)
531
+ # [n_heads, max_token_length, max_token_length]
532
+ relative_position = relative_position.unsqueeze(0).expand(n_heads, -1, -1)
533
+ slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device) * -1
534
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * relative_position
535
+ # [1, n_heads, max_token_length, max_token_length]
536
+ alibi = alibi.unsqueeze(0)
537
+ assert alibi.shape == torch.Size([1, n_heads, size, size])
538
+
539
+ self._current_alibi_size = size
540
+ return alibi
541
+
542
+ def forward(
543
+ self,
544
+ hidden_states: torch.Tensor,
545
+ attention_mask: Optional[torch.FloatTensor] = None,
546
+ head_mask: Optional[torch.FloatTensor] = None,
547
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
548
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
549
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
550
+ use_cache: Optional[bool] = None,
551
+ output_attentions: Optional[bool] = False,
552
+ output_hidden_states: Optional[bool] = False,
553
+ return_dict: Optional[bool] = True,
554
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
555
+ all_hidden_states = () if output_hidden_states else None
556
+ all_self_attentions = () if output_attentions else None
557
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
558
+ # Add alibi matrix to extended_attention_mask
559
+ _, seqlen, _ = hidden_states.size()
560
+ if self._current_alibi_size < seqlen:
561
+ # Rebuild the alibi tensor when needed
562
+ warnings.warn(
563
+ f'Increasing alibi size from {self._current_alibi_size} to {seqlen}.'
564
+ )
565
+ self.register_buffer(
566
+ "alibi",
567
+ self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device).to(
568
+ hidden_states.dtype
569
+ ),
570
+ persistent=False,
571
+ )
572
+ elif self.alibi.device != hidden_states.device:
573
+ # Device catch-up
574
+ self.alibi = self.alibi.to(hidden_states.device)
575
+
576
+ alibi_bias = self.alibi[:, :, :seqlen, :seqlen]
577
+ if self.gradient_checkpointing and self.training:
578
+ if use_cache:
579
+ logger.warning_once(
580
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
581
+ )
582
+ use_cache = False
583
+
584
+ next_decoder_cache = () if use_cache else None
585
+ for i, layer_module in enumerate(self.layer):
586
+ if output_hidden_states:
587
+ all_hidden_states = all_hidden_states + (hidden_states,)
588
+
589
+ layer_head_mask = head_mask[i] if head_mask is not None else None
590
+ past_key_value = past_key_values[i] if past_key_values is not None else None
591
+
592
+ if self.gradient_checkpointing and self.training:
593
+
594
+ def create_custom_forward(module):
595
+ def custom_forward(*inputs):
596
+ return module(*inputs, past_key_value, output_attentions)
597
+
598
+ return custom_forward
599
+
600
+ layer_outputs = torch.utils.checkpoint.checkpoint(
601
+ create_custom_forward(layer_module),
602
+ hidden_states,
603
+ attention_mask,
604
+ layer_head_mask,
605
+ encoder_hidden_states,
606
+ encoder_attention_mask,
607
+ )
608
+ else:
609
+ layer_outputs = layer_module(
610
+ hidden_states,
611
+ attention_mask,
612
+ layer_head_mask,
613
+ encoder_hidden_states,
614
+ encoder_attention_mask,
615
+ alibi_bias,
616
+ past_key_value,
617
+ output_attentions,
618
+ )
619
+
620
+ hidden_states = layer_outputs[0]
621
+ if use_cache:
622
+ next_decoder_cache += (layer_outputs[-1],)
623
+ if output_attentions:
624
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
625
+ if self.config.add_cross_attention:
626
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
627
+
628
+ if output_hidden_states:
629
+ all_hidden_states = all_hidden_states + (hidden_states,)
630
+
631
+ if not return_dict:
632
+ return tuple(
633
+ v
634
+ for v in [
635
+ hidden_states,
636
+ next_decoder_cache,
637
+ all_hidden_states,
638
+ all_self_attentions,
639
+ all_cross_attentions,
640
+ ]
641
+ if v is not None
642
+ )
643
+ return BaseModelOutputWithPastAndCrossAttentions(
644
+ last_hidden_state=hidden_states,
645
+ past_key_values=next_decoder_cache,
646
+ hidden_states=all_hidden_states,
647
+ attentions=all_self_attentions,
648
+ cross_attentions=all_cross_attentions,
649
+ )
650
+
651
+
652
+ class LongBertPooler(nn.Module):
653
+ def __init__(self, config):
654
+ super().__init__()
655
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
656
+ self.activation = nn.Tanh()
657
+
658
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
659
+ # We "pool" the model by simply taking the hidden state corresponding
660
+ # to the first token.
661
+ first_token_tensor = hidden_states[:, 0]
662
+ pooled_output = self.dense(first_token_tensor)
663
+ pooled_output = self.activation(pooled_output)
664
+ return pooled_output
665
+
666
+
667
+ class LongBertPreTrainedModel(PreTrainedModel):
668
+ """
669
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
670
+ models.
671
+ """
672
+
673
+ config_class = LongBertConfig
674
+ load_tf_weights = load_tf_weights_in_bert
675
+ base_model_prefix = "bert"
676
+ supports_gradient_checkpointing = True
677
+
678
+ def _init_weights(self, module):
679
+ """Initialize the weights"""
680
+ if isinstance(module, nn.Linear):
681
+ # Slightly different from the TF version which uses truncated_normal for initialization
682
+ # cf https://github.com/pytorch/pytorch/pull/5617
683
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
684
+ if module.bias is not None:
685
+ module.bias.data.zero_()
686
+ elif isinstance(module, nn.Embedding):
687
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
688
+ if module.padding_idx is not None:
689
+ module.weight.data[module.padding_idx].zero_()
690
+ elif isinstance(module, nn.LayerNorm):
691
+ module.bias.data.zero_()
692
+ module.weight.data.fill_(1.0)
693
+
694
+ def _set_gradient_checkpointing(self, module, value=False):
695
+ if isinstance(module, LongBertEncoder):
696
+ module.gradient_checkpointing = value
697
+
698
+
699
+ @dataclass
700
+ class LongBertForPreTrainingOutput(ModelOutput):
701
+ """
702
+ Output type of [`BertForPreTraining`].
703
+
704
+ Args:
705
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
706
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
707
+ (classification) loss.
708
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
709
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
710
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
711
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
712
+ before SoftMax).
713
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
714
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
715
+ shape `(batch_size, sequence_length, hidden_size)`.
716
+
717
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
718
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
719
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
720
+ sequence_length)`.
721
+
722
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
723
+ heads.
724
+ """
725
+
726
+ loss: Optional[torch.FloatTensor] = None
727
+ prediction_logits: torch.FloatTensor = None
728
+ seq_relationship_logits: torch.FloatTensor = None
729
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
730
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
731
+
732
+
733
+ class LongBertModel(LongBertPreTrainedModel):
734
+ """
735
+
736
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
737
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
738
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
739
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
740
+
741
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
742
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
743
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
744
+ """
745
+
746
+ def __init__(self, config, add_pooling_layer=True):
747
+ super().__init__(config)
748
+ self.config = config
749
+ self.embeddings = LongBertEmbeddings(config)
750
+ self.encoder = LongBertEncoder(config)
751
+
752
+ self.pooler = LongBertPooler(config) if add_pooling_layer else None
753
+ self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path)
754
+ # Initialize weights and apply final processing
755
+ self.post_init()
756
+
757
+ def get_input_embeddings(self):
758
+ return self.embeddings.word_embeddings
759
+
760
+ def set_input_embeddings(self, value):
761
+ self.embeddings.word_embeddings = value
762
+
763
+ def _prune_heads(self, heads_to_prune):
764
+ """
765
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
766
+ class PreTrainedModel
767
+ """
768
+ for layer, heads in heads_to_prune.items():
769
+ self.encoder.layer[layer].attention.prune_heads(heads)
770
+
771
+ def forward(
772
+ self,
773
+ input_ids: Optional[torch.Tensor] = None,
774
+ attention_mask: Optional[torch.Tensor] = None,
775
+ token_type_ids: Optional[torch.Tensor] = None,
776
+ head_mask: Optional[torch.Tensor] = None,
777
+ inputs_embeds: Optional[torch.Tensor] = None,
778
+ encoder_hidden_states: Optional[torch.Tensor] = None,
779
+ encoder_attention_mask: Optional[torch.Tensor] = None,
780
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
781
+ use_cache: Optional[bool] = None,
782
+ output_attentions: Optional[bool] = None,
783
+ output_hidden_states: Optional[bool] = None,
784
+ return_dict: Optional[bool] = None,
785
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
786
+ r"""
787
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
788
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
789
+ the model is configured as a decoder.
790
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
791
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
792
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
793
+
794
+ - 1 for tokens that are **not masked**,
795
+ - 0 for tokens that are **masked**.
796
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
797
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
798
+
799
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
800
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
801
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
802
+ use_cache (`bool`, *optional*):
803
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
804
+ `past_key_values`).
805
+ """
806
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
807
+ output_hidden_states = (
808
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
809
+ )
810
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
811
+
812
+ if self.config.is_decoder:
813
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
814
+ else:
815
+ use_cache = False
816
+
817
+ if input_ids is not None and inputs_embeds is not None:
818
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
819
+ elif input_ids is not None:
820
+ input_shape = input_ids.size()
821
+ elif inputs_embeds is not None:
822
+ input_shape = inputs_embeds.size()[:-1]
823
+ else:
824
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
825
+
826
+ batch_size, seq_length = input_shape
827
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
828
+
829
+ # past_key_values_length
830
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
831
+
832
+ if attention_mask is None:
833
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
834
+
835
+ if token_type_ids is None:
836
+ if hasattr(self.embeddings, "token_type_ids"):
837
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
838
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
839
+ token_type_ids = buffered_token_type_ids_expanded
840
+ else:
841
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
842
+
843
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
844
+ # ourselves in which case we just need to make it broadcastable to all heads.
845
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
846
+
847
+ # If a 2D or 3D attention mask is provided for the cross-attention
848
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
849
+ if self.config.is_decoder and encoder_hidden_states is not None:
850
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
851
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
852
+ if encoder_attention_mask is None:
853
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
854
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
855
+ else:
856
+ encoder_extended_attention_mask = None
857
+
858
+ # Prepare head mask if needed
859
+ # 1.0 in head_mask indicate we keep the head
860
+ # attention_probs has shape bsz x n_heads x N x N
861
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
862
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
863
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
864
+
865
+ embedding_output = self.embeddings(
866
+ input_ids=input_ids,
867
+ token_type_ids=token_type_ids,
868
+ inputs_embeds=inputs_embeds
869
+ )
870
+ encoder_outputs = self.encoder(
871
+ embedding_output,
872
+ attention_mask=extended_attention_mask,
873
+ head_mask=head_mask,
874
+ encoder_hidden_states=encoder_hidden_states,
875
+ encoder_attention_mask=encoder_extended_attention_mask,
876
+ past_key_values=past_key_values,
877
+ use_cache=use_cache,
878
+ output_attentions=output_attentions,
879
+ output_hidden_states=output_hidden_states,
880
+ return_dict=return_dict,
881
+ )
882
+ sequence_output = encoder_outputs[0]
883
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
884
+
885
+ if not return_dict:
886
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
887
+
888
+ return BaseModelOutputWithPoolingAndCrossAttentions(
889
+ last_hidden_state=sequence_output,
890
+ pooler_output=pooled_output,
891
+ past_key_values=encoder_outputs.past_key_values,
892
+ hidden_states=encoder_outputs.hidden_states,
893
+ attentions=encoder_outputs.attentions,
894
+ cross_attentions=encoder_outputs.cross_attentions,
895
+ )
896
+
897
+ def encode(self,
898
+ sentences: Union[str, List[str]],
899
+ batch_size: int = 32,
900
+ show_progress_bar: Optional[bool] = None,
901
+ output_value: str = 'sentence_embedding',
902
+ convert_to_numpy: bool = True,
903
+ convert_to_tensor: bool = False,
904
+ device: Optional[torch.device] = "cpu",
905
+ normalize_embeddings: bool = False,
906
+ **tokenizer_kwargs,
907
+ ) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:
908
+ """
909
+ Computes sentence embeddings
910
+
911
+ Args:
912
+ sentences(`str` or `List[str]`):
913
+ Sentence or sentences to be encoded
914
+ batch_size(`int`, *optional*, defaults to 32):
915
+ Batch size for the computation
916
+ show_progress_bar(`bool`, *optional*, defaults to None):
917
+ Show a progress bar when encoding sentences.
918
+ If set to None, progress bar is only shown when `logger.level == logging.INFO` or `logger.level == logging.DEBUG`.
919
+ output_value(`str`, *optional*, defaults to 'sentence_embedding'):
920
+ Default sentence_embedding, to get sentence embeddings.
921
+ Can be set to token_embeddings to get wordpiece token embeddings.
922
+ Set to None, to get all output values
923
+ convert_to_numpy(`bool`, *optional*, defaults to True):
924
+ If true, the output is a list of numpy vectors.
925
+ Else, it is a list of pytorch tensors.
926
+ convert_to_tensor(`bool`, *optional*, defaults to False):
927
+ If true, you get one large tensor as return.
928
+ Overwrites any setting from convert_to_numpy
929
+ device(`torch.device`, *optional*, defaults to None):
930
+ Which torch.device to use for the computation
931
+ normalize_embeddings(`bool`, *optional*, defaults to False):
932
+ If set to true, returned vectors will have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used.
933
+ tokenizer_kwargs(`Dict[str, Any]`, *optional*, defaults to {}):
934
+ Keyword arguments for the tokenizer
935
+
936
+ Returns:
937
+ By default, a list of tensors is returned.
938
+ If convert_to_tensor, a stacked tensor is returned.
939
+ If convert_to_numpy, a numpy matrix is returned.
940
+ """
941
+
942
+ if convert_to_tensor:
943
+ convert_to_numpy = False
944
+
945
+ if output_value != 'sentence_embedding':
946
+ convert_to_tensor = False
947
+ convert_to_numpy = False
948
+
949
+ input_was_string = False
950
+ if isinstance(sentences, str) or not hasattr(sentences, '__len__'):
951
+ sentences = [sentences]
952
+ input_was_string = True
953
+
954
+ # TODO: Maybe use better length heuristic?
955
+ permutation = np.argsort([-len(i) for i in sentences])
956
+ inverse_permutation = np.argsort(permutation)
957
+ sentences = [sentences[idx] for idx in permutation]
958
+
959
+ tokenizer_kwargs['padding'] = tokenizer_kwargs.get('padding', True)
960
+ tokenizer_kwargs['max_length'] = tokenizer_kwargs.get('max_length', 8192)
961
+ tokenizer_kwargs['truncation'] = tokenizer_kwargs.get('truncation', True)
962
+
963
+ all_embeddings = []
964
+
965
+ if has_tqdm:
966
+ range_iter = trange(
967
+ 0,
968
+ len(sentences),
969
+ batch_size,
970
+ desc="Encoding",
971
+ disable=not show_progress_bar,
972
+ )
973
+ else:
974
+ range_iter = range(0, len(sentences), batch_size)
975
+
976
+ for i in range_iter:
977
+ encoded_input = self.tokenizer(
978
+ sentences[i: i + batch_size],
979
+ return_tensors='pt',
980
+ **tokenizer_kwargs,
981
+ )
982
+ for key in encoded_input.keys():
983
+ encoded_input[key] = encoded_input[key].to(self.device)
984
+ token_embs = self.forward(**encoded_input)[0]
985
+ # Accumulate in fp32 to avoid overflow
986
+ token_embs = token_embs.float()
987
+
988
+ if output_value == 'token_embeddings':
989
+ raise NotImplementedError
990
+ elif output_value is None:
991
+ raise NotImplementedError
992
+ else:
993
+ embeddings = self.mean_pooling(
994
+ token_embs, encoded_input['attention_mask']
995
+ )
996
+
997
+ if normalize_embeddings:
998
+ embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
999
+
1000
+ if convert_to_numpy:
1001
+ embeddings = embeddings.cpu()
1002
+ all_embeddings.extend(embeddings)
1003
+
1004
+ all_embeddings = [all_embeddings[idx] for idx in inverse_permutation]
1005
+
1006
+ if convert_to_tensor:
1007
+ all_embeddings = torch.stack(all_embeddings)
1008
+ elif convert_to_numpy:
1009
+ all_embeddings = np.asarray([emb.detach().numpy() for emb in all_embeddings])
1010
+
1011
+ if input_was_string:
1012
+ all_embeddings = all_embeddings[0]
1013
+ return all_embeddings
1014
+
1015
+ def mean_pooling(self, token_embeddings: torch.Tensor, attention_mask: torch.Tensor):
1016
+ input_mask_expanded = (
1017
+ attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
1018
+ )
1019
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
1020
+ input_mask_expanded.sum(1), min=1e-9
1021
+ )
1022
+
1023
+
1024
+
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "do_lower_case": false
3
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff