AI Logic

Architectures

DeBERTa

Updated:

Structure of DeBERTa. Left: the overall pre-training flow (embeddings without added positions, repeated encoder layers sharing a relative position embedding, an enhanced mask decoder that uses absolute positions for Q, and a language model head). Right: inside disentangled attention (from content and relative position projections, three scores β€” contentβ†’content, contentβ†’position, positionβ†’content β€” are summed, divided by √3d, and passed through softmax)

Background and overview

DeBERTa (Decoding-enhanced BERT with disentangled attention) is a language model that improves on BERT and RoBERTa by keeping the "content" and "position" of each word in separate vectors and computing attention weights separately for content-to-content and content-position combinations. It was proposed by He et al. at Microsoft in 2020 and presented at ICLR 2021.

BERT adds the word embedding and the position embedding at the input layer into a single vector and uses it in all layers. DeBERTa introduces two improvements here:

  • Disentangled attention: content vectors and relative position vectors are kept separate, and the attention weight is computed as the sum of three parts: "content β†’ content," "content β†’ position," and "position β†’ content." This is because the relationship between two words depends not only on the words themselves but also on how far apart they are. For example, "deep" and "learning" are much more strongly related when they are next to each other than when they appear in different sentences.
  • Enhanced mask decoder (EMD): the encoder uses only relative positions, and the absolute position in the sentence is added only in the decoder, right before predicting the masked words.

For fine-tuning, the paper also proposes SiFT, a virtual adversarial training method that normalizes the embeddings before adding small perturbations.

In the paper, with about half of RoBERTa-Large's training data (78GB vs. 160GB), DeBERTa outperforms it across a wide range of tasks: 91.1% accuracy on MNLI (RoBERTa: 90.2%), 90.7 F1 on SQuAD v2.0 (88.4), and 86.8% accuracy on RACE (83.2%). A version scaled up to 1.5 billion parameters reached a macro average of 89.9 on SuperGLUE, surpassing the human score (89.8) for the first time.

Architecture

Like BERT, DeBERTa stacks LL Transformer encoder layers. In the figure at the top of the article, the left shows the overall pre-training flow and the right shows the inside of disentangled attention.

The model sizes in the paper are as follows:

ModelLayers LLVector size ddHeadsFeed-forward hidden size
DeBERTa-Base12768123072
DeBERTa-Large241024164096
DeBERTa 1.5B481536246144

There are three differences from BERT:

  1. No positions are added at the input layer: the input is just the word embedding, which is fed into the layers as the "content vector" HH.
  2. Self-attention is replaced with disentangled attention: the attention in each layer uses the content vectors HH and a relative position embedding P∈R2kΓ—dP \in \mathbb{R}^{2k \times d} shared across all layers (next section). The residual connections, layer normalization, and feed-forward network are the same as in BERT.
  3. An EMD is placed before the masked language model output: before predicting the masked words from the encoder output HH, it passes through Transformer layers that add absolute positions.

The idea of disentangled attention is explained here for a single head. If the word at position ii is represented by two vectors, its content vector HiH_i and its relative position vector Pi∣jP_{i|j} with respect to position jj, the attention score between ii and jj can be decomposed into four terms:

Ai,j={Hi,Pi∣j}Γ—{Hj,Pj∣i}⊀=HiHj⊀+HiPj∣i⊀+Pi∣jHj⊀+Pi∣jPj∣i⊀A_{i,j} = \{H_i, P_{i|j}\} \times \{H_j, P_{j|i}\}^\top = H_i H_j^\top + H_i P_{j|i}^\top + P_{i|j} H_j^\top + P_{i|j} P_{j|i}^\top

The four terms are, in order, "content β†’ content," "content β†’ position," "position β†’ content," and "position β†’ position." Because DeBERTa uses relative positions, it argues that the "position β†’ position" term provides little new information, and drops the last term.

Earlier relative position methods (such as Shaw et al.'s relative position representations) computed only the equivalents of the "content β†’ content" and "content β†’ position" terms. DeBERTa's novelty is adding the "position β†’ content" term, and in the paper's experiments, removing this term lowered performance.

Computing disentangled attention and the EMD

Disentangled attention for a single head is computed as follows:

  1. Truncate the relative distance Ξ΄(i,j)\delta(i, j) between two positions at a maximum distance kk and turn it into an index in [0,2k)[0, 2k) (k=512k = 512 in pre-training).
  2. From the content vectors HH, compute Qc=HWq,cQ_c = H W_{q,c}, Kc=HWk,cK_c = H W_{k,c}, Vc=HWv,cV_c = H W_{v,c}; from the relative position embedding PP, compute Qr=PWq,rQ_r = P W_{q,r}, Kr=PWk,rK_r = P W_{k,r}.
  3. Compute the score A~i,j\tilde{A}_{i,j} as the sum of three terms.
  4. Divide by 3d\sqrt{3d}, apply softmax, and output the weighted sum of VcV_c.

The relative distance index is defined as:

Ξ΄(i,j)={0iβˆ’jβ‰€βˆ’k2kβˆ’1iβˆ’jβ‰₯kiβˆ’j+kotherwise\delta(i, j) = \begin{cases} 0 & i - j \le -k \\ 2k - 1 & i - j \ge k \\ i - j + k & \text{otherwise} \end{cases}

The score and output are as follows. Kr,Ξ΄(i,j)K_{r,\delta(i,j)} is the Ξ΄(i,j)\delta(i,j)-th row of KrK_r.

A~i,j=Qc,iKc,j⊀⏟contentβ†’content+Qc,iKr,Ξ΄(i,j)⊀⏟contentβ†’position+Kc,jQr,Ξ΄(j,i)⊀⏟positionβ†’content\tilde{A}_{i,j} = \underbrace{Q_{c,i} K_{c,j}^\top}_{\text{content} \to \text{content}} + \underbrace{Q_{c,i} K_{r,\delta(i,j)}^\top}_{\text{content} \to \text{position}} + \underbrace{K_{c,j} Q_{r,\delta(j,i)}^\top}_{\text{position} \to \text{content}} Ho=softmax(A~3d)VcH_o = \mathrm{softmax}\left(\frac{\tilde{A}}{\sqrt{3d}}\right) V_c

The "position β†’ content" term uses Ξ΄(j,i)\delta(j, i) rather than Ξ΄(i,j)\delta(i, j) because it represents "the weight of the content at jj as seen from position ii." Since three terms are summed, the score is divided by 3d\sqrt{3d} instead of the usual d\sqrt{d}, keeping the magnitude of values in check and stabilizing training.

Preparing a relative position vector for every word pair would require O(N2d)O(N^2 d) memory for a sequence of length NN. DeBERTa computes QcKr⊀Q_c K_r^\top (NΓ—2kN \times 2k) all at once and then picks out values using Ξ΄\delta as an index, keeping memory at O(kd)O(kd).

The enhanced mask decoder (EMD) is the part that predicts the masked words. In its Transformer layers, Q is computed from the input II, and K and V from the encoder output HH. In the first layer, II is the absolute position embedding; in the second layer, II is the output of the first layer. The paper uses two layers with shared weights and feeds their output into the language model head.

Pre-training uses the same masked language model as BERT. The paper's settings for DeBERTa-Large are as follows:

ItemValue
DataWikipedia (12GB), BookCorpus (6GB), OpenWebText (38GB), Stories (31GB). About 78GB after deduplication
TokenizationThe same BPE vocabulary as GPT-2 and RoBERTa
Batch / steps2,000 sequences Γ— 1M steps (about half the number of sequences of RoBERTa and XLNet)
OptimizationAdam (learning rate 2Γ—10βˆ’42 \times 10^{-4}, Ο΅=10βˆ’6\epsilon = 10^{-6}), weight decay 0.01, gradient clipping 1.0
Learning rate10k steps of warmup, then linear decay
ComputeAbout 20 days on 96 V100 GPUs

For masking, in addition to BERT's method, it also masks contiguous spans of up to 3 tokens.

Why separating content and position helps

When content and position are added into a single vector as in BERT, the influences of "which word it is" and "where it is" get mixed in the attention score. DeBERTa keeps the two as separate vectors and computes the score for each combination with separate weights, making it easier to learn relationships such as "this word attends strongly to the word right next to it" and "from this position, attend to a certain kind of word."

However, relative positions alone are not always enough. The paper's example is "a new store opened beside the new mall," where "store" and "mall" are masked and must be predicted. Both come right after "new," and their surrounding words and relative positions are very similar, but the subject of the sentence is "store." Such syntactic roles depend heavily on the absolute position in the sentence.

When describing your seat in a building, "the seat next to the window" (relative position) is not enough if there are many similar windows. Adding "the east end of the 3rd floor" (absolute position) pins it down. DeBERTa learns relationships through relative positions such as "next to" or "two ahead" in each layer, and adds absolute position as a clue only at the end, right before predicting the words.

As for why absolute positions are added at the end rather than at the input layer, the paper speculates that introducing absolute positions early may prevent the model from sufficiently learning relative position information. Indeed, a variant that adds absolute positions at the input layer (DeBERTa-AP) had worse perplexity on WikiText-103 than DeBERTa (20.0 vs. 19.9 on the test set).

Disentangled attention increases computation by about 30% compared with BERT and RoBERTa. Parameters also increase by the relative position projections Wq,rW_{q,r}, Wk,rW_{k,r} and the embedding PP (about 49M for Large, a 13% increase). The paper reports that sharing Wq,rW_{q,r} and Wk,rW_{k,r} with the content projections brings the parameter count down to that of RoBERTa, with nearly the same results for Base.

Experimental results

GLUE (dev set; Matthews correlation for CoLA, correlation for STS-B, accuracy for the others; all models of similar size with 24 layers and 1024 dimensions)

ModelCoLAQQPMNLI (matched)SST-2QNLIRTEMRPCAverage
BERT-Large60.691.386.693.292.370.488.084.05
RoBERTa-Large68.092.290.296.493.986.690.988.82
XLNet-Large69.092.390.897.094.985.990.889.15
ELECTRA-Large69.192.490.996.995.088.090.889.46
DeBERTa-Large70.592.391.196.895.388.391.990.00

RoBERTa, XLNet, and ELECTRA were trained on 160GB of data, whereas DeBERTa, trained on 78GB, achieved the highest average.

Question answering and reading comprehension (dev set; F1 / EM for SQuAD, accuracy for RACE)

ModelSQuAD v1.1SQuAD v2.0RACE
BERT-Large90.9 / 84.181.8 / 79.072.0
RoBERTa-Large94.6 / 88.989.4 / 86.583.2
XLNet-Large95.1 / 89.790.6 / 87.985.4
DeBERTa-Large95.5 / 90.190.7 / 88.086.8

Which components helped (Base size; trained on Wikipedia and BookCorpus)

ModelMNLI (matched / mismatched)SQuAD v1.1 (F1)SQuAD v2.0 (F1)RACE
RoBERTa-Base (retrained with the same settings)84.9 / 85.191.179.566.8
DeBERTa-Base86.3 / 86.292.182.571.7
γ€€Without EMD86.1 / 86.191.881.370.3
γ€€Without the content β†’ position term85.9 / 85.791.681.369.3
γ€€Without the position β†’ content term86.0 / 85.891.780.869.6

Removing any of EMD, content β†’ position, or position β†’ content lowered performance on all tasks. Removing two at once lowers it further.

Scaling to 1.5 billion parameters: a 48-layer, 1536-dimensional model was trained on 160GB of data with a new 128K-token vocabulary. The relative position projections are shared with the content projections, and a convolution layer is added alongside the first layer. On the SuperGLUE test set, a single model (fine-tuned with SiFT) reached a macro average of 89.9, surpassing the human baseline of 89.8 and the 11-billion-parameter T5's 89.3.

Practical notes

When using DeBERTa, keep the following points in mind:

  • Use even smaller fine-tuning learning rates: the paper's search ranges are 1.5Γ—10βˆ’51.5 \times 10^{-5} to 4Γ—10βˆ’54 \times 10^{-5} for Base, 5Γ—10βˆ’65 \times 10^{-6} to 1Γ—10βˆ’51 \times 10^{-5} for Large, and 1Γ—10βˆ’61 \times 10^{-6} to 5Γ—10βˆ’65 \times 10^{-6} for 1.5B, smaller for larger models.
  • Use the tokenizer that matches the model: the paper's Base and Large use the same BPE vocabulary as GPT-2 and RoBERTa, while 1.5B uses a new 128K-token vocabulary.
  • Long inputs: because relative distances are truncated at kk, each layer directly sees only about kk tokens on either side, but stacking layers lets information reach farther indirectly. The paper states that DeBERTa-Large (k=512k = 512, 24 layers) can theoretically handle up to 24,528 tokens, and reports that extending the RACE input from 512 to 768 raised accuracy from 86.3% to 86.8%.
  • SiFT helps for large models: embedding norms vary widely across words and models, and adversarial training becomes more unstable for larger models. SiFT prevents this by normalizing the embeddings before adding perturbations. In the paper, SiFT was used only in the 1.5B SuperGLUE experiments.

The paper's comparisons with RoBERTa and XLNet are made under conditions where both the amount of training data (78GB for DeBERTa, 160GB for RoBERTa and XLNet) and the number of training sequences differ. They show that DeBERTa "outperformed with less data," but they do not measure differences due to architecture alone. To see the effect of the architecture under matched conditions, refer to the ablation against RoBERTa retrained on the same data (the third table in the experiments section).

Comparison with other models

Comparing BERT-family encoder models from the same angles, with a focus on how they handle position, gives the following:

ModelHow position is introducedAttention scorePre-training taskTraining data in the paper
BERTAbsolute position embeddings added at the input layerDot product of vectors summing content and positionMasked language model + next sentence prediction16GB
RoBERTaSame as BERTSame as BERTMasked language model (longer training, more data)160GB
XLNetRelative positions (Transformer-XL)Content β†’ content + content β†’ positionPermutation language modelAbout 160GB
DeBERTaRelative positions in each layer, absolute positions in the decoder (EMD)Content β†’ content + content β†’ position + position β†’ contentMasked language model78GB

Rough guidelines for choosing:

  • Improving accuracy on understanding tasks such as sentence classification, entailment, and question answering: DeBERTa outperformed BERT, RoBERTa, and XLNet of similar size with less data.
  • Keeping computation low: disentangled attention costs about 30% more computation than RoBERTa. If speed is the priority, smaller models such as DistilBERT are also candidates.
  • Generating text: encoder-only models are not suitable. Use a decoder-only model such as GPT or an encoder-decoder model such as BART.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
from transformers import AutoTokenizer, AutoModelForSequenceClassification

"""
1. A small implementation of disentangled attention (one head) following Eqs. (3)(4) and Algorithm 1 of the paper
2. An example of fine-tuning a pre-trained DeBERTa for classification with Hugging Face transformers
"""


def relative_index(n, k):
    """Ξ΄(i, j): truncate i - j into an index in [0, 2k) (Eq. 3)"""
    pos = torch.arange(n)
    rel = pos[:, None] - pos[None, :]               # rel[i, j] = i - j
    return torch.clamp(rel + k, 0, 2 * k - 1)       # 0 if i-j <= -k, 2k-1 if i-j >= k


class DisentangledSelfAttention(nn.Module):
    def __init__(self, d, k=512):
        super().__init__()
        self.d, self.k = d, k
        self.q_c = nn.Linear(d, d)                  # content projections W_q,c, W_k,c, W_v,c
        self.k_c = nn.Linear(d, d)
        self.v_c = nn.Linear(d, d)
        self.q_r = nn.Linear(d, d, bias=False)      # position projections W_q,r, W_k,r
        self.k_r = nn.Linear(d, d, bias=False)

    def forward(self, h, p):
        # h: content vectors [n, d], p: relative position embedding [2k, d] (shared across all layers)
        n = h.shape[0]
        qc, kc, vc = self.q_c(h), self.k_c(h), self.v_c(h)
        qr, kr = self.q_r(p), self.k_r(p)
        delta = relative_index(n, self.k)           # [n, n]

        a_cc = qc @ kc.T                            # content -> content [n, n]
        a_cp = (qc @ kr.T).gather(1, delta)         # content -> position: pick out [i, Ξ΄(i,j)]
        a_pc = (kc @ qr.T).gather(1, delta).T       # position -> content: pick out [j, Ξ΄(j,i)] and transpose
        a = (a_cc + a_cp + a_pc) / math.sqrt(3 * self.d)   # three terms, so divide by √(3d)
        return a.softmax(dim=-1) @ vc               # [n, d]


d, k, n = 64, 8, 10
attn = DisentangledSelfAttention(d, k)
p = nn.Parameter(torch.randn(2 * k, d) * 0.02)      # relative position embedding
print(attn(torch.randn(n, d), p).shape)             # torch.Size([10, 64])

# --- 2. Classify the relation between two sentences with a pre-trained DeBERTa ---
name = "microsoft/deberta-base"
tokenizer = AutoTokenizer.from_pretrained(name)    # same BPE vocabulary as GPT-2 and RoBERTa
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5, eps=1e-6, weight_decay=0.01)

batch = tokenizer(
    ["A man is playing a guitar.", "A dog runs in the park."],
    ["A person plays an instrument.", "The cat is sleeping."],
    padding=True, truncation=True, max_length=128, return_tensors="pt")
labels = torch.tensor([1, 0])

model.train()                                       # enable dropout
loss = model(**batch, labels=labels).loss
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)   # gradient clipping 1.0 as in the paper
optimizer.step()
optimizer.zero_grad()

model.eval()
with torch.no_grad():
    print(model(**batch).logits.softmax(dim=-1))

FAQ

Q. What is the biggest difference between DeBERTa and BERT?
A.

How position is handled. BERT adds word and position embeddings at the input layer into a single vector. DeBERTa keeps content and relative position as separate vectors and computes the attention score as the sum of three parts: "content β†’ content," "content β†’ position," and "position β†’ content." Absolute positions are added only in the decoder (EMD), right before predicting the masked words.

Q. Why is the "position β†’ position" term not used?
A.

Because relative positions are used, the dot product between two relative position vectors provides little new information. For this reason, the paper removes "position β†’ position" from the four terms in its implementation.

Q. Why is the attention score divided by $\sqrt{3d}$ instead of $\sqrt{d}$?
A.

Because the score is the sum of three terms, its values tend to become large otherwise. The paper states that dividing by 3d\sqrt{3d} to keep the magnitude in check stabilizes training, especially for large models.

References

  1. He, P., Liu, X., Gao, J., & Chen, W. (2021). DeBERTa: Decoding-enhanced BERT with Disentangled Attention. ICLR 2021. arXiv:2006.03654.
  2. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  3. Liu, Y., Ott, M., Goyal, N., et al. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach. arXiv:1907.11692.
  4. Shaw, P., Uszkoreit, J., & Vaswani, A. (2018). Self-Attention with Relative Position Representations. NAACL-HLT 2018. arXiv:1803.02155.
  5. Microsoft. DeBERTa (official implementation and pre-trained models). GitHub.