Home

Awesome

DeBERTa: Decoding-enhanced BERT with Disentangled Attention

This repository is the official implementation of DeBERTa: Decoding-enhanced BERT with Disentangled Attention and DeBERTa V3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing

News

03/18/2023

12/8/2021

11/16/2021

3/31/2021

2/03/2021

DeBERTa v2 code and the 900M, 1.5B model are here now. This includes the 1.5B model used for our SuperGLUE single-model submission and achieving 89.9, versus human baseline 89.8. You can find more details about this submission in our blog

What's new in v2

12/29/2020

With DeBERTa 1.5B model, we surpass T5 11B model and human performance on SuperGLUE leaderboard. Code and model will be released soon. Please check out our paper for more details.

06/13/2020

We released the pre-trained models, source code, and fine-tuning scripts to reproduce some of the experimental results in the paper. You can follow similar scripts to apply DeBERTa to your own experiments or applications. Pre-training scripts will be released in the next step.

Introduction to DeBERTa

DeBERTa (Decoding-enhanced BERT with disentangled attention) improves the BERT and RoBERTa models using two novel techniques. The first is the disentangled attention mechanism, where each word is represented using two vectors that encode its content and position, respectively, and the attention weights among words are computed using disentangled matrices on their contents and relative positions. Second, an enhanced mask decoder is used to replace the output softmax layer to predict the masked tokens for model pretraining. We show that these two techniques significantly improve the efficiency of model pre-training and performance of downstream tasks.

Pre-trained Models

Our pre-trained models are packaged into zipped files. You can download them from our releases, or download an individual model via the links below:

ModelVocabulary(K)Backbone Parameters(M)Hidden SizeLayersNote
V2-XXLarge<sup>1</sup>1281320153648128K new SPM vocab
V2-XLarge128710153624128K new SPM vocab
XLarge50700102448Same vocab as RoBERTa
Large50350102424Same vocab as RoBERTa
Base5010076812Same vocab as RoBERTa
V2-XXLarge-MNLI1281320153648Fine-turned with MNLI
V2-XLarge-MNLI128710153624Fine-turned with MNLI
XLarge-MNLI50700102448Fine-turned with MNLI
Large-MNLI50350102424Fine-turned with MNLI
Base-MNLI508676812Fine-turned with MNLI
DeBERTa-V3-Large<sup>2</sup>128304102424128K new SPM vocab
DeBERTa-V3-Base<sup>2</sup>1288676812128K new SPM vocab
DeBERTa-V3-Small<sup>2</sup>128447686128K new SPM vocab
DeBERTa-V3-XSmall<sup>2</sup>1282238412128K new SPM vocab
mDeBERTa-V3-Base<sup>2</sup>2508676812250K new SPM vocab, multi-lingual model with 102 languages

Note

Try the model

Read our documentation

Requirements

There are several ways to try our code,

Use docker

Docker is the recommended way to run the code as we already built every dependency into our docker bagai/deberta and you can follow the docker official site to install docker on your machine.

To run with docker, make sure your system fulfills the requirements in the above list. Here are the steps to try the GLUE experiments: Pull the code, run ./run_docker.sh , and then you can run the bash commands under /DeBERTa/experiments/glue/

Use pip

Pull the code and run pip3 install -r requirements.txt in the root directory of the code, then enter experiments/glue/ folder of the code and try the bash commands under that folder for glue experiments.

Install as a pip package

pip install deberta

Use DeBERTa in existing code


# To apply DeBERTa to your existing code, you need to make two changes to your code,
# 1. change your model to consume DeBERTa as the encoder
from DeBERTa import deberta
import torch
class MyModel(torch.nn.Module):
  def __init__(self):
    super().__init__()
    # Your existing model code
    self.deberta = deberta.DeBERTa(pre_trained='base') # Or 'large' 'base-mnli' 'large-mnli' 'xlarge' 'xlarge-mnli' 'xlarge-v2' 'xxlarge-v2'
    # Your existing model code
    # do inilization as before
    # 
    self.deberta.apply_state() # Apply the pre-trained model of DeBERTa at the end of the constructor
    #
  def forward(self, input_ids):
    # The inputs to DeBERTa forward are
    # `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length] with the word token indices in the vocabulary
    # `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token types indices selected in [0, 1]. 
    #    Type 0 corresponds to a `sentence A` and type 1 corresponds to a `sentence B` token (see BERT paper for more details).
    # `attention_mask`: an optional parameter for input mask or attention mask. 
    #   - If it's an input mask, then it will be torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [0, 1]. 
    #      It's a mask to be used if the input sequence length is smaller than the max input sequence length in the current batch. 
    #      It's the mask that we typically use for attention when a batch has varying length sentences.
    #   - If it's an attention mask then if will be torch.LongTensor of shape [batch_size, sequence_length, sequence_length]. 
    #      In this case, it's a mask indicating which tokens in the sequence should be attended by other tokens in the sequence. 
    # `output_all_encoded_layers`: whether to output results of all encoder layers, default, True
    encoding = deberta.bert(input_ids)[-1]

# 2. Change your tokenizer with the tokenizer built-in DeBERta
from DeBERTa import deberta
vocab_path, vocab_type = deberta.load_vocab(pretrained_id='base')
tokenizer = deberta.tokenizers[vocab_type](vocab_path)
# We apply the same schema of special tokens as BERT, e.g. [CLS], [SEP], [MASK]
max_seq_len = 512
tokens = tokenizer.tokenize('Examples input text of DeBERTa')
# Truncate long sequence
tokens = tokens[:max_seq_len -2]
# Add special tokens to the `tokens`
tokens = ['[CLS]'] + tokens + ['[SEP]']
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1]*len(input_ids)
# padding
paddings = max_seq_len-len(input_ids)
input_ids = input_ids + [0]*paddings
input_mask = input_mask + [0]*paddings
features = {
'input_ids': torch.tensor(input_ids, dtype=torch.int),
'input_mask': torch.tensor(input_mask, dtype=torch.int)
}

Run DeBERTa experiments from command line

For glue tasks,

  1. Get the data
cache_dir=/tmp/DeBERTa/
cd experiments/glue
./download_data.sh  $cache_dir/glue_tasks
  1. Run task
task=STS-B 
OUTPUT=/tmp/DeBERTa/exps/$task
export OMP_NUM_THREADS=1
python3 -m DeBERTa.apps.run --task_name $task --do_train  \
  --data_dir $cache_dir/glue_tasks/$task \
  --eval_batch_size 128 \
  --predict_batch_size 128 \
  --output_dir $OUTPUT \
  --scale_steps 250 \
  --loss_scale 16384 \
  --accumulative_update 1 \  
  --num_train_epochs 6 \
  --warmup 100 \
  --learning_rate 2e-5 \
  --train_batch_size 32 \
  --max_seq_len 128

Notes

Experiments

Our fine-tuning experiments are carried on half a DGX-2 node with 8x32 V100 GPU cards, the results may vary due to different GPU models, drivers, CUDA SDK versions, using FP16 or FP32, and random seeds. We report our numbers based on multiple runs with different random seeds here. Here are the results from the Large model:

TaskCommandResultsRunning Time(8x32G V100 GPUs)
MNLI xxlarge v2experiments/glue/mnli.sh xxlarge-v291.7/91.9 +/-0.14h
MNLI xlarge v2experiments/glue/mnli.sh xlarge-v291.7/91.6 +/-0.12.5h
MNLI xlargeexperiments/glue/mnli.sh xlarge91.5/91.2 +/-0.12.5h
MNLI largeexperiments/glue/mnli.sh large91.3/91.1 +/-0.12.5h
QQP largeexperiments/glue/qqp.sh large92.3 +/-0.16h
QNLI largeexperiments/glue/qnli.sh large95.3 +/-0.22h
MRPC largeexperiments/glue/mrpc.sh large91.9 +/-0.50.5h
RTE largeexperiments/glue/rte.sh large86.6 +/-1.00.5h
SST-2 largeexperiments/glue/sst2.sh large96.7 +/-0.31h
STS-b largeexperiments/glue/Stsb.sh large92.5 +/-0.30.5h
CoLA largeexperiments/glue/cola.sh70.5 +/-1.00.5h

And here are the results from the Base model

TaskCommandResultsRunning Time(8x32G V100 GPUs)
MNLI baseexperiments/glue/mnli.sh base88.8/88.5 +/-0.21.5h

Fine-tuning on NLU tasks

We present the dev results on SQuAD 1.1/2.0 and several GLUE benchmark tasks.

ModelSQuAD 1.1SQuAD 2.0MNLI-m/mmSST-2QNLICoLARTEMRPCQQPSTS-B
F1/EMF1/EMAccAccAccMCCAccAcc/F1Acc/F1P/S
BERT-Large90.9/84.181.8/79.086.6/-93.292.360.670.488.0/-91.3/-90.0/-
RoBERTa-Large94.6/88.989.4/86.590.2/-96.493.968.086.690.9/-92.2/-92.4/-
XLNet-Large95.1/89.790.6/87.990.8/-97.094.969.085.990.8/-92.3/-92.5/-
DeBERTa-Large<sup>1</sup>95.5/90.190.7/88.091.3/91.196.595.369.591.092.6/94.692.3/-92.8/92.5
DeBERTa-XLarge<sup>1</sup>-/--/-91.5/91.297.0--93.192.1/94.3-92.9/92.7
DeBERTa-V2-XLarge<sup>1</sup>95.8/90.891.4/88.991.7/91.697.595.871.193.992.0/94.292.3/89.892.9/92.9
DeBERTa-V2-XXLarge<sup>1,2</sup>96.1/91.492.2/89.791.7/91.997.296.072.093.593.1/94.992.7/90.393.2/93.1
DeBERTa-V3-Large-/-91.5/89.091.8/91.996.996.075.392.792.2/-93.0/-93.0/-
DeBERTa-V3-Base-/-88.4/85.490.6/90.7-------
DeBERTa-V3-Small-/-82.9/80.488.3/87.7-------
DeBERTa-V3-XSmall-/-84.8/82.088.1/88.3-------

Fine-tuning on XNLI

We present the dev results on XNLI with zero-shot crosslingual transfer setting, i.e. training with english data only, test on other languages.

Modelavgenfresdeelbgrutrarvithzhhiswur
XLM-R-base76.285.879.780.778.777.579.678.174.273.876.574.676.772.466.568.3
mDeBERTa-V3-Base79.8+/-0.288.282.684.482.782.382.480.879.578.578.176.479.575.973.972.4

Notes.

Pre-training with MLM and RTD objectives

To pre-train DeBERTa with MLM and RTD objectives, please check experiments/language_models

Contacts

Pengcheng He(penhe@microsoft.com), Xiaodong Liu(xiaodl@microsoft.com), Jianfeng Gao(jfgao@microsoft.com), Weizhu Chen(wzchen@microsoft.com)

Citation

@misc{he2021debertav3,
      title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing}, 
      author={Pengcheng He and Jianfeng Gao and Weizhu Chen},
      year={2021},
      eprint={2111.09543},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
@inproceedings{
he2021deberta,
title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
booktitle={International Conference on Learning Representations},
year={2021},
url={https://openreview.net/forum?id=XPZIaotutsD}
}