Upload folder using huggingface_hub
Browse files- .gitattributes +8 -27
- README.md +88 -0
- __init__.py +0 -0
- config.json +35 -0
- configuration_deberta.py +60 -0
- ds_config.json +23 -0
- generation_config.json +14 -0
- modeling_deberta.py +1391 -0
- pytorch_model.bin +3 -0
- spm.model +3 -0
- tokenizer_config.json +4 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,16 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.
|
| 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
|
|
|
|
| 1 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 3 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.tar.gz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 11 |
*.joblib 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 |
*.pb filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
| 15 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 16 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
| 1 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
license: mit
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
language: en
|
| 3 |
+
tags:
|
| 4 |
+
- deberta
|
| 5 |
+
- fill-mask
|
| 6 |
+
thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
|
| 7 |
license: mit
|
| 8 |
---
|
| 9 |
+
|
| 10 |
+
## DeBERTa: Decoding-enhanced BERT with Disentangled Attention
|
| 11 |
+
|
| 12 |
+
[DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. It outperforms BERT and RoBERTa on majority of NLU tasks with 80GB training data.
|
| 13 |
+
|
| 14 |
+
Please check the [official repository](https://github.com/microsoft/DeBERTa) for more details and updates.
|
| 15 |
+
|
| 16 |
+
This is the DeBERTa V2 xxlarge model with 48 layers, 1536 hidden size. The total parameters are 1.5B and it is trained with 160GB raw data.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
### Fine-tuning on NLU tasks
|
| 20 |
+
|
| 21 |
+
We present the dev results on SQuAD 1.1/2.0 and several GLUE benchmark tasks.
|
| 22 |
+
|
| 23 |
+
| Model | SQuAD 1.1 | SQuAD 2.0 | MNLI-m/mm | SST-2 | QNLI | CoLA | RTE | MRPC | QQP |STS-B |
|
| 24 |
+
|---------------------------|-----------|-----------|-------------|-------|------|------|--------|-------|-------|------|
|
| 25 |
+
| | F1/EM | F1/EM | Acc | Acc | Acc | MCC | Acc |Acc/F1 |Acc/F1 |P/S |
|
| 26 |
+
| BERT-Large | 90.9/84.1 | 81.8/79.0 | 86.6/- | 93.2 | 92.3 | 60.6 | 70.4 | 88.0/- | 91.3/- |90.0/- |
|
| 27 |
+
| RoBERTa-Large | 94.6/88.9 | 89.4/86.5 | 90.2/- | 96.4 | 93.9 | 68.0 | 86.6 | 90.9/- | 92.2/- |92.4/- |
|
| 28 |
+
| XLNet-Large | 95.1/89.7 | 90.6/87.9 | 90.8/- | 97.0 | 94.9 | 69.0 | 85.9 | 90.8/- | 92.3/- |92.5/- |
|
| 29 |
+
| [DeBERTa-Large](https://huggingface.co/microsoft/deberta-large)<sup>1</sup> | 95.5/90.1 | 90.7/88.0 | 91.3/91.1| 96.5|95.3| 69.5| 91.0| 92.6/94.6| 92.3/- |92.8/92.5 |
|
| 30 |
+
| [DeBERTa-XLarge](https://huggingface.co/microsoft/deberta-xlarge)<sup>1</sup> | -/- | -/- | 91.5/91.2| 97.0 | - | - | 93.1 | 92.1/94.3 | - |92.9/92.7|
|
| 31 |
+
| [DeBERTa-V2-XLarge](https://huggingface.co/microsoft/deberta-v2-xlarge)<sup>1</sup>|95.8/90.8| 91.4/88.9|91.7/91.6| **97.5**| 95.8|71.1|**93.9**|92.0/94.2|92.3/89.8|92.9/92.9|
|
| 32 |
+
|**[DeBERTa-V2-XXLarge](https://huggingface.co/microsoft/deberta-v2-xxlarge)<sup>1,2</sup>**|**96.1/91.4**|**92.2/89.7**|**91.7/91.9**|97.2|**96.0**|**72.0**| 93.5| **93.1/94.9**|**92.7/90.3** |**93.2/93.1** |
|
| 33 |
+
--------
|
| 34 |
+
#### Notes.
|
| 35 |
+
- <sup>1</sup> Following RoBERTa, for RTE, MRPC, STS-B, we fine-tune the tasks based on [DeBERTa-Large-MNLI](https://huggingface.co/microsoft/deberta-large-mnli), [DeBERTa-XLarge-MNLI](https://huggingface.co/microsoft/deberta-xlarge-mnli), [DeBERTa-V2-XLarge-MNLI](https://huggingface.co/microsoft/deberta-v2-xlarge-mnli), [DeBERTa-V2-XXLarge-MNLI](https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli). The results of SST-2/QQP/QNLI/SQuADv2 will also be slightly improved when start from MNLI fine-tuned models, however, we only report the numbers fine-tuned from pretrained base models for those 4 tasks.
|
| 36 |
+
- <sup>2</sup> To try the **XXLarge** model with **[HF transformers](https://huggingface.co/transformers/main_classes/trainer.html)**, we recommand using **deepspeed** as it's faster and saves memory.
|
| 37 |
+
|
| 38 |
+
Run with `Deepspeed`,
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
pip install datasets
|
| 42 |
+
pip install deepspeed
|
| 43 |
+
|
| 44 |
+
# Download the deepspeed config file
|
| 45 |
+
wget https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/ds_config.json -O ds_config.json
|
| 46 |
+
|
| 47 |
+
export TASK_NAME=mnli
|
| 48 |
+
output_dir="ds_results"
|
| 49 |
+
num_gpus=8
|
| 50 |
+
batch_size=8
|
| 51 |
+
python -m torch.distributed.launch --nproc_per_node=${num_gpus} \\
|
| 52 |
+
run_glue.py \\
|
| 53 |
+
--model_name_or_path microsoft/deberta-v2-xxlarge \\
|
| 54 |
+
--task_name $TASK_NAME \\
|
| 55 |
+
--do_train \\
|
| 56 |
+
--do_eval \\
|
| 57 |
+
--max_seq_length 256 \\
|
| 58 |
+
--per_device_train_batch_size ${batch_size} \\
|
| 59 |
+
--learning_rate 3e-6 \\
|
| 60 |
+
--num_train_epochs 3 \\
|
| 61 |
+
--output_dir $output_dir \\
|
| 62 |
+
--overwrite_output_dir \\
|
| 63 |
+
--logging_steps 10 \\
|
| 64 |
+
--logging_dir $output_dir \\
|
| 65 |
+
--deepspeed ds_config.json
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
You can also run with `--sharded_ddp`
|
| 69 |
+
```bash
|
| 70 |
+
cd transformers/examples/text-classification/
|
| 71 |
+
export TASK_NAME=mnli
|
| 72 |
+
python -m torch.distributed.launch --nproc_per_node=8 run_glue.py --model_name_or_path microsoft/deberta-v2-xxlarge \\
|
| 73 |
+
--task_name $TASK_NAME --do_train --do_eval --max_seq_length 256 --per_device_train_batch_size 8 \\
|
| 74 |
+
--learning_rate 3e-6 --num_train_epochs 3 --output_dir /tmp/$TASK_NAME/ --overwrite_output_dir --sharded_ddp --fp16
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
### Citation
|
| 79 |
+
|
| 80 |
+
If you find DeBERTa useful for your work, please cite the following paper:
|
| 81 |
+
|
| 82 |
+
``` latex
|
| 83 |
+
@inproceedings{
|
| 84 |
+
he2021deberta,
|
| 85 |
+
title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
|
| 86 |
+
author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
|
| 87 |
+
booktitle={International Conference on Learning Representations},
|
| 88 |
+
year={2021},
|
| 89 |
+
url={https://openreview.net/forum?id=XPZIaotutsD}
|
| 90 |
+
}
|
| 91 |
+
```
|
__init__.py
ADDED
|
File without changes
|
config.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DebertaV2ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_deberta.DebertaV2Config",
|
| 7 |
+
"AutoModel": "modeling_deberta.DebertaV2Model",
|
| 8 |
+
"AutoModelForMaskedLM": "modeling_deberta.DebertaV2ForMaskedLM",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_deberta.DebertaV2ForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"sep_token_id": 2,
|
| 12 |
+
"mask_token_id": 128000,
|
| 13 |
+
"attention_probs_dropout_prob": 0.1,
|
| 14 |
+
"hidden_act": "gelu",
|
| 15 |
+
"hidden_dropout_prob": 0.1,
|
| 16 |
+
"hidden_size": 1536,
|
| 17 |
+
"initializer_range": 0.02,
|
| 18 |
+
"intermediate_size": 6144,
|
| 19 |
+
"max_position_embeddings": 512,
|
| 20 |
+
"relative_attention": true,
|
| 21 |
+
"position_buckets": 256,
|
| 22 |
+
"norm_rel_ebd": "layer_norm",
|
| 23 |
+
"share_att_key": true,
|
| 24 |
+
"pos_att_type": "p2c|c2p",
|
| 25 |
+
"layer_norm_eps": 1e-7,
|
| 26 |
+
"conv_kernel_size": 3,
|
| 27 |
+
"conv_act": "gelu",
|
| 28 |
+
"max_relative_positions": -1,
|
| 29 |
+
"position_biased_input": false,
|
| 30 |
+
"num_attention_heads": 24,
|
| 31 |
+
"attention_head_size": 64,
|
| 32 |
+
"num_hidden_layers": 48,
|
| 33 |
+
"type_vocab_size": 0,
|
| 34 |
+
"vocab_size": 128100
|
| 35 |
+
}
|
configuration_deberta.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class DebertaV2Config(PretrainedConfig):
|
| 4 |
+
model_type = "deberta-v2"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size=128100,
|
| 9 |
+
hidden_size=1536,
|
| 10 |
+
sep_token_id=2,
|
| 11 |
+
mask_token_id=128000,
|
| 12 |
+
num_hidden_layers=24,
|
| 13 |
+
num_attention_heads=24,
|
| 14 |
+
intermediate_size=6144,
|
| 15 |
+
hidden_act="gelu",
|
| 16 |
+
hidden_dropout_prob=0.1,
|
| 17 |
+
attention_probs_dropout_prob=0.1,
|
| 18 |
+
max_position_embeddings=512,
|
| 19 |
+
type_vocab_size=0,
|
| 20 |
+
initializer_range=0.02,
|
| 21 |
+
layer_norm_eps=1e-7,
|
| 22 |
+
relative_attention=False,
|
| 23 |
+
max_relative_positions=-1,
|
| 24 |
+
pad_token_id=0,
|
| 25 |
+
position_biased_input=True,
|
| 26 |
+
pos_att_type=None,
|
| 27 |
+
pooler_dropout=0,
|
| 28 |
+
pooler_hidden_act="gelu",
|
| 29 |
+
**kwargs,
|
| 30 |
+
):
|
| 31 |
+
super().__init__(**kwargs)
|
| 32 |
+
|
| 33 |
+
self.hidden_size = hidden_size
|
| 34 |
+
self.mask_token_id = mask_token_id
|
| 35 |
+
self.sep_token_id = sep_token_id
|
| 36 |
+
self.num_hidden_layers = num_hidden_layers
|
| 37 |
+
self.num_attention_heads = num_attention_heads
|
| 38 |
+
self.intermediate_size = intermediate_size
|
| 39 |
+
self.hidden_act = hidden_act
|
| 40 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 41 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 42 |
+
self.max_position_embeddings = max_position_embeddings
|
| 43 |
+
self.type_vocab_size = type_vocab_size
|
| 44 |
+
self.initializer_range = initializer_range
|
| 45 |
+
self.relative_attention = relative_attention
|
| 46 |
+
self.max_relative_positions = max_relative_positions
|
| 47 |
+
self.pad_token_id = pad_token_id
|
| 48 |
+
self.position_biased_input = position_biased_input
|
| 49 |
+
|
| 50 |
+
# Backwards compatibility
|
| 51 |
+
if isinstance(pos_att_type, str):
|
| 52 |
+
pos_att_type = [x.strip() for x in pos_att_type.lower().split("|")]
|
| 53 |
+
|
| 54 |
+
self.pos_att_type = pos_att_type
|
| 55 |
+
self.vocab_size = vocab_size
|
| 56 |
+
self.layer_norm_eps = layer_norm_eps
|
| 57 |
+
|
| 58 |
+
self.pooler_hidden_size = kwargs.get("pooler_hidden_size", hidden_size)
|
| 59 |
+
self.pooler_dropout = pooler_dropout
|
| 60 |
+
self.pooler_hidden_act = pooler_hidden_act
|
ds_config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fp16": {
|
| 3 |
+
|
| 4 |
+
"enabled": true,
|
| 5 |
+
|
| 6 |
+
"initial_scale_power": 12
|
| 7 |
+
|
| 8 |
+
},
|
| 9 |
+
"zero_optimization": {
|
| 10 |
+
|
| 11 |
+
"stage": 2,
|
| 12 |
+
|
| 13 |
+
"reduce_bucket_size": 5e7,
|
| 14 |
+
|
| 15 |
+
"allgather_bucket_size": 1.25e9,
|
| 16 |
+
|
| 17 |
+
"overlap_comm": true,
|
| 18 |
+
|
| 19 |
+
"contiguous_gradients": true
|
| 20 |
+
|
| 21 |
+
},
|
| 22 |
+
"zero_allow_untested_optimizer": true
|
| 23 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"transformers_version": "4.36.0",
|
| 7 |
+
"top_k": 64,
|
| 8 |
+
"top_p": 0.9,
|
| 9 |
+
"repetition_penalty": 1.0,
|
| 10 |
+
"sample": true,
|
| 11 |
+
"temperature": 0.3,
|
| 12 |
+
"max_new_tokens": 512,
|
| 13 |
+
"use_cache": false
|
| 14 |
+
}
|
modeling_deberta.py
ADDED
|
@@ -0,0 +1,1391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 Microsoft and the Hugging Face Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch DeBERTa-v2 model."""
|
| 16 |
+
|
| 17 |
+
from collections.abc import Sequence
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
| 24 |
+
|
| 25 |
+
from transformers.activations import ACT2FN
|
| 26 |
+
from transformers.modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
MaskedLMOutput,
|
| 29 |
+
CausalLMOutput,
|
| 30 |
+
MultipleChoiceModelOutput,
|
| 31 |
+
QuestionAnsweringModelOutput,
|
| 32 |
+
SequenceClassifierOutput,
|
| 33 |
+
TokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 36 |
+
from transformers.pytorch_utils import softmax_backward_data
|
| 37 |
+
from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 38 |
+
from transformers.models.deberta_v2.modeling_deberta_v2 import DebertaV2Config
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
_CONFIG_FOR_DOC = "DebertaV2Config"
|
| 44 |
+
_CHECKPOINT_FOR_DOC = "microsoft/deberta-v2-xlarge"
|
| 45 |
+
_QA_TARGET_START_INDEX = 2
|
| 46 |
+
_QA_TARGET_END_INDEX = 9
|
| 47 |
+
|
| 48 |
+
DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 49 |
+
"microsoft/deberta-v2-xlarge",
|
| 50 |
+
"microsoft/deberta-v2-xxlarge",
|
| 51 |
+
"microsoft/deberta-v2-xlarge-mnli",
|
| 52 |
+
"microsoft/deberta-v2-xxlarge-mnli",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Copied from transformers.models.deberta.modeling_deberta.ContextPooler
|
| 57 |
+
class ContextPooler(nn.Module):
|
| 58 |
+
def __init__(self, config):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size)
|
| 61 |
+
self.dropout = StableDropout(config.pooler_dropout)
|
| 62 |
+
self.config = config
|
| 63 |
+
|
| 64 |
+
def forward(self, hidden_states):
|
| 65 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 66 |
+
# to the first token.
|
| 67 |
+
|
| 68 |
+
context_token = hidden_states[:, 0]
|
| 69 |
+
context_token = self.dropout(context_token)
|
| 70 |
+
pooled_output = self.dense(context_token)
|
| 71 |
+
pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output)
|
| 72 |
+
return pooled_output
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def output_dim(self):
|
| 76 |
+
return self.config.hidden_size
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Copied from transformers.models.deberta.modeling_deberta.XSoftmax with deberta->deberta_v2
|
| 80 |
+
class XSoftmax(torch.autograd.Function):
|
| 81 |
+
"""
|
| 82 |
+
Masked Softmax which is optimized for saving memory
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
input (`torch.tensor`): The input tensor that will apply softmax.
|
| 86 |
+
mask (`torch.IntTensor`):
|
| 87 |
+
The mask matrix where 0 indicate that element will be ignored in the softmax calculation.
|
| 88 |
+
dim (int): The dimension that will apply softmax
|
| 89 |
+
|
| 90 |
+
Example:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> import torch
|
| 94 |
+
>>> from transformers.models.deberta_v2.modeling_deberta_v2 import XSoftmax
|
| 95 |
+
|
| 96 |
+
>>> # Make a tensor
|
| 97 |
+
>>> x = torch.randn([4, 20, 100])
|
| 98 |
+
|
| 99 |
+
>>> # Create a mask
|
| 100 |
+
>>> mask = (x > 0).int()
|
| 101 |
+
|
| 102 |
+
>>> # Specify the dimension to apply softmax
|
| 103 |
+
>>> dim = -1
|
| 104 |
+
|
| 105 |
+
>>> y = XSoftmax.apply(x, mask, dim)
|
| 106 |
+
```"""
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def forward(self, input, mask, dim):
|
| 110 |
+
self.dim = dim
|
| 111 |
+
rmask = ~(mask.to(torch.bool))
|
| 112 |
+
|
| 113 |
+
output = input.masked_fill(rmask, torch.tensor(torch.finfo(input.dtype).min))
|
| 114 |
+
output = torch.softmax(output, self.dim)
|
| 115 |
+
output.masked_fill_(rmask, 0)
|
| 116 |
+
self.save_for_backward(output)
|
| 117 |
+
return output
|
| 118 |
+
|
| 119 |
+
@staticmethod
|
| 120 |
+
def backward(self, grad_output):
|
| 121 |
+
(output,) = self.saved_tensors
|
| 122 |
+
inputGrad = softmax_backward_data(self, grad_output, output, self.dim, output)
|
| 123 |
+
return inputGrad, None, None
|
| 124 |
+
|
| 125 |
+
@staticmethod
|
| 126 |
+
def symbolic(g, self, mask, dim):
|
| 127 |
+
import torch.onnx.symbolic_helper as sym_help
|
| 128 |
+
from torch.onnx.symbolic_opset9 import masked_fill, softmax
|
| 129 |
+
|
| 130 |
+
mask_cast_value = g.op("Cast", mask, to_i=sym_help.cast_pytorch_to_onnx["Long"])
|
| 131 |
+
r_mask = g.op(
|
| 132 |
+
"Cast",
|
| 133 |
+
g.op("Sub", g.op("Constant", value_t=torch.tensor(1, dtype=torch.int64)), mask_cast_value),
|
| 134 |
+
to_i=sym_help.cast_pytorch_to_onnx["Bool"],
|
| 135 |
+
)
|
| 136 |
+
output = masked_fill(
|
| 137 |
+
g, self, r_mask, g.op("Constant", value_t=torch.tensor(torch.finfo(self.type().dtype()).min))
|
| 138 |
+
)
|
| 139 |
+
output = softmax(g, output, dim)
|
| 140 |
+
return masked_fill(g, output, r_mask, g.op("Constant", value_t=torch.tensor(0, dtype=torch.bool)))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# Copied from transformers.models.deberta.modeling_deberta.DropoutContext
|
| 144 |
+
class DropoutContext(object):
|
| 145 |
+
def __init__(self):
|
| 146 |
+
self.dropout = 0
|
| 147 |
+
self.mask = None
|
| 148 |
+
self.scale = 1
|
| 149 |
+
self.reuse_mask = True
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# Copied from transformers.models.deberta.modeling_deberta.get_mask
|
| 153 |
+
def get_mask(input, local_context):
|
| 154 |
+
if not isinstance(local_context, DropoutContext):
|
| 155 |
+
dropout = local_context
|
| 156 |
+
mask = None
|
| 157 |
+
else:
|
| 158 |
+
dropout = local_context.dropout
|
| 159 |
+
dropout *= local_context.scale
|
| 160 |
+
mask = local_context.mask if local_context.reuse_mask else None
|
| 161 |
+
|
| 162 |
+
if dropout > 0 and mask is None:
|
| 163 |
+
mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).to(torch.bool)
|
| 164 |
+
|
| 165 |
+
if isinstance(local_context, DropoutContext):
|
| 166 |
+
if local_context.mask is None:
|
| 167 |
+
local_context.mask = mask
|
| 168 |
+
|
| 169 |
+
return mask, dropout
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# Copied from transformers.models.deberta.modeling_deberta.XDropout
|
| 173 |
+
class XDropout(torch.autograd.Function):
|
| 174 |
+
"""Optimized dropout function to save computation and memory by using mask operation instead of multiplication."""
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def forward(ctx, input, local_ctx):
|
| 178 |
+
mask, dropout = get_mask(input, local_ctx)
|
| 179 |
+
ctx.scale = 1.0 / (1 - dropout)
|
| 180 |
+
if dropout > 0:
|
| 181 |
+
ctx.save_for_backward(mask)
|
| 182 |
+
return input.masked_fill(mask, 0) * ctx.scale
|
| 183 |
+
else:
|
| 184 |
+
return input
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def backward(ctx, grad_output):
|
| 188 |
+
if ctx.scale > 1:
|
| 189 |
+
(mask,) = ctx.saved_tensors
|
| 190 |
+
return grad_output.masked_fill(mask, 0) * ctx.scale, None
|
| 191 |
+
else:
|
| 192 |
+
return grad_output, None
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def symbolic(g: torch._C.Graph, input: torch._C.Value, local_ctx: Union[float, DropoutContext]) -> torch._C.Value:
|
| 196 |
+
from torch.onnx import symbolic_opset12
|
| 197 |
+
|
| 198 |
+
dropout_p = local_ctx
|
| 199 |
+
if isinstance(local_ctx, DropoutContext):
|
| 200 |
+
dropout_p = local_ctx.dropout
|
| 201 |
+
# StableDropout only calls this function when training.
|
| 202 |
+
train = True
|
| 203 |
+
# TODO: We should check if the opset_version being used to export
|
| 204 |
+
# is > 12 here, but there's no good way to do that. As-is, if the
|
| 205 |
+
# opset_version < 12, export will fail with a CheckerError.
|
| 206 |
+
# Once https://github.com/pytorch/pytorch/issues/78391 is fixed, do something like:
|
| 207 |
+
# if opset_version < 12:
|
| 208 |
+
# return torch.onnx.symbolic_opset9.dropout(g, input, dropout_p, train)
|
| 209 |
+
return symbolic_opset12.dropout(g, input, dropout_p, train)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# Copied from transformers.models.deberta.modeling_deberta.StableDropout
|
| 213 |
+
class StableDropout(nn.Module):
|
| 214 |
+
"""
|
| 215 |
+
Optimized dropout module for stabilizing the training
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
drop_prob (float): the dropout probabilities
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def __init__(self, drop_prob):
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.drop_prob = drop_prob
|
| 224 |
+
self.count = 0
|
| 225 |
+
self.context_stack = None
|
| 226 |
+
|
| 227 |
+
def forward(self, x):
|
| 228 |
+
"""
|
| 229 |
+
Call the module
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
x (`torch.tensor`): The input tensor to apply dropout
|
| 233 |
+
"""
|
| 234 |
+
if self.training and self.drop_prob > 0:
|
| 235 |
+
return XDropout.apply(x, self.get_context())
|
| 236 |
+
return x
|
| 237 |
+
|
| 238 |
+
def clear_context(self):
|
| 239 |
+
self.count = 0
|
| 240 |
+
self.context_stack = None
|
| 241 |
+
|
| 242 |
+
def init_context(self, reuse_mask=True, scale=1):
|
| 243 |
+
if self.context_stack is None:
|
| 244 |
+
self.context_stack = []
|
| 245 |
+
self.count = 0
|
| 246 |
+
for c in self.context_stack:
|
| 247 |
+
c.reuse_mask = reuse_mask
|
| 248 |
+
c.scale = scale
|
| 249 |
+
|
| 250 |
+
def get_context(self):
|
| 251 |
+
if self.context_stack is not None:
|
| 252 |
+
if self.count >= len(self.context_stack):
|
| 253 |
+
self.context_stack.append(DropoutContext())
|
| 254 |
+
ctx = self.context_stack[self.count]
|
| 255 |
+
ctx.dropout = self.drop_prob
|
| 256 |
+
self.count += 1
|
| 257 |
+
return ctx
|
| 258 |
+
else:
|
| 259 |
+
return self.drop_prob
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNorm
|
| 263 |
+
class DebertaV2SelfOutput(nn.Module):
|
| 264 |
+
def __init__(self, config):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 267 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 268 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
| 269 |
+
|
| 270 |
+
def forward(self, hidden_states, input_tensor):
|
| 271 |
+
hidden_states = self.dense(hidden_states)
|
| 272 |
+
hidden_states = self.dropout(hidden_states)
|
| 273 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 274 |
+
return hidden_states
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2
|
| 278 |
+
class DebertaV2Attention(nn.Module):
|
| 279 |
+
def __init__(self, config):
|
| 280 |
+
super().__init__()
|
| 281 |
+
self.self = DisentangledSelfAttention(config)
|
| 282 |
+
self.output = DebertaV2SelfOutput(config)
|
| 283 |
+
self.config = config
|
| 284 |
+
|
| 285 |
+
def forward(
|
| 286 |
+
self,
|
| 287 |
+
hidden_states,
|
| 288 |
+
attention_mask,
|
| 289 |
+
output_attentions=False,
|
| 290 |
+
query_states=None,
|
| 291 |
+
relative_pos=None,
|
| 292 |
+
rel_embeddings=None,
|
| 293 |
+
):
|
| 294 |
+
self_output = self.self(
|
| 295 |
+
hidden_states,
|
| 296 |
+
attention_mask,
|
| 297 |
+
output_attentions,
|
| 298 |
+
query_states=query_states,
|
| 299 |
+
relative_pos=relative_pos,
|
| 300 |
+
rel_embeddings=rel_embeddings,
|
| 301 |
+
)
|
| 302 |
+
if output_attentions:
|
| 303 |
+
self_output, att_matrix = self_output
|
| 304 |
+
if query_states is None:
|
| 305 |
+
query_states = hidden_states
|
| 306 |
+
attention_output = self.output(self_output, query_states)
|
| 307 |
+
|
| 308 |
+
if output_attentions:
|
| 309 |
+
return (attention_output, att_matrix)
|
| 310 |
+
else:
|
| 311 |
+
return attention_output
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2
|
| 315 |
+
class DebertaV2Intermediate(nn.Module):
|
| 316 |
+
def __init__(self, config):
|
| 317 |
+
super().__init__()
|
| 318 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 319 |
+
if isinstance(config.hidden_act, str):
|
| 320 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 321 |
+
else:
|
| 322 |
+
self.intermediate_act_fn = config.hidden_act
|
| 323 |
+
|
| 324 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 325 |
+
hidden_states = self.dense(hidden_states)
|
| 326 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 327 |
+
return hidden_states
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNorm
|
| 331 |
+
class DebertaV2Output(nn.Module):
|
| 332 |
+
def __init__(self, config):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 335 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 336 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
| 337 |
+
self.config = config
|
| 338 |
+
|
| 339 |
+
def forward(self, hidden_states, input_tensor):
|
| 340 |
+
hidden_states = self.dense(hidden_states)
|
| 341 |
+
hidden_states = self.dropout(hidden_states)
|
| 342 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 343 |
+
return hidden_states
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2
|
| 347 |
+
class DebertaV2Layer(nn.Module):
|
| 348 |
+
def __init__(self, config):
|
| 349 |
+
super().__init__()
|
| 350 |
+
self.attention = DebertaV2Attention(config)
|
| 351 |
+
self.intermediate = DebertaV2Intermediate(config)
|
| 352 |
+
self.output = DebertaV2Output(config)
|
| 353 |
+
|
| 354 |
+
def forward(
|
| 355 |
+
self,
|
| 356 |
+
hidden_states,
|
| 357 |
+
attention_mask,
|
| 358 |
+
query_states=None,
|
| 359 |
+
relative_pos=None,
|
| 360 |
+
rel_embeddings=None,
|
| 361 |
+
output_attentions=False,
|
| 362 |
+
):
|
| 363 |
+
attention_output = self.attention(
|
| 364 |
+
hidden_states,
|
| 365 |
+
attention_mask,
|
| 366 |
+
output_attentions=output_attentions,
|
| 367 |
+
query_states=query_states,
|
| 368 |
+
relative_pos=relative_pos,
|
| 369 |
+
rel_embeddings=rel_embeddings,
|
| 370 |
+
)
|
| 371 |
+
if output_attentions:
|
| 372 |
+
attention_output, att_matrix = attention_output
|
| 373 |
+
intermediate_output = self.intermediate(attention_output)
|
| 374 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 375 |
+
if output_attentions:
|
| 376 |
+
return (layer_output, att_matrix)
|
| 377 |
+
else:
|
| 378 |
+
return layer_output
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class ConvLayer(nn.Module):
|
| 382 |
+
def __init__(self, config):
|
| 383 |
+
super().__init__()
|
| 384 |
+
kernel_size = getattr(config, "conv_kernel_size", 3)
|
| 385 |
+
groups = getattr(config, "conv_groups", 1)
|
| 386 |
+
self.conv_act = getattr(config, "conv_act", "tanh")
|
| 387 |
+
self.conv = nn.Conv1d(
|
| 388 |
+
config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups
|
| 389 |
+
)
|
| 390 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 391 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
| 392 |
+
self.config = config
|
| 393 |
+
|
| 394 |
+
def forward(self, hidden_states, residual_states, input_mask):
|
| 395 |
+
out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous()
|
| 396 |
+
rmask = (1 - input_mask).bool()
|
| 397 |
+
out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0)
|
| 398 |
+
out = ACT2FN[self.conv_act](self.dropout(out))
|
| 399 |
+
|
| 400 |
+
layer_norm_input = residual_states + out
|
| 401 |
+
output = self.LayerNorm(layer_norm_input).to(layer_norm_input)
|
| 402 |
+
|
| 403 |
+
if input_mask is None:
|
| 404 |
+
output_states = output
|
| 405 |
+
else:
|
| 406 |
+
if input_mask.dim() != layer_norm_input.dim():
|
| 407 |
+
if input_mask.dim() == 4:
|
| 408 |
+
input_mask = input_mask.squeeze(1).squeeze(1)
|
| 409 |
+
input_mask = input_mask.unsqueeze(2)
|
| 410 |
+
|
| 411 |
+
input_mask = input_mask.to(output.dtype)
|
| 412 |
+
output_states = output * input_mask
|
| 413 |
+
|
| 414 |
+
return output_states
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class DebertaV2Encoder(nn.Module):
|
| 418 |
+
"""Modified BertEncoder with relative position bias support"""
|
| 419 |
+
|
| 420 |
+
def __init__(self, config):
|
| 421 |
+
super().__init__()
|
| 422 |
+
|
| 423 |
+
self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)])
|
| 424 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
| 425 |
+
|
| 426 |
+
if self.relative_attention:
|
| 427 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
| 428 |
+
if self.max_relative_positions < 1:
|
| 429 |
+
self.max_relative_positions = config.max_position_embeddings
|
| 430 |
+
|
| 431 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
| 432 |
+
pos_ebd_size = self.max_relative_positions * 2
|
| 433 |
+
|
| 434 |
+
if self.position_buckets > 0:
|
| 435 |
+
pos_ebd_size = self.position_buckets * 2
|
| 436 |
+
|
| 437 |
+
self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size)
|
| 438 |
+
|
| 439 |
+
self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]
|
| 440 |
+
|
| 441 |
+
if "layer_norm" in self.norm_rel_ebd:
|
| 442 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
|
| 443 |
+
|
| 444 |
+
self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None
|
| 445 |
+
self.gradient_checkpointing = False
|
| 446 |
+
|
| 447 |
+
def get_rel_embedding(self):
|
| 448 |
+
rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None
|
| 449 |
+
if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd):
|
| 450 |
+
rel_embeddings = self.LayerNorm(rel_embeddings)
|
| 451 |
+
return rel_embeddings
|
| 452 |
+
|
| 453 |
+
def get_attention_mask(self, attention_mask):
|
| 454 |
+
if attention_mask.dim() <= 2:
|
| 455 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 456 |
+
attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1)
|
| 457 |
+
attention_mask = attention_mask.triu(diagonal=-510).tril(diagonal=510)
|
| 458 |
+
attention_mask[:, :, :, 0] = 1
|
| 459 |
+
attention_mask[:, :, :, -1] = 1
|
| 460 |
+
elif attention_mask.dim() == 3:
|
| 461 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 462 |
+
|
| 463 |
+
return attention_mask
|
| 464 |
+
|
| 465 |
+
def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None):
|
| 466 |
+
if self.relative_attention and relative_pos is None:
|
| 467 |
+
q = query_states.size(-2) if query_states is not None else hidden_states.size(-2)
|
| 468 |
+
relative_pos = build_relative_position(
|
| 469 |
+
q,
|
| 470 |
+
hidden_states.size(-2),
|
| 471 |
+
bucket_size=self.position_buckets,
|
| 472 |
+
max_position=self.max_relative_positions,
|
| 473 |
+
device=hidden_states.device,
|
| 474 |
+
)
|
| 475 |
+
return relative_pos
|
| 476 |
+
|
| 477 |
+
def forward(
|
| 478 |
+
self,
|
| 479 |
+
hidden_states,
|
| 480 |
+
attention_mask,
|
| 481 |
+
output_hidden_states=True,
|
| 482 |
+
output_attentions=False,
|
| 483 |
+
query_states=None,
|
| 484 |
+
relative_pos=None,
|
| 485 |
+
return_dict=True,
|
| 486 |
+
):
|
| 487 |
+
if attention_mask.dim() <= 2:
|
| 488 |
+
input_mask = attention_mask
|
| 489 |
+
else:
|
| 490 |
+
input_mask = attention_mask.sum(-2) > 0
|
| 491 |
+
attention_mask = self.get_attention_mask(attention_mask)
|
| 492 |
+
relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)
|
| 493 |
+
|
| 494 |
+
all_hidden_states = () if output_hidden_states else None
|
| 495 |
+
all_attentions = () if output_attentions else None
|
| 496 |
+
|
| 497 |
+
if isinstance(hidden_states, Sequence):
|
| 498 |
+
next_kv = hidden_states[0]
|
| 499 |
+
else:
|
| 500 |
+
next_kv = hidden_states
|
| 501 |
+
rel_embeddings = self.get_rel_embedding()
|
| 502 |
+
output_states = next_kv
|
| 503 |
+
for i, layer_module in enumerate(self.layer):
|
| 504 |
+
if output_hidden_states:
|
| 505 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
| 506 |
+
|
| 507 |
+
if self.gradient_checkpointing and self.training:
|
| 508 |
+
output_states = self._gradient_checkpointing_func(
|
| 509 |
+
layer_module.__call__,
|
| 510 |
+
next_kv,
|
| 511 |
+
attention_mask,
|
| 512 |
+
query_states,
|
| 513 |
+
relative_pos,
|
| 514 |
+
rel_embeddings,
|
| 515 |
+
output_attentions,
|
| 516 |
+
)
|
| 517 |
+
else:
|
| 518 |
+
output_states = layer_module(
|
| 519 |
+
next_kv,
|
| 520 |
+
attention_mask,
|
| 521 |
+
query_states=query_states,
|
| 522 |
+
relative_pos=relative_pos,
|
| 523 |
+
rel_embeddings=rel_embeddings,
|
| 524 |
+
output_attentions=output_attentions,
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
if output_attentions:
|
| 528 |
+
output_states, att_m = output_states
|
| 529 |
+
|
| 530 |
+
if i == 0 and self.conv is not None:
|
| 531 |
+
output_states = self.conv(hidden_states, output_states, input_mask)
|
| 532 |
+
|
| 533 |
+
if query_states is not None:
|
| 534 |
+
query_states = output_states
|
| 535 |
+
if isinstance(hidden_states, Sequence):
|
| 536 |
+
next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None
|
| 537 |
+
else:
|
| 538 |
+
next_kv = output_states
|
| 539 |
+
|
| 540 |
+
if output_attentions:
|
| 541 |
+
all_attentions = all_attentions + (att_m,)
|
| 542 |
+
|
| 543 |
+
if output_hidden_states:
|
| 544 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
| 545 |
+
|
| 546 |
+
if not return_dict:
|
| 547 |
+
return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None)
|
| 548 |
+
return BaseModelOutput(
|
| 549 |
+
last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def make_log_bucket_position(relative_pos, bucket_size, max_position):
|
| 554 |
+
sign = torch.sign(relative_pos)
|
| 555 |
+
mid = bucket_size // 2
|
| 556 |
+
abs_pos = torch.where(
|
| 557 |
+
(relative_pos < mid) & (relative_pos > -mid),
|
| 558 |
+
torch.tensor(mid - 1).type_as(relative_pos),
|
| 559 |
+
torch.abs(relative_pos),
|
| 560 |
+
)
|
| 561 |
+
log_pos = (
|
| 562 |
+
torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid
|
| 563 |
+
)
|
| 564 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign)
|
| 565 |
+
bucket_pos = bucket_pos.clamp(min=-bucket_size+1, max=bucket_size-1)
|
| 566 |
+
return bucket_pos
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1, device=None):
|
| 570 |
+
"""
|
| 571 |
+
Build relative position according to the query and key
|
| 572 |
+
|
| 573 |
+
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
|
| 574 |
+
\\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q -
|
| 575 |
+
P_k\\)
|
| 576 |
+
|
| 577 |
+
Args:
|
| 578 |
+
query_size (int): the length of query
|
| 579 |
+
key_size (int): the length of key
|
| 580 |
+
bucket_size (int): the size of position bucket
|
| 581 |
+
max_position (int): the maximum allowed absolute position
|
| 582 |
+
device (`torch.device`): the device on which tensors will be created.
|
| 583 |
+
|
| 584 |
+
Return:
|
| 585 |
+
`torch.LongTensor`: A tensor with shape [1, query_size, key_size]
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
q_ids = torch.arange(0, query_size, device=device)
|
| 589 |
+
k_ids = torch.arange(0, key_size, device=device)
|
| 590 |
+
rel_pos_ids = q_ids[:, None] - k_ids[None, :]
|
| 591 |
+
if bucket_size > 0 and max_position > 0:
|
| 592 |
+
rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
|
| 593 |
+
rel_pos_ids = rel_pos_ids.to(torch.long)
|
| 594 |
+
rel_pos_ids = rel_pos_ids[:query_size, :]
|
| 595 |
+
rel_pos_ids = rel_pos_ids.unsqueeze(0)
|
| 596 |
+
return rel_pos_ids
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
@torch.jit.script
|
| 600 |
+
# Copied from transformers.models.deberta.modeling_deberta.c2p_dynamic_expand
|
| 601 |
+
def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos):
|
| 602 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)])
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
@torch.jit.script
|
| 606 |
+
# Copied from transformers.models.deberta.modeling_deberta.p2c_dynamic_expand
|
| 607 |
+
def p2c_dynamic_expand(c2p_pos, query_layer, key_layer):
|
| 608 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)])
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
@torch.jit.script
|
| 612 |
+
# Copied from transformers.models.deberta.modeling_deberta.pos_dynamic_expand
|
| 613 |
+
def pos_dynamic_expand(pos_index, p2c_att, key_layer):
|
| 614 |
+
return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2)))
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
class DisentangledSelfAttention(nn.Module):
|
| 618 |
+
"""
|
| 619 |
+
Disentangled self-attention module
|
| 620 |
+
|
| 621 |
+
Parameters:
|
| 622 |
+
config (`DebertaV2Config`):
|
| 623 |
+
A model config class instance with the configuration to build a new model. The schema is similar to
|
| 624 |
+
*BertConfig*, for more details, please refer [`DebertaV2Config`]
|
| 625 |
+
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
def __init__(self, config):
|
| 629 |
+
super().__init__()
|
| 630 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 631 |
+
raise ValueError(
|
| 632 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 633 |
+
f"heads ({config.num_attention_heads})"
|
| 634 |
+
)
|
| 635 |
+
self.num_attention_heads = config.num_attention_heads
|
| 636 |
+
_attention_head_size = config.hidden_size // config.num_attention_heads
|
| 637 |
+
self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size)
|
| 638 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 639 |
+
self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 640 |
+
self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 641 |
+
self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 642 |
+
|
| 643 |
+
self.share_att_key = getattr(config, "share_att_key", False)
|
| 644 |
+
self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else []
|
| 645 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
| 646 |
+
|
| 647 |
+
if self.relative_attention:
|
| 648 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
| 649 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
| 650 |
+
if self.max_relative_positions < 1:
|
| 651 |
+
self.max_relative_positions = config.max_position_embeddings
|
| 652 |
+
self.pos_ebd_size = self.max_relative_positions
|
| 653 |
+
if self.position_buckets > 0:
|
| 654 |
+
self.pos_ebd_size = self.position_buckets
|
| 655 |
+
|
| 656 |
+
self.pos_dropout = StableDropout(config.hidden_dropout_prob)
|
| 657 |
+
|
| 658 |
+
if not self.share_att_key:
|
| 659 |
+
if "c2p" in self.pos_att_type:
|
| 660 |
+
self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 661 |
+
if "p2c" in self.pos_att_type:
|
| 662 |
+
self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size)
|
| 663 |
+
|
| 664 |
+
self.dropout = StableDropout(config.attention_probs_dropout_prob)
|
| 665 |
+
|
| 666 |
+
def transpose_for_scores(self, x, attention_heads):
|
| 667 |
+
new_x_shape = x.size()[:-1] + (attention_heads, -1)
|
| 668 |
+
x = x.view(new_x_shape)
|
| 669 |
+
return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1))
|
| 670 |
+
|
| 671 |
+
def forward(
|
| 672 |
+
self,
|
| 673 |
+
hidden_states,
|
| 674 |
+
attention_mask,
|
| 675 |
+
output_attentions=False,
|
| 676 |
+
query_states=None,
|
| 677 |
+
relative_pos=None,
|
| 678 |
+
rel_embeddings=None,
|
| 679 |
+
):
|
| 680 |
+
"""
|
| 681 |
+
Call the module
|
| 682 |
+
|
| 683 |
+
Args:
|
| 684 |
+
hidden_states (`torch.FloatTensor`):
|
| 685 |
+
Input states to the module usually the output from previous layer, it will be the Q,K and V in
|
| 686 |
+
*Attention(Q,K,V)*
|
| 687 |
+
|
| 688 |
+
attention_mask (`torch.BoolTensor`):
|
| 689 |
+
An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
|
| 690 |
+
sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
|
| 691 |
+
th token.
|
| 692 |
+
|
| 693 |
+
output_attentions (`bool`, optional):
|
| 694 |
+
Whether return the attention matrix.
|
| 695 |
+
|
| 696 |
+
query_states (`torch.FloatTensor`, optional):
|
| 697 |
+
The *Q* state in *Attention(Q,K,V)*.
|
| 698 |
+
|
| 699 |
+
relative_pos (`torch.LongTensor`):
|
| 700 |
+
The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
|
| 701 |
+
values ranging in [*-max_relative_positions*, *max_relative_positions*].
|
| 702 |
+
|
| 703 |
+
rel_embeddings (`torch.FloatTensor`):
|
| 704 |
+
The embedding of relative distances. It's a tensor of shape [\\(2 \\times
|
| 705 |
+
\\text{max_relative_positions}\\), *hidden_size*].
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
"""
|
| 709 |
+
if query_states is None:
|
| 710 |
+
query_states = hidden_states
|
| 711 |
+
query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads)
|
| 712 |
+
key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
|
| 713 |
+
value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads)
|
| 714 |
+
|
| 715 |
+
rel_att = None
|
| 716 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 717 |
+
scale_factor = 1
|
| 718 |
+
if "c2p" in self.pos_att_type:
|
| 719 |
+
scale_factor += 1
|
| 720 |
+
if "p2c" in self.pos_att_type:
|
| 721 |
+
scale_factor += 1
|
| 722 |
+
scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
|
| 723 |
+
attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2) / scale.to(dtype=query_layer.dtype))
|
| 724 |
+
if self.relative_attention:
|
| 725 |
+
rel_embeddings = self.pos_dropout(rel_embeddings)
|
| 726 |
+
rel_att = self.disentangled_attention_bias(
|
| 727 |
+
query_layer, key_layer, relative_pos, rel_embeddings, scale_factor
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
if rel_att is not None:
|
| 731 |
+
attention_scores = attention_scores + rel_att
|
| 732 |
+
attention_scores = attention_scores
|
| 733 |
+
attention_scores = attention_scores.view(
|
| 734 |
+
-1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1)
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
# bsz x height x length x dimension
|
| 738 |
+
attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1)
|
| 739 |
+
attention_probs = self.dropout(attention_probs)
|
| 740 |
+
context_layer = torch.bmm(
|
| 741 |
+
attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer
|
| 742 |
+
)
|
| 743 |
+
context_layer = (
|
| 744 |
+
context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1))
|
| 745 |
+
.permute(0, 2, 1, 3)
|
| 746 |
+
.contiguous()
|
| 747 |
+
)
|
| 748 |
+
new_context_layer_shape = context_layer.size()[:-2] + (-1,)
|
| 749 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 750 |
+
if output_attentions:
|
| 751 |
+
return (context_layer, attention_probs)
|
| 752 |
+
else:
|
| 753 |
+
return context_layer
|
| 754 |
+
|
| 755 |
+
def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor):
|
| 756 |
+
if relative_pos is None:
|
| 757 |
+
q = query_layer.size(-2)
|
| 758 |
+
relative_pos = build_relative_position(
|
| 759 |
+
q,
|
| 760 |
+
key_layer.size(-2),
|
| 761 |
+
bucket_size=self.position_buckets,
|
| 762 |
+
max_position=self.max_relative_positions,
|
| 763 |
+
device=query_layer.device,
|
| 764 |
+
)
|
| 765 |
+
if relative_pos.dim() == 2:
|
| 766 |
+
relative_pos = relative_pos.unsqueeze(0).unsqueeze(0)
|
| 767 |
+
elif relative_pos.dim() == 3:
|
| 768 |
+
relative_pos = relative_pos.unsqueeze(1)
|
| 769 |
+
# bsz x height x query x key
|
| 770 |
+
elif relative_pos.dim() != 4:
|
| 771 |
+
raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
|
| 772 |
+
|
| 773 |
+
att_span = self.pos_ebd_size
|
| 774 |
+
relative_pos = relative_pos.long().to(query_layer.device)
|
| 775 |
+
|
| 776 |
+
rel_embeddings = rel_embeddings[0 : att_span * 2, :].unsqueeze(0)
|
| 777 |
+
if self.share_att_key:
|
| 778 |
+
pos_query_layer = self.transpose_for_scores(
|
| 779 |
+
self.query_proj(rel_embeddings), self.num_attention_heads
|
| 780 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1)
|
| 781 |
+
pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat(
|
| 782 |
+
query_layer.size(0) // self.num_attention_heads, 1, 1
|
| 783 |
+
)
|
| 784 |
+
else:
|
| 785 |
+
if "c2p" in self.pos_att_type:
|
| 786 |
+
pos_key_layer = self.transpose_for_scores(
|
| 787 |
+
self.pos_key_proj(rel_embeddings), self.num_attention_heads
|
| 788 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
| 789 |
+
if "p2c" in self.pos_att_type:
|
| 790 |
+
pos_query_layer = self.transpose_for_scores(
|
| 791 |
+
self.pos_query_proj(rel_embeddings), self.num_attention_heads
|
| 792 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
| 793 |
+
|
| 794 |
+
score = 0
|
| 795 |
+
# content->position
|
| 796 |
+
if "c2p" in self.pos_att_type:
|
| 797 |
+
scale = torch.sqrt(torch.tensor(pos_key_layer.size(-1), dtype=torch.float) * scale_factor)
|
| 798 |
+
c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2))
|
| 799 |
+
c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
|
| 800 |
+
c2p_att = torch.gather(
|
| 801 |
+
c2p_att,
|
| 802 |
+
dim=-1,
|
| 803 |
+
index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]),
|
| 804 |
+
)
|
| 805 |
+
score += c2p_att / scale.to(dtype=c2p_att.dtype)
|
| 806 |
+
|
| 807 |
+
# position->content
|
| 808 |
+
if "p2c" in self.pos_att_type:
|
| 809 |
+
scale = torch.sqrt(torch.tensor(pos_query_layer.size(-1), dtype=torch.float) * scale_factor)
|
| 810 |
+
if key_layer.size(-2) != query_layer.size(-2):
|
| 811 |
+
r_pos = build_relative_position(
|
| 812 |
+
key_layer.size(-2),
|
| 813 |
+
key_layer.size(-2),
|
| 814 |
+
bucket_size=self.position_buckets,
|
| 815 |
+
max_position=self.max_relative_positions,
|
| 816 |
+
device=query_layer.device,
|
| 817 |
+
)
|
| 818 |
+
r_pos = r_pos.unsqueeze(0)
|
| 819 |
+
else:
|
| 820 |
+
r_pos = relative_pos
|
| 821 |
+
|
| 822 |
+
p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1)
|
| 823 |
+
p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2))
|
| 824 |
+
p2c_att = torch.gather(
|
| 825 |
+
p2c_att,
|
| 826 |
+
dim=-1,
|
| 827 |
+
index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]),
|
| 828 |
+
).transpose(-1, -2)
|
| 829 |
+
score += p2c_att / scale.to(dtype=p2c_att.dtype)
|
| 830 |
+
|
| 831 |
+
return score
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNorm
|
| 835 |
+
class DebertaV2Embeddings(nn.Module):
|
| 836 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 837 |
+
|
| 838 |
+
def __init__(self, config):
|
| 839 |
+
super().__init__()
|
| 840 |
+
pad_token_id = getattr(config, "pad_token_id", 0)
|
| 841 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 842 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)
|
| 843 |
+
|
| 844 |
+
self.position_biased_input = getattr(config, "position_biased_input", True)
|
| 845 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)
|
| 846 |
+
|
| 847 |
+
if config.type_vocab_size > 0:
|
| 848 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)
|
| 849 |
+
|
| 850 |
+
if self.embedding_size != config.hidden_size:
|
| 851 |
+
self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False)
|
| 852 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 853 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
| 854 |
+
self.config = config
|
| 855 |
+
|
| 856 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 857 |
+
self.register_buffer(
|
| 858 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None):
|
| 862 |
+
if input_ids is not None:
|
| 863 |
+
input_shape = input_ids.size()
|
| 864 |
+
else:
|
| 865 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 866 |
+
|
| 867 |
+
seq_length = input_shape[1]
|
| 868 |
+
|
| 869 |
+
if position_ids is None:
|
| 870 |
+
if seq_length > self.position_ids.size(1):
|
| 871 |
+
position_ids = torch.cat([
|
| 872 |
+
torch.zeros(1, seq_length - self.position_ids.size(1), dtype=self.position_ids.dtype, device=self.position_ids.device),
|
| 873 |
+
self.position_ids
|
| 874 |
+
], dim=1)
|
| 875 |
+
else:
|
| 876 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 877 |
+
|
| 878 |
+
if token_type_ids is None:
|
| 879 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 880 |
+
|
| 881 |
+
if inputs_embeds is None:
|
| 882 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 883 |
+
|
| 884 |
+
if self.position_embeddings is not None:
|
| 885 |
+
position_embeddings = self.position_embeddings(position_ids.long())
|
| 886 |
+
else:
|
| 887 |
+
position_embeddings = torch.zeros_like(inputs_embeds)
|
| 888 |
+
|
| 889 |
+
embeddings = inputs_embeds
|
| 890 |
+
if self.position_biased_input:
|
| 891 |
+
embeddings += position_embeddings
|
| 892 |
+
if self.config.type_vocab_size > 0:
|
| 893 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 894 |
+
embeddings += token_type_embeddings
|
| 895 |
+
|
| 896 |
+
if self.embedding_size != self.config.hidden_size:
|
| 897 |
+
embeddings = self.embed_proj(embeddings)
|
| 898 |
+
|
| 899 |
+
embeddings = self.LayerNorm(embeddings)
|
| 900 |
+
|
| 901 |
+
if mask is not None:
|
| 902 |
+
if mask.dim() != embeddings.dim():
|
| 903 |
+
if mask.dim() == 4:
|
| 904 |
+
mask = mask.squeeze(1).squeeze(1)
|
| 905 |
+
mask = mask.unsqueeze(2)
|
| 906 |
+
mask = mask.to(embeddings.dtype)
|
| 907 |
+
|
| 908 |
+
embeddings = embeddings * mask
|
| 909 |
+
|
| 910 |
+
embeddings = self.dropout(embeddings)
|
| 911 |
+
return embeddings, position_embeddings
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaPreTrainedModel with Deberta->DebertaV2
|
| 915 |
+
class DebertaV2PreTrainedModel(PreTrainedModel):
|
| 916 |
+
"""
|
| 917 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 918 |
+
models.
|
| 919 |
+
"""
|
| 920 |
+
|
| 921 |
+
config_class = DebertaV2Config
|
| 922 |
+
base_model_prefix = "deberta"
|
| 923 |
+
supports_gradient_checkpointing = True
|
| 924 |
+
|
| 925 |
+
def _init_weights(self, module):
|
| 926 |
+
"""Initialize the weights."""
|
| 927 |
+
if isinstance(module, nn.Linear):
|
| 928 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 929 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 930 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 931 |
+
if module.bias is not None:
|
| 932 |
+
module.bias.data.zero_()
|
| 933 |
+
elif isinstance(module, nn.Embedding):
|
| 934 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 935 |
+
if module.padding_idx is not None:
|
| 936 |
+
module.weight.data[module.padding_idx].zero_()
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
DEBERTA_START_DOCSTRING = r"""
|
| 940 |
+
The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled
|
| 941 |
+
Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build
|
| 942 |
+
on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two
|
| 943 |
+
improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data.
|
| 944 |
+
|
| 945 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 946 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 947 |
+
and behavior.
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
Parameters:
|
| 951 |
+
config ([`DebertaV2Config`]): Model configuration class with all the parameters of the model.
|
| 952 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 953 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 954 |
+
"""
|
| 955 |
+
|
| 956 |
+
DEBERTA_INPUTS_DOCSTRING = r"""
|
| 957 |
+
Args:
|
| 958 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 959 |
+
Indices of input sequence tokens in the vocabulary.
|
| 960 |
+
|
| 961 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 962 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 963 |
+
|
| 964 |
+
[What are input IDs?](../glossary#input-ids)
|
| 965 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 966 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 967 |
+
|
| 968 |
+
- 1 for tokens that are **not masked**,
|
| 969 |
+
- 0 for tokens that are **masked**.
|
| 970 |
+
|
| 971 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 972 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 973 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 974 |
+
1]`:
|
| 975 |
+
|
| 976 |
+
- 0 corresponds to a *sentence A* token,
|
| 977 |
+
- 1 corresponds to a *sentence B* token.
|
| 978 |
+
|
| 979 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 980 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 981 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 982 |
+
config.max_position_embeddings - 1]`.
|
| 983 |
+
|
| 984 |
+
[What are position IDs?](../glossary#position-ids)
|
| 985 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 986 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 987 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 988 |
+
model's internal embedding lookup matrix.
|
| 989 |
+
output_attentions (`bool`, *optional*):
|
| 990 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 991 |
+
tensors for more detail.
|
| 992 |
+
output_hidden_states (`bool`, *optional*):
|
| 993 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 994 |
+
more detail.
|
| 995 |
+
return_dict (`bool`, *optional*):
|
| 996 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 997 |
+
"""
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
@add_start_docstrings(
|
| 1001 |
+
"The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1002 |
+
DEBERTA_START_DOCSTRING,
|
| 1003 |
+
)
|
| 1004 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2
|
| 1005 |
+
class DebertaV2Model(DebertaV2PreTrainedModel):
|
| 1006 |
+
def __init__(self, config):
|
| 1007 |
+
super().__init__(config)
|
| 1008 |
+
|
| 1009 |
+
self.embeddings = DebertaV2Embeddings(config)
|
| 1010 |
+
self.encoder = DebertaV2Encoder(config)
|
| 1011 |
+
self.z_steps = 4
|
| 1012 |
+
self.config = config
|
| 1013 |
+
# Initialize weights and apply final processing
|
| 1014 |
+
self.post_init()
|
| 1015 |
+
|
| 1016 |
+
def get_input_embeddings(self):
|
| 1017 |
+
return self.embeddings.word_embeddings
|
| 1018 |
+
|
| 1019 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1020 |
+
self.embeddings.word_embeddings = new_embeddings
|
| 1021 |
+
|
| 1022 |
+
def _prune_heads(self, heads_to_prune):
|
| 1023 |
+
"""
|
| 1024 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1025 |
+
class PreTrainedModel
|
| 1026 |
+
"""
|
| 1027 |
+
raise NotImplementedError("The prune function is not implemented in DeBERTa model.")
|
| 1028 |
+
|
| 1029 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1030 |
+
@add_code_sample_docstrings(
|
| 1031 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1032 |
+
output_type=BaseModelOutput,
|
| 1033 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1034 |
+
)
|
| 1035 |
+
def forward(
|
| 1036 |
+
self,
|
| 1037 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1038 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1039 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1040 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1041 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1042 |
+
output_attentions: Optional[bool] = None,
|
| 1043 |
+
output_hidden_states: Optional[bool] = None,
|
| 1044 |
+
return_dict: Optional[bool] = None,
|
| 1045 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 1046 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1047 |
+
output_hidden_states = (
|
| 1048 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1049 |
+
)
|
| 1050 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1051 |
+
|
| 1052 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1053 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1054 |
+
elif input_ids is not None:
|
| 1055 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1056 |
+
input_shape = input_ids.size()
|
| 1057 |
+
elif inputs_embeds is not None:
|
| 1058 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1059 |
+
else:
|
| 1060 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1061 |
+
|
| 1062 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1063 |
+
|
| 1064 |
+
if attention_mask is None:
|
| 1065 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 1066 |
+
|
| 1067 |
+
if token_type_ids is None:
|
| 1068 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1069 |
+
|
| 1070 |
+
embedding_output, position_embeddings = self.embeddings(
|
| 1071 |
+
input_ids=input_ids,
|
| 1072 |
+
token_type_ids=token_type_ids,
|
| 1073 |
+
position_ids=position_ids,
|
| 1074 |
+
mask=attention_mask,
|
| 1075 |
+
inputs_embeds=inputs_embeds,
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
encoder_outputs = self.encoder(
|
| 1079 |
+
embedding_output,
|
| 1080 |
+
attention_mask,
|
| 1081 |
+
output_hidden_states=True,
|
| 1082 |
+
output_attentions=output_attentions,
|
| 1083 |
+
return_dict=return_dict,
|
| 1084 |
+
)
|
| 1085 |
+
encoded_layers = list(encoder_outputs[1])
|
| 1086 |
+
|
| 1087 |
+
# print(self.z_steps)
|
| 1088 |
+
|
| 1089 |
+
if self.z_steps > 0:
|
| 1090 |
+
hidden_states = encoded_layers[-2]
|
| 1091 |
+
layers = [self.encoder.layer[-1] for _ in range(self.z_steps)]
|
| 1092 |
+
query_states = position_embeddings + encoded_layers[-2]
|
| 1093 |
+
rel_embeddings = self.encoder.get_rel_embedding()
|
| 1094 |
+
attention_mask = self.encoder.get_attention_mask(attention_mask)
|
| 1095 |
+
rel_pos = self.encoder.get_rel_pos(embedding_output)
|
| 1096 |
+
for layer in layers:
|
| 1097 |
+
query_states = layer(
|
| 1098 |
+
hidden_states,
|
| 1099 |
+
attention_mask,
|
| 1100 |
+
output_attentions=False,
|
| 1101 |
+
query_states=query_states,
|
| 1102 |
+
relative_pos=rel_pos,
|
| 1103 |
+
rel_embeddings=rel_embeddings,
|
| 1104 |
+
)
|
| 1105 |
+
encoded_layers.append(query_states)
|
| 1106 |
+
|
| 1107 |
+
sequence_output = encoded_layers[-1]
|
| 1108 |
+
|
| 1109 |
+
if not return_dict:
|
| 1110 |
+
return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]
|
| 1111 |
+
|
| 1112 |
+
return BaseModelOutput(
|
| 1113 |
+
last_hidden_state=sequence_output,
|
| 1114 |
+
hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
|
| 1115 |
+
attentions=encoder_outputs.attentions,
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
@add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING)
|
| 1120 |
+
class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel):
|
| 1121 |
+
_tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
|
| 1122 |
+
|
| 1123 |
+
def __init__(self, config):
|
| 1124 |
+
super().__init__(config)
|
| 1125 |
+
|
| 1126 |
+
self.deberta = DebertaV2Model(config)
|
| 1127 |
+
self.cls = DebertaV2OnlyMLMHead(config)
|
| 1128 |
+
|
| 1129 |
+
# Initialize weights and apply final processing
|
| 1130 |
+
self.post_init()
|
| 1131 |
+
|
| 1132 |
+
def get_output_embeddings(self):
|
| 1133 |
+
return self.cls.predictions.decoder
|
| 1134 |
+
|
| 1135 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1136 |
+
self.cls.predictions.decoder = new_embeddings
|
| 1137 |
+
|
| 1138 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1139 |
+
@add_code_sample_docstrings(
|
| 1140 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1141 |
+
output_type=MaskedLMOutput,
|
| 1142 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1143 |
+
mask="[MASK]",
|
| 1144 |
+
)
|
| 1145 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM.forward with Deberta->DebertaV2
|
| 1146 |
+
def forward(
|
| 1147 |
+
self,
|
| 1148 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1149 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1150 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1151 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1152 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1153 |
+
labels: Optional[torch.Tensor] = None,
|
| 1154 |
+
output_attentions: Optional[bool] = None,
|
| 1155 |
+
output_hidden_states: Optional[bool] = None,
|
| 1156 |
+
return_dict: Optional[bool] = None,
|
| 1157 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 1158 |
+
r"""
|
| 1159 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1160 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1161 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1162 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1163 |
+
"""
|
| 1164 |
+
|
| 1165 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1166 |
+
|
| 1167 |
+
outputs = self.deberta(
|
| 1168 |
+
input_ids,
|
| 1169 |
+
attention_mask=attention_mask,
|
| 1170 |
+
token_type_ids=token_type_ids,
|
| 1171 |
+
position_ids=position_ids,
|
| 1172 |
+
inputs_embeds=inputs_embeds,
|
| 1173 |
+
output_attentions=output_attentions,
|
| 1174 |
+
output_hidden_states=output_hidden_states,
|
| 1175 |
+
return_dict=return_dict,
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
sequence_output = outputs[0]
|
| 1179 |
+
prediction_scores = self.cls(sequence_output)
|
| 1180 |
+
|
| 1181 |
+
masked_lm_loss = None
|
| 1182 |
+
if labels is not None:
|
| 1183 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 1184 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1185 |
+
|
| 1186 |
+
if not return_dict:
|
| 1187 |
+
output = (prediction_scores,) + outputs[1:]
|
| 1188 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1189 |
+
|
| 1190 |
+
return MaskedLMOutput(
|
| 1191 |
+
loss=masked_lm_loss,
|
| 1192 |
+
logits=prediction_scores,
|
| 1193 |
+
hidden_states=outputs.hidden_states,
|
| 1194 |
+
attentions=outputs.attentions,
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
@add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING)
|
| 1198 |
+
class DebertaV2ForCausalLM(DebertaV2ForMaskedLM):
|
| 1199 |
+
_tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
|
| 1200 |
+
|
| 1201 |
+
def __init__(self, config):
|
| 1202 |
+
super().__init__(config)
|
| 1203 |
+
config.is_decoder = True
|
| 1204 |
+
self.mask_token_id = config.mask_token_id
|
| 1205 |
+
self.sep_token_id = config.sep_token_id
|
| 1206 |
+
self.n_masks = 3
|
| 1207 |
+
|
| 1208 |
+
def set_decoder(self, decoder):
|
| 1209 |
+
self.deberta = decoder
|
| 1210 |
+
|
| 1211 |
+
def get_decoder(self):
|
| 1212 |
+
return self.deberta
|
| 1213 |
+
|
| 1214 |
+
def can_generate(self):
|
| 1215 |
+
return True
|
| 1216 |
+
|
| 1217 |
+
def prepare_inputs_for_generation(
|
| 1218 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 1219 |
+
):
|
| 1220 |
+
position_ids = kwargs.get("position_ids", None)
|
| 1221 |
+
|
| 1222 |
+
if input_ids[0, -1] == 2:
|
| 1223 |
+
input_ids = input_ids[:, :-1]
|
| 1224 |
+
if attention_mask is not None:
|
| 1225 |
+
attention_mask = attention_mask[:, :-1]
|
| 1226 |
+
if position_ids is not None:
|
| 1227 |
+
position_ids = position_ids[:, :-1]
|
| 1228 |
+
|
| 1229 |
+
# Omit tokens covered by past_key_values
|
| 1230 |
+
if past_key_values is not None:
|
| 1231 |
+
pass # should never happen
|
| 1232 |
+
|
| 1233 |
+
if attention_mask is not None and position_ids is None:
|
| 1234 |
+
# create position_ids on the fly for batch generation
|
| 1235 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1236 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1237 |
+
if past_key_values:
|
| 1238 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 1239 |
+
|
| 1240 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1241 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 1242 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 1243 |
+
else:
|
| 1244 |
+
model_inputs = {"input_ids": input_ids}
|
| 1245 |
+
|
| 1246 |
+
model_inputs.update(
|
| 1247 |
+
{
|
| 1248 |
+
"position_ids": position_ids,
|
| 1249 |
+
"past_key_values": past_key_values,
|
| 1250 |
+
"use_cache": kwargs.get("use_cache"),
|
| 1251 |
+
"attention_mask": attention_mask,
|
| 1252 |
+
}
|
| 1253 |
+
)
|
| 1254 |
+
return model_inputs
|
| 1255 |
+
|
| 1256 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1257 |
+
@add_code_sample_docstrings(
|
| 1258 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1259 |
+
output_type=CausalLMOutput,
|
| 1260 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1261 |
+
mask="[MASK]",
|
| 1262 |
+
)
|
| 1263 |
+
def forward(
|
| 1264 |
+
self,
|
| 1265 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1266 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1267 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1268 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1269 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 1270 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1271 |
+
labels: Optional[torch.Tensor] = None,
|
| 1272 |
+
use_cache: Optional[bool] = None,
|
| 1273 |
+
output_attentions: Optional[bool] = None,
|
| 1274 |
+
output_hidden_states: Optional[bool] = None,
|
| 1275 |
+
return_dict: Optional[bool] = None,
|
| 1276 |
+
) -> Union[Tuple, CausalLMOutput]:
|
| 1277 |
+
|
| 1278 |
+
assert labels is None, "only inference is supported for now"
|
| 1279 |
+
assert inputs_embeds is None, "inputs_embeds is not supported for now"
|
| 1280 |
+
assert token_type_ids is None, "token_type_ids is not supported for now"
|
| 1281 |
+
assert past_key_values is None, "past_key_values is not supported for now"
|
| 1282 |
+
assert use_cache is None, "use_cache is not supported for now"
|
| 1283 |
+
|
| 1284 |
+
assert input_ids[0, -1] != self.sep_token_id, "remove the last token if it is a sep token"
|
| 1285 |
+
|
| 1286 |
+
batch_size, seq_length = input_ids.shape
|
| 1287 |
+
input_ids = torch.cat(
|
| 1288 |
+
[
|
| 1289 |
+
input_ids,
|
| 1290 |
+
torch.full((batch_size, self.n_masks), self.mask_token_id, device=input_ids.device),
|
| 1291 |
+
torch.full((batch_size, 1), self.sep_token_id, device=input_ids.device)
|
| 1292 |
+
],
|
| 1293 |
+
dim=-1
|
| 1294 |
+
)
|
| 1295 |
+
attention_mask = torch.cat(
|
| 1296 |
+
[
|
| 1297 |
+
attention_mask,
|
| 1298 |
+
torch.full((batch_size, self.n_masks + 1), attention_mask[0, -1], device=attention_mask.device),
|
| 1299 |
+
],
|
| 1300 |
+
dim=-1
|
| 1301 |
+
)
|
| 1302 |
+
position_ids = torch.cat(
|
| 1303 |
+
[
|
| 1304 |
+
position_ids,
|
| 1305 |
+
torch.arange(0, self.n_masks + 1, device=position_ids.device).unsqueeze(0) + position_ids[:, -1:],
|
| 1306 |
+
],
|
| 1307 |
+
dim=-1
|
| 1308 |
+
)
|
| 1309 |
+
|
| 1310 |
+
outputs = super().forward(
|
| 1311 |
+
input_ids,
|
| 1312 |
+
attention_mask=attention_mask,
|
| 1313 |
+
token_type_ids=token_type_ids,
|
| 1314 |
+
position_ids=position_ids,
|
| 1315 |
+
inputs_embeds=inputs_embeds,
|
| 1316 |
+
output_attentions=output_attentions,
|
| 1317 |
+
output_hidden_states=output_hidden_states,
|
| 1318 |
+
return_dict=return_dict,
|
| 1319 |
+
)
|
| 1320 |
+
|
| 1321 |
+
# shift the outputs and skip excess masks
|
| 1322 |
+
logits = outputs.logits[:, 1:-(self.n_masks), :].contiguous()
|
| 1323 |
+
|
| 1324 |
+
loss = None
|
| 1325 |
+
if labels is not None:
|
| 1326 |
+
pass
|
| 1327 |
+
|
| 1328 |
+
if not return_dict:
|
| 1329 |
+
output = (logits,) + outputs[1:]
|
| 1330 |
+
return (loss,) + output if loss is not None else output
|
| 1331 |
+
|
| 1332 |
+
return CausalLMOutput(
|
| 1333 |
+
loss=loss,
|
| 1334 |
+
logits=logits,
|
| 1335 |
+
hidden_states=outputs.hidden_states,
|
| 1336 |
+
attentions=outputs.attentions,
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaPredictionHeadTransform with Deberta->DebertaV2
|
| 1341 |
+
class DebertaV2PredictionHeadTransform(nn.Module):
|
| 1342 |
+
def __init__(self, config):
|
| 1343 |
+
super().__init__()
|
| 1344 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 1345 |
+
|
| 1346 |
+
self.dense = nn.Linear(config.hidden_size, self.embedding_size)
|
| 1347 |
+
if isinstance(config.hidden_act, str):
|
| 1348 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 1349 |
+
else:
|
| 1350 |
+
self.transform_act_fn = config.hidden_act
|
| 1351 |
+
self.LayerNorm = nn.LayerNorm(self.embedding_size, eps=config.layer_norm_eps)
|
| 1352 |
+
|
| 1353 |
+
def forward(self, hidden_states):
|
| 1354 |
+
hidden_states = self.dense(hidden_states)
|
| 1355 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 1356 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 1357 |
+
return hidden_states
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaLMPredictionHead with Deberta->DebertaV2
|
| 1361 |
+
class DebertaV2LMPredictionHead(nn.Module):
|
| 1362 |
+
def __init__(self, config):
|
| 1363 |
+
super().__init__()
|
| 1364 |
+
self.transform = DebertaV2PredictionHeadTransform(config)
|
| 1365 |
+
|
| 1366 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 1367 |
+
# The output weights are the same as the input embeddings, but there is
|
| 1368 |
+
# an output-only bias for each token.
|
| 1369 |
+
self.decoder = nn.Linear(self.embedding_size, config.vocab_size, bias=True)
|
| 1370 |
+
|
| 1371 |
+
#self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 1372 |
+
|
| 1373 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 1374 |
+
#self.decoder.bias = self.bias
|
| 1375 |
+
|
| 1376 |
+
def forward(self, hidden_states):
|
| 1377 |
+
hidden_states = self.transform(hidden_states)
|
| 1378 |
+
hidden_states = self.decoder(hidden_states)
|
| 1379 |
+
return hidden_states
|
| 1380 |
+
|
| 1381 |
+
|
| 1382 |
+
# copied from transformers.models.bert.BertOnlyMLMHead with bert -> deberta
|
| 1383 |
+
class DebertaV2OnlyMLMHead(nn.Module):
|
| 1384 |
+
def __init__(self, config):
|
| 1385 |
+
super().__init__()
|
| 1386 |
+
self.predictions = DebertaV2LMPredictionHead(config)
|
| 1387 |
+
|
| 1388 |
+
def forward(self, sequence_output):
|
| 1389 |
+
prediction_scores = self.predictions(sequence_output)
|
| 1390 |
+
return prediction_scores
|
| 1391 |
+
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1b1b0c5fcd18795a94c7bedd61d0ba84b3682444e36beedf88aa118df4ec99b
|
| 3 |
+
size 3135918282
|
spm.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5598d5e96f339a8d980c15f9afd405a2e5e1be7db41de3ed13b0f03fac1e8c17
|
| 3 |
+
size 2447305
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"do_lower_case": false,
|
| 3 |
+
"vocab_type": "spm"
|
| 4 |
+
}
|