dleemiller commited on
Commit
34f9324
·
verified ·
1 Parent(s): 3f87d1b

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,3 +1,376 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - sentence-transformers
4
+ - cross-encoder
5
+ - reranker
6
+ - generated_from_trainer
7
+ - dataset_size:5749
8
+ - loss:BinaryCrossEntropyLoss
9
+ pipeline_tag: text-ranking
10
+ library_name: sentence-transformers
11
+ metrics:
12
+ - pearson
13
+ - spearman
14
+ model-index:
15
+ - name: CrossEncoder
16
+ results:
17
+ - task:
18
+ type: cross-encoder-correlation
19
+ name: Cross Encoder Correlation
20
+ dataset:
21
+ name: sts validation
22
+ type: sts-validation
23
+ metrics:
24
+ - type: pearson
25
+ value: 0.8224681407582783
26
+ name: Pearson
27
+ - type: spearman
28
+ value: 0.8229125405854616
29
+ name: Spearman
30
+ ---
31
+
32
+ # CrossEncoder
33
+
34
+ This is a [Cross Encoder](https://www.sbert.net/docs/cross_encoder/usage/usage.html) model trained using the [sentence-transformers](https://www.SBERT.net) library. It computes scores for pairs of texts, which can be used for text reranking and semantic search.
35
+
36
+ ## Model Details
37
+
38
+ ### Model Description
39
+ - **Model Type:** Cross Encoder
40
+ <!-- - **Base model:** [Unknown](https://huggingface.co/unknown) -->
41
+ - **Maximum Sequence Length:** 416 tokens
42
+ - **Number of Output Labels:** 1 label
43
+ <!-- - **Training Dataset:** Unknown -->
44
+ <!-- - **Language:** Unknown -->
45
+ <!-- - **License:** Unknown -->
46
+
47
+ ### Model Sources
48
+
49
+ - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
50
+ - **Documentation:** [Cross Encoder Documentation](https://www.sbert.net/docs/cross_encoder/usage/usage.html)
51
+ - **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
52
+ - **Hugging Face:** [Cross Encoders on Hugging Face](https://huggingface.co/models?library=sentence-transformers&other=cross-encoder)
53
+
54
+ ## Usage
55
+
56
+ ### Direct Usage (Sentence Transformers)
57
+
58
+ First install the Sentence Transformers library:
59
+
60
+ ```bash
61
+ pip install -U sentence-transformers
62
+ ```
63
+
64
+ Then you can load this model and run inference.
65
+ ```python
66
+ from sentence_transformers import CrossEncoder
67
+
68
+ # Download from the 🤗 Hub
69
+ model = CrossEncoder("cross_encoder_model_id")
70
+ # Get scores for pairs of texts
71
+ pairs = [
72
+ ['Customers include Mitsubishi, Siemens, DBTel, Dell, HP, Palm, Philips, Sharp, and Sony.', "MediaQ's customers include major handheld makers Mitsubishi, Siemens, Palm, Sharp, Philips, Dell and Sony."],
73
+ ['Do you not understand what that string of words means?', "Do you not understand what the word 'led' implies?"],
74
+ ['Black and white cows behind a fence.', 'Two black and white cows behind a metal gate against a partly cloudy blue sky.'],
75
+ ['Ah ha, ha, ha, ha, ha!', 'Ha, ha, ha, ha, ha, ha!'],
76
+ ["Gunmen Surround Libya's Foreign Ministry To Push Demands", 'Gunmen surround Libyan foreign ministry to push demands'],
77
+ ]
78
+ scores = model.predict(pairs)
79
+ print(scores.shape)
80
+ # (5,)
81
+
82
+ # Or rank different texts based on similarity to a single text
83
+ ranks = model.rank(
84
+ 'Customers include Mitsubishi, Siemens, DBTel, Dell, HP, Palm, Philips, Sharp, and Sony.',
85
+ [
86
+ "MediaQ's customers include major handheld makers Mitsubishi, Siemens, Palm, Sharp, Philips, Dell and Sony.",
87
+ "Do you not understand what the word 'led' implies?",
88
+ 'Two black and white cows behind a metal gate against a partly cloudy blue sky.',
89
+ 'Ha, ha, ha, ha, ha, ha!',
90
+ 'Gunmen surround Libyan foreign ministry to push demands',
91
+ ]
92
+ )
93
+ # [{'corpus_id': ..., 'score': ...}, {'corpus_id': ..., 'score': ...}, ...]
94
+ ```
95
+
96
+ <!--
97
+ ### Direct Usage (Transformers)
98
+
99
+ <details><summary>Click to see the direct usage in Transformers</summary>
100
+
101
+ </details>
102
+ -->
103
+
104
+ <!--
105
+ ### Downstream Usage (Sentence Transformers)
106
+
107
+ You can finetune this model on your own dataset.
108
+
109
+ <details><summary>Click to expand</summary>
110
+
111
+ </details>
112
+ -->
113
+
114
+ <!--
115
+ ### Out-of-Scope Use
116
+
117
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
118
+ -->
119
+
120
+ ## Evaluation
121
+
122
+ ### Metrics
123
+
124
+ #### Cross Encoder Correlation
125
+
126
+ * Dataset: `sts-validation`
127
+ * Evaluated with [<code>CECorrelationEvaluator</code>](https://sbert.net/docs/package_reference/cross_encoder/evaluation.html#sentence_transformers.cross_encoder.evaluation.CECorrelationEvaluator)
128
+
129
+ | Metric | Value |
130
+ |:-------------|:-----------|
131
+ | pearson | 0.8225 |
132
+ | **spearman** | **0.8229** |
133
+
134
+ <!--
135
+ ## Bias, Risks and Limitations
136
+
137
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
138
+ -->
139
+
140
+ <!--
141
+ ### Recommendations
142
+
143
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
144
+ -->
145
+
146
+ ## Training Details
147
+
148
+ ### Training Dataset
149
+
150
+ #### Unnamed Dataset
151
+
152
+ * Size: 5,749 training samples
153
+ * Columns: <code>sentence_0</code>, <code>sentence_1</code>, and <code>label</code>
154
+ * Approximate statistics based on the first 1000 samples:
155
+ | | sentence_0 | sentence_1 | label |
156
+ |:--------|:------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------|:---------------------------------------------------------------|
157
+ | type | string | string | float |
158
+ | details | <ul><li>min: 16 characters</li><li>mean: 57.59 characters</li><li>max: 228 characters</li></ul> | <ul><li>min: 15 characters</li><li>mean: 57.85 characters</li><li>max: 239 characters</li></ul> | <ul><li>min: 0.0</li><li>mean: 0.54</li><li>max: 1.0</li></ul> |
159
+ * Samples:
160
+ | sentence_0 | sentence_1 | label |
161
+ |:-----------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------|:------------------|
162
+ | <code>Customers include Mitsubishi, Siemens, DBTel, Dell, HP, Palm, Philips, Sharp, and Sony.</code> | <code>MediaQ's customers include major handheld makers Mitsubishi, Siemens, Palm, Sharp, Philips, Dell and Sony.</code> | <code>0.64</code> |
163
+ | <code>Do you not understand what that string of words means?</code> | <code>Do you not understand what the word 'led' implies?</code> | <code>0.24</code> |
164
+ | <code>Black and white cows behind a fence.</code> | <code>Two black and white cows behind a metal gate against a partly cloudy blue sky.</code> | <code>0.64</code> |
165
+ * Loss: [<code>BinaryCrossEntropyLoss</code>](https://sbert.net/docs/package_reference/cross_encoder/losses.html#binarycrossentropyloss) with these parameters:
166
+ ```json
167
+ {
168
+ "activation_fn": "torch.nn.modules.linear.Identity",
169
+ "pos_weight": null
170
+ }
171
+ ```
172
+
173
+ ### Training Hyperparameters
174
+ #### Non-Default Hyperparameters
175
+
176
+ - `eval_strategy`: steps
177
+ - `per_device_train_batch_size`: 64
178
+ - `per_device_eval_batch_size`: 64
179
+ - `num_train_epochs`: 6
180
+ - `fp16`: True
181
+
182
+ #### All Hyperparameters
183
+ <details><summary>Click to expand</summary>
184
+
185
+ - `overwrite_output_dir`: False
186
+ - `do_predict`: False
187
+ - `eval_strategy`: steps
188
+ - `prediction_loss_only`: True
189
+ - `per_device_train_batch_size`: 64
190
+ - `per_device_eval_batch_size`: 64
191
+ - `per_gpu_train_batch_size`: None
192
+ - `per_gpu_eval_batch_size`: None
193
+ - `gradient_accumulation_steps`: 1
194
+ - `eval_accumulation_steps`: None
195
+ - `torch_empty_cache_steps`: None
196
+ - `learning_rate`: 5e-05
197
+ - `weight_decay`: 0.0
198
+ - `adam_beta1`: 0.9
199
+ - `adam_beta2`: 0.999
200
+ - `adam_epsilon`: 1e-08
201
+ - `max_grad_norm`: 1
202
+ - `num_train_epochs`: 6
203
+ - `max_steps`: -1
204
+ - `lr_scheduler_type`: linear
205
+ - `lr_scheduler_kwargs`: {}
206
+ - `warmup_ratio`: 0.0
207
+ - `warmup_steps`: 0
208
+ - `log_level`: passive
209
+ - `log_level_replica`: warning
210
+ - `log_on_each_node`: True
211
+ - `logging_nan_inf_filter`: True
212
+ - `save_safetensors`: True
213
+ - `save_on_each_node`: False
214
+ - `save_only_model`: False
215
+ - `restore_callback_states_from_checkpoint`: False
216
+ - `no_cuda`: False
217
+ - `use_cpu`: False
218
+ - `use_mps_device`: False
219
+ - `seed`: 42
220
+ - `data_seed`: None
221
+ - `jit_mode_eval`: False
222
+ - `use_ipex`: False
223
+ - `bf16`: False
224
+ - `fp16`: True
225
+ - `fp16_opt_level`: O1
226
+ - `half_precision_backend`: auto
227
+ - `bf16_full_eval`: False
228
+ - `fp16_full_eval`: False
229
+ - `tf32`: None
230
+ - `local_rank`: 0
231
+ - `ddp_backend`: None
232
+ - `tpu_num_cores`: None
233
+ - `tpu_metrics_debug`: False
234
+ - `debug`: []
235
+ - `dataloader_drop_last`: False
236
+ - `dataloader_num_workers`: 0
237
+ - `dataloader_prefetch_factor`: None
238
+ - `past_index`: -1
239
+ - `disable_tqdm`: False
240
+ - `remove_unused_columns`: True
241
+ - `label_names`: None
242
+ - `load_best_model_at_end`: False
243
+ - `ignore_data_skip`: False
244
+ - `fsdp`: []
245
+ - `fsdp_min_num_params`: 0
246
+ - `fsdp_config`: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
247
+ - `fsdp_transformer_layer_cls_to_wrap`: None
248
+ - `accelerator_config`: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
249
+ - `parallelism_config`: None
250
+ - `deepspeed`: None
251
+ - `label_smoothing_factor`: 0.0
252
+ - `optim`: adamw_torch_fused
253
+ - `optim_args`: None
254
+ - `adafactor`: False
255
+ - `group_by_length`: False
256
+ - `length_column_name`: length
257
+ - `ddp_find_unused_parameters`: None
258
+ - `ddp_bucket_cap_mb`: None
259
+ - `ddp_broadcast_buffers`: False
260
+ - `dataloader_pin_memory`: True
261
+ - `dataloader_persistent_workers`: False
262
+ - `skip_memory_metrics`: True
263
+ - `use_legacy_prediction_loop`: False
264
+ - `push_to_hub`: False
265
+ - `resume_from_checkpoint`: None
266
+ - `hub_model_id`: None
267
+ - `hub_strategy`: every_save
268
+ - `hub_private_repo`: None
269
+ - `hub_always_push`: False
270
+ - `hub_revision`: None
271
+ - `gradient_checkpointing`: False
272
+ - `gradient_checkpointing_kwargs`: None
273
+ - `include_inputs_for_metrics`: False
274
+ - `include_for_metrics`: []
275
+ - `eval_do_concat_batches`: True
276
+ - `fp16_backend`: auto
277
+ - `push_to_hub_model_id`: None
278
+ - `push_to_hub_organization`: None
279
+ - `mp_parameters`:
280
+ - `auto_find_batch_size`: False
281
+ - `full_determinism`: False
282
+ - `torchdynamo`: None
283
+ - `ray_scope`: last
284
+ - `ddp_timeout`: 1800
285
+ - `torch_compile`: False
286
+ - `torch_compile_backend`: None
287
+ - `torch_compile_mode`: None
288
+ - `include_tokens_per_second`: False
289
+ - `include_num_input_tokens_seen`: False
290
+ - `neftune_noise_alpha`: None
291
+ - `optim_target_modules`: None
292
+ - `batch_eval_metrics`: False
293
+ - `eval_on_start`: False
294
+ - `use_liger_kernel`: False
295
+ - `liger_kernel_config`: None
296
+ - `eval_use_gather_object`: False
297
+ - `average_tokens_across_devices`: False
298
+ - `prompts`: None
299
+ - `batch_sampler`: batch_sampler
300
+ - `multi_dataset_batch_sampler`: proportional
301
+ - `router_mapping`: {}
302
+ - `learning_rate_mapping`: {}
303
+
304
+ </details>
305
+
306
+ ### Training Logs
307
+ | Epoch | Step | sts-validation_spearman |
308
+ |:------:|:----:|:-----------------------:|
309
+ | 0.2222 | 20 | 0.8000 |
310
+ | 0.4444 | 40 | 0.8078 |
311
+ | 0.6667 | 60 | 0.8023 |
312
+ | 0.8889 | 80 | 0.8122 |
313
+ | 1.0 | 90 | 0.8162 |
314
+ | 1.1111 | 100 | 0.8119 |
315
+ | 1.3333 | 120 | 0.8064 |
316
+ | 1.5556 | 140 | 0.8222 |
317
+ | 1.7778 | 160 | 0.8215 |
318
+ | 2.0 | 180 | 0.8193 |
319
+ | 2.2222 | 200 | 0.8181 |
320
+ | 2.4444 | 220 | 0.8183 |
321
+ | 2.6667 | 240 | 0.8160 |
322
+ | 2.8889 | 260 | 0.8210 |
323
+ | 3.0 | 270 | 0.8221 |
324
+ | 3.1111 | 280 | 0.8154 |
325
+ | 3.3333 | 300 | 0.8133 |
326
+ | 3.5556 | 320 | 0.8164 |
327
+ | 3.7778 | 340 | 0.8207 |
328
+ | 4.0 | 360 | 0.8227 |
329
+ | 4.2222 | 380 | 0.8186 |
330
+ | 4.4444 | 400 | 0.8202 |
331
+ | 4.6667 | 420 | 0.8229 |
332
+
333
+
334
+ ### Framework Versions
335
+ - Python: 3.12.2
336
+ - Sentence Transformers: 5.1.0
337
+ - Transformers: 4.57.0.dev0
338
+ - PyTorch: 2.8.0+cu128
339
+ - Accelerate: 1.10.1
340
+ - Datasets: 4.0.0
341
+ - Tokenizers: 0.22.0
342
+
343
+ ## Citation
344
+
345
+ ### BibTeX
346
+
347
+ #### Sentence Transformers
348
+ ```bibtex
349
+ @inproceedings{reimers-2019-sentence-bert,
350
+ title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
351
+ author = "Reimers, Nils and Gurevych, Iryna",
352
+ booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
353
+ month = "11",
354
+ year = "2019",
355
+ publisher = "Association for Computational Linguistics",
356
+ url = "https://arxiv.org/abs/1908.10084",
357
+ }
358
+ ```
359
+
360
+ <!--
361
+ ## Glossary
362
+
363
+ *Clearly define terms in order to be accessible across audiences.*
364
+ -->
365
+
366
+ <!--
367
+ ## Model Card Authors
368
+
369
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
370
+ -->
371
+
372
+ <!--
373
+ ## Model Card Contact
374
+
375
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
376
+ -->
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertHashForSequenceClassification"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bert_hash.BertHashConfig",
8
+ "AutoModel": "modeling_bert_hash.BertHashModel",
9
+ "AutoModelForMaskedLM": "modeling_bert_hash.BertHashForMaskedLM",
10
+ "AutoModelForSequenceClassification": "modeling_bert_hash.BertHashForSequenceClassification"
11
+ },
12
+ "classifier_dropout": 0.15,
13
+ "dtype": "float32",
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 128,
17
+ "id2label": {
18
+ "0": "LABEL_0"
19
+ },
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 512,
22
+ "label2id": {
23
+ "LABEL_0": 0
24
+ },
25
+ "layer_norm_eps": 1e-12,
26
+ "max_position_embeddings": 512,
27
+ "model_type": "bert_hash",
28
+ "num_attention_heads": 2,
29
+ "num_hidden_layers": 2,
30
+ "pad_token_id": 0,
31
+ "position_embedding_type": "absolute",
32
+ "projections": 16,
33
+ "sentence_transformers": {
34
+ "activation_fn": "torch.nn.modules.activation.Sigmoid",
35
+ "version": "5.1.0"
36
+ },
37
+ "transformers_version": "4.57.0.dev0",
38
+ "type_vocab_size": 2,
39
+ "use_cache": true,
40
+ "vocab_size": 30522
41
+ }
configuration_bert_hash.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.bert.configuration_bert import BertConfig
2
+
3
+
4
+ class BertHashConfig(BertConfig):
5
+ """
6
+ Extension of Bert configuration to add projections parameter.
7
+ """
8
+
9
+ model_type = "bert_hash"
10
+
11
+ def __init__(self, projections=5, **kwargs):
12
+ super().__init__(**kwargs)
13
+
14
+ self.projections = projections
eval/CrossEncoderCorrelationEvaluator_sts-validation_results.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ epoch,steps,Pearson_Correlation,Spearman_Correlation
2
+ 1.0,90,0.8110515656956032,0.8161851068076348
3
+ 2.0,180,0.8212706351818923,0.8193479884122252
4
+ 3.0,270,0.8237602688353948,0.8221027044017133
5
+ 4.0,360,0.8216995594169731,0.8226789104514981
6
+ 5.0,450,0.8207243438053199,0.8197782020964833
7
+ 6.0,540,0.8215869400188868,0.8203661626963028
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18e25fad14ed5ef5c1b2a2f5d42b77fa50459270953eb9964e5ac0298444befa
3
+ size 3883812
modeling_bert_hash.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
6
+
7
+ from transformers.cache_utils import Cache
8
+ from transformers.models.bert.modeling_bert import BertEncoder, BertPooler, BertPreTrainedModel, BertOnlyMLMHead
9
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
10
+ from transformers.modeling_outputs import (
11
+ BaseModelOutputWithPoolingAndCrossAttentions,
12
+ MaskedLMOutput,
13
+ SequenceClassifierOutput,
14
+ )
15
+ from transformers.utils import auto_docstring, logging
16
+
17
+ from .configuration_bert_hash import BertHashConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class BertHashTokens(nn.Module):
23
+ """
24
+ Module that embeds token vocabulary to an intermediate embeddings layer then projects those embeddings to the
25
+ hidden size.
26
+
27
+ The number of projections is like a hash. Setting the projections parameter to 5 is like generating a
28
+ 160-bit hash (5 x float32) for each token. That hash is then projected to the hidden size.
29
+
30
+ This significantly reduces the number of parameters necessary for token embeddings.
31
+
32
+ For example:
33
+ Standard token embeddings:
34
+ 30,522 (vocab size) x 768 (hidden size) = 23,440,896 parameters
35
+ 23,440,896 x 4 (float32) = 93,763,584 bytes
36
+
37
+ Hash token embeddings:
38
+ 30,522 (vocab size) x 5 (hash buckets) + 5 x 768 (projection matrix)= 156,450 parameters
39
+ 156,450 x 4 (float32) = 625,800 bytes
40
+ """
41
+
42
+ def __init__(self, config):
43
+ super().__init__()
44
+ self.config = config
45
+
46
+ # Token embeddings
47
+ self.embeddings = nn.Embedding(config.vocab_size, config.projections, padding_idx=config.pad_token_id)
48
+
49
+ # Token embeddings projections
50
+ self.projections = nn.Linear(config.projections, config.hidden_size)
51
+
52
+ def forward(self, input_ids):
53
+ # Project embeddings to hidden size
54
+ return self.projections(self.embeddings(input_ids))
55
+
56
+
57
+ class BertHashEmbeddings(nn.Module):
58
+ """Construct the embeddings from word, position and token_type embeddings."""
59
+
60
+ def __init__(self, config):
61
+ super().__init__()
62
+ self.word_embeddings = BertHashTokens(config)
63
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
64
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
65
+
66
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
67
+ # any TensorFlow checkpoint file
68
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
69
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
70
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
71
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
72
+ self.register_buffer(
73
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
74
+ )
75
+ self.register_buffer(
76
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
77
+ )
78
+
79
+ def forward(
80
+ self,
81
+ input_ids: Optional[torch.LongTensor] = None,
82
+ token_type_ids: Optional[torch.LongTensor] = None,
83
+ position_ids: Optional[torch.LongTensor] = None,
84
+ inputs_embeds: Optional[torch.FloatTensor] = None,
85
+ past_key_values_length: int = 0,
86
+ ) -> torch.Tensor:
87
+ if input_ids is not None:
88
+ input_shape = input_ids.size()
89
+ else:
90
+ input_shape = inputs_embeds.size()[:-1]
91
+
92
+ seq_length = input_shape[1]
93
+
94
+ if position_ids is None:
95
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
96
+
97
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
98
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
99
+ # issue #5664
100
+ if token_type_ids is None:
101
+ if hasattr(self, "token_type_ids"):
102
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
103
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
104
+ token_type_ids = buffered_token_type_ids_expanded
105
+ else:
106
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
107
+
108
+ if inputs_embeds is None:
109
+ inputs_embeds = self.word_embeddings(input_ids)
110
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
111
+
112
+ embeddings = inputs_embeds + token_type_embeddings
113
+ if self.position_embedding_type == "absolute":
114
+ position_embeddings = self.position_embeddings(position_ids)
115
+ embeddings += position_embeddings
116
+ embeddings = self.LayerNorm(embeddings)
117
+ embeddings = self.dropout(embeddings)
118
+ return embeddings
119
+
120
+
121
+ @auto_docstring(
122
+ custom_intro="""
123
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
124
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
125
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
126
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
127
+
128
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
129
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
130
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
131
+ """
132
+ )
133
+ class BertHashModel(BertPreTrainedModel):
134
+ config_class = BertHashConfig
135
+
136
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
137
+
138
+ def __init__(self, config, add_pooling_layer=True):
139
+ r"""
140
+ add_pooling_layer (bool, *optional*, defaults to `True`):
141
+ Whether to add a pooling layer
142
+ """
143
+ super().__init__(config)
144
+ self.config = config
145
+
146
+ self.embeddings = BertHashEmbeddings(config)
147
+ self.encoder = BertEncoder(config)
148
+
149
+ self.pooler = BertPooler(config) if add_pooling_layer else None
150
+
151
+ self.attn_implementation = config._attn_implementation
152
+ self.position_embedding_type = config.position_embedding_type
153
+
154
+ # Initialize weights and apply final processing
155
+ self.post_init()
156
+
157
+ def get_input_embeddings(self):
158
+ return self.embeddings.word_embeddings.embeddings
159
+
160
+ def set_input_embeddings(self, value):
161
+ self.embeddings.word_embeddings.embeddings = value
162
+
163
+ def _prune_heads(self, heads_to_prune):
164
+ """
165
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
166
+ class PreTrainedModel
167
+ """
168
+ for layer, heads in heads_to_prune.items():
169
+ self.encoder.layer[layer].attention.prune_heads(heads)
170
+
171
+ @auto_docstring
172
+ def forward(
173
+ self,
174
+ input_ids: Optional[torch.Tensor] = None,
175
+ attention_mask: Optional[torch.Tensor] = None,
176
+ token_type_ids: Optional[torch.Tensor] = None,
177
+ position_ids: Optional[torch.Tensor] = None,
178
+ head_mask: Optional[torch.Tensor] = None,
179
+ inputs_embeds: Optional[torch.Tensor] = None,
180
+ encoder_hidden_states: Optional[torch.Tensor] = None,
181
+ encoder_attention_mask: Optional[torch.Tensor] = None,
182
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
183
+ use_cache: Optional[bool] = None,
184
+ output_attentions: Optional[bool] = None,
185
+ output_hidden_states: Optional[bool] = None,
186
+ return_dict: Optional[bool] = None,
187
+ cache_position: Optional[torch.Tensor] = None,
188
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
189
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
190
+ output_hidden_states = (
191
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
192
+ )
193
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
194
+
195
+ if self.config.is_decoder:
196
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
197
+ else:
198
+ use_cache = False
199
+
200
+ if input_ids is not None and inputs_embeds is not None:
201
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
202
+ elif input_ids is not None:
203
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
204
+ input_shape = input_ids.size()
205
+ elif inputs_embeds is not None:
206
+ input_shape = inputs_embeds.size()[:-1]
207
+ else:
208
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
209
+
210
+ batch_size, seq_length = input_shape
211
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
212
+
213
+ past_key_values_length = 0
214
+ if past_key_values is not None:
215
+ past_key_values_length = (
216
+ past_key_values[0][0].shape[-2]
217
+ if not isinstance(past_key_values, Cache)
218
+ else past_key_values.get_seq_length()
219
+ )
220
+
221
+ if token_type_ids is None:
222
+ if hasattr(self.embeddings, "token_type_ids"):
223
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
224
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
225
+ token_type_ids = buffered_token_type_ids_expanded
226
+ else:
227
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
228
+
229
+ embedding_output = self.embeddings(
230
+ input_ids=input_ids,
231
+ position_ids=position_ids,
232
+ token_type_ids=token_type_ids,
233
+ inputs_embeds=inputs_embeds,
234
+ past_key_values_length=past_key_values_length,
235
+ )
236
+
237
+ if attention_mask is None:
238
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
239
+
240
+ use_sdpa_attention_masks = (
241
+ self.attn_implementation == "sdpa"
242
+ and self.position_embedding_type == "absolute"
243
+ and head_mask is None
244
+ and not output_attentions
245
+ )
246
+
247
+ # Expand the attention mask
248
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
249
+ # Expand the attention mask for SDPA.
250
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
251
+ if self.config.is_decoder:
252
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
253
+ attention_mask,
254
+ input_shape,
255
+ embedding_output,
256
+ past_key_values_length,
257
+ )
258
+ else:
259
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
260
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
261
+ )
262
+ else:
263
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
264
+ # ourselves in which case we just need to make it broadcastable to all heads.
265
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
266
+
267
+ # If a 2D or 3D attention mask is provided for the cross-attention
268
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
269
+ if self.config.is_decoder and encoder_hidden_states is not None:
270
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
271
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
272
+ if encoder_attention_mask is None:
273
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
274
+
275
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
276
+ # Expand the attention mask for SDPA.
277
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
278
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
279
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
280
+ )
281
+ else:
282
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
283
+ else:
284
+ encoder_extended_attention_mask = None
285
+
286
+ # Prepare head mask if needed
287
+ # 1.0 in head_mask indicate we keep the head
288
+ # attention_probs has shape bsz x n_heads x N x N
289
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
290
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
291
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
292
+
293
+ encoder_outputs = self.encoder(
294
+ embedding_output,
295
+ attention_mask=extended_attention_mask,
296
+ head_mask=head_mask,
297
+ encoder_hidden_states=encoder_hidden_states,
298
+ encoder_attention_mask=encoder_extended_attention_mask,
299
+ past_key_values=past_key_values,
300
+ use_cache=use_cache,
301
+ output_attentions=output_attentions,
302
+ output_hidden_states=output_hidden_states,
303
+ return_dict=return_dict,
304
+ cache_position=cache_position,
305
+ )
306
+ sequence_output = encoder_outputs[0]
307
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
308
+
309
+ if not return_dict:
310
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
311
+
312
+ return BaseModelOutputWithPoolingAndCrossAttentions(
313
+ last_hidden_state=sequence_output,
314
+ pooler_output=pooled_output,
315
+ past_key_values=encoder_outputs.past_key_values,
316
+ hidden_states=encoder_outputs.hidden_states,
317
+ attentions=encoder_outputs.attentions,
318
+ cross_attentions=encoder_outputs.cross_attentions,
319
+ )
320
+
321
+
322
+ @auto_docstring
323
+ class BertHashForMaskedLM(BertPreTrainedModel):
324
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
325
+ config_class = BertHashConfig
326
+
327
+ def __init__(self, config):
328
+ super().__init__(config)
329
+
330
+ if config.is_decoder:
331
+ logger.warning(
332
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
333
+ "bi-directional self-attention."
334
+ )
335
+
336
+ self.bert = BertHashModel(config, add_pooling_layer=False)
337
+ self.cls = BertOnlyMLMHead(config)
338
+
339
+ # Initialize weights and apply final processing
340
+ self.post_init()
341
+
342
+ @auto_docstring
343
+ def forward(
344
+ self,
345
+ input_ids: Optional[torch.Tensor] = None,
346
+ attention_mask: Optional[torch.Tensor] = None,
347
+ token_type_ids: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.Tensor] = None,
349
+ head_mask: Optional[torch.Tensor] = None,
350
+ inputs_embeds: Optional[torch.Tensor] = None,
351
+ encoder_hidden_states: Optional[torch.Tensor] = None,
352
+ encoder_attention_mask: Optional[torch.Tensor] = None,
353
+ labels: Optional[torch.Tensor] = None,
354
+ output_attentions: Optional[bool] = None,
355
+ output_hidden_states: Optional[bool] = None,
356
+ return_dict: Optional[bool] = None,
357
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
358
+ r"""
359
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
360
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
361
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
362
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
363
+ """
364
+
365
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
366
+
367
+ outputs = self.bert(
368
+ input_ids,
369
+ attention_mask=attention_mask,
370
+ token_type_ids=token_type_ids,
371
+ position_ids=position_ids,
372
+ head_mask=head_mask,
373
+ inputs_embeds=inputs_embeds,
374
+ encoder_hidden_states=encoder_hidden_states,
375
+ encoder_attention_mask=encoder_attention_mask,
376
+ output_attentions=output_attentions,
377
+ output_hidden_states=output_hidden_states,
378
+ return_dict=return_dict,
379
+ )
380
+
381
+ sequence_output = outputs[0]
382
+ prediction_scores = self.cls(sequence_output)
383
+
384
+ masked_lm_loss = None
385
+ if labels is not None:
386
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
387
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
388
+
389
+ if not return_dict:
390
+ output = (prediction_scores,) + outputs[2:]
391
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
392
+
393
+ return MaskedLMOutput(
394
+ loss=masked_lm_loss,
395
+ logits=prediction_scores,
396
+ hidden_states=outputs.hidden_states,
397
+ attentions=outputs.attentions,
398
+ )
399
+
400
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
401
+ input_shape = input_ids.shape
402
+ effective_batch_size = input_shape[0]
403
+
404
+ # add a dummy token
405
+ if self.config.pad_token_id is None:
406
+ raise ValueError("The PAD token should be defined for generation")
407
+
408
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
409
+ dummy_token = torch.full(
410
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
411
+ )
412
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
413
+
414
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
415
+
416
+ @classmethod
417
+ def can_generate(cls) -> bool:
418
+ """
419
+ Legacy correction: BertForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
420
+ `prepare_inputs_for_generation` method.
421
+ """
422
+ return False
423
+
424
+
425
+ @auto_docstring(
426
+ custom_intro="""
427
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
428
+ output) e.g. for GLUE tasks.
429
+ """
430
+ )
431
+ class BertHashForSequenceClassification(BertPreTrainedModel):
432
+ config_class = BertHashConfig
433
+
434
+ def __init__(self, config):
435
+ super().__init__(config)
436
+ self.num_labels = config.num_labels
437
+ self.config = config
438
+
439
+ self.bert = BertHashModel(config)
440
+ classifier_dropout = (
441
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
442
+ )
443
+ self.dropout = nn.Dropout(classifier_dropout)
444
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
445
+
446
+ # Initialize weights and apply final processing
447
+ self.post_init()
448
+
449
+ @auto_docstring
450
+ def forward(
451
+ self,
452
+ input_ids: Optional[torch.Tensor] = None,
453
+ attention_mask: Optional[torch.Tensor] = None,
454
+ token_type_ids: Optional[torch.Tensor] = None,
455
+ position_ids: Optional[torch.Tensor] = None,
456
+ head_mask: Optional[torch.Tensor] = None,
457
+ inputs_embeds: Optional[torch.Tensor] = None,
458
+ labels: Optional[torch.Tensor] = None,
459
+ output_attentions: Optional[bool] = None,
460
+ output_hidden_states: Optional[bool] = None,
461
+ return_dict: Optional[bool] = None,
462
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
463
+ r"""
464
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
465
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
466
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
467
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
468
+ """
469
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
470
+
471
+ outputs = self.bert(
472
+ input_ids,
473
+ attention_mask=attention_mask,
474
+ token_type_ids=token_type_ids,
475
+ position_ids=position_ids,
476
+ head_mask=head_mask,
477
+ inputs_embeds=inputs_embeds,
478
+ output_attentions=output_attentions,
479
+ output_hidden_states=output_hidden_states,
480
+ return_dict=return_dict,
481
+ )
482
+
483
+ pooled_output = outputs[1]
484
+
485
+ pooled_output = self.dropout(pooled_output)
486
+ logits = self.classifier(pooled_output)
487
+
488
+ loss = None
489
+ if labels is not None:
490
+ if self.config.problem_type is None:
491
+ if self.num_labels == 1:
492
+ self.config.problem_type = "regression"
493
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
494
+ self.config.problem_type = "single_label_classification"
495
+ else:
496
+ self.config.problem_type = "multi_label_classification"
497
+
498
+ if self.config.problem_type == "regression":
499
+ loss_fct = MSELoss()
500
+ if self.num_labels == 1:
501
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
502
+ else:
503
+ loss = loss_fct(logits, labels)
504
+ elif self.config.problem_type == "single_label_classification":
505
+ loss_fct = CrossEntropyLoss()
506
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
507
+ elif self.config.problem_type == "multi_label_classification":
508
+ loss_fct = BCEWithLogitsLoss()
509
+ loss = loss_fct(logits, labels)
510
+ if not return_dict:
511
+ output = (logits,) + outputs[2:]
512
+ return ((loss,) + output) if loss is not None else output
513
+
514
+ return SequenceClassifierOutput(
515
+ loss=loss,
516
+ logits=logits,
517
+ hidden_states=outputs.hidden_states,
518
+ attentions=outputs.attentions,
519
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "extra_special_tokens": {},
48
+ "mask_token": "[MASK]",
49
+ "max_length": 416,
50
+ "model_max_length": 416,
51
+ "pad_to_multiple_of": null,
52
+ "pad_token": "[PAD]",
53
+ "pad_token_type_id": 0,
54
+ "padding_side": "right",
55
+ "sep_token": "[SEP]",
56
+ "stride": 0,
57
+ "strip_accents": null,
58
+ "tokenize_chinese_chars": true,
59
+ "tokenizer_class": "BertTokenizer",
60
+ "truncation_side": "right",
61
+ "truncation_strategy": "longest_first",
62
+ "unk_token": "[UNK]"
63
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff