Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

BERT series models

BERT series models

BERT (Bidirectional Encoder Representations from Transformers) is a revolutionary natural language processing model proposed by Google in 2018; it completely changed the research and application paradigm in the field of NLP.

This article will systematically introduce BERT's core principles, training methods, fine-tuning techniques, and mainstream variant models.


BERT architecture and training

The figure below shows BERT (Bidirectional Encoder Representations from Transformers) the model's core architecture and the Masked Language Modeling (MLM) task during pre-training.

1. Input Layer (Embedding)

- `[MASK]` is the word randomly masked by BERT during pre-training (for example, `W₄` in the original text is replaced by `[MASK]`). - **Token Embeddings**: the semantic information of words. - **Position Embeddings**: the position information of a word in the sequence. - **Segment Embeddings**: distinguishes sentences (useful for sentence-pair tasks, not explicitly shown in the figure).

2. Transformer Encoder

- **Self-Attention mechanism**: captures contextual dependencies bidirectionally (a core feature of BERT). - **Feed-Forward Network**: a non-linear transformation. - **Residual connections and layer normalization**: stabilizes the training process.

3. Masked Language Modeling (MLM) task

- **Fully-Connected Layer**: maps the vectors output by the Transformer (e.g. `O₄`) to the dimension of the vocabulary size. - **Activation function GELU**: Gaussian Error Linear Unit (the non-linear function used by BERT). - **Layer normalization (Norm)**: normalizes the output. - **Softmax**: computes the probability of each word in the vocabulary and selects the word with the highest probability as the prediction (e.g. `W'₁, W'₂, ..., W'₅` are candidate words).

Transformer encoder structure

BERT is built on the encoder part of the Transformer; its core is the multi-layer self-attention mechanism:

Example

Simplified Transformer encoder layer

class

TransformerEncoderLayer

(

nn.

Module

)

:

   

def

init

(

self

,

d_model

,

nhead

,

dim_feedforward

=

2048

)

:

       

super

(

)

.

init

(

)

       

self

.

self_attn

=

MultiheadAttention

(

d_model

,

nhead

)

       

self

.

linear1

=

nn.

Linear

(

d_model

,

dim_feedforward

)

       

self

.

linear2

=

nn.

Linear

(

dim_feedforward

,

d_model

)

       

self

.

norm1

=

nn.

LayerNorm

(

d_model

)

       

self

.

norm2

=

nn.

LayerNorm

(

d_model

)

       

   

def

forward

(

self

,

src

)

:

       

Self-attention mechanism

        src2

=

self

.

self_attn

(

src

,

src

,

src

)

[

0

]

        src

=

src +

self

.

norm1

(

src2

)

       

Feed-forward network

        src2

=

self

.

linear2

(

F.

relu

(

self

.

linear1

(

src

)

)

)

        src

=

src +

self

.

norm2

(

src2

)

       

return

src

Key innovation: bidirectional context modeling

Unlike traditional language models, BERT achieves bidirectional contextual understanding through the following two pre-training tasks:

  1. Masked Language Model (MLM): randomly mask 15% of the input tokens and predict the masked words
  2. Next Sentence Prediction (NSP): determine whether two sentences appear consecutively

Training parameters and configuration

Parameters BERT-base BERT-large
Number of layers 12 24
Hidden layer size 768 1024
Number of attention heads 12 16
Total number of parameters 110M 340M

BERT fine-tuning methods

Standard fine-tuning workflow

  1. Adding a task adaptation layer: add a classification/regression layer according to the downstream task
  2. Learning rate setting: usually use a small learning rate (2e-5 to 5e-5)
  3. Batch size: 16 or 32 are common choices
  4. Training epochs: 2-4 epochs are usually sufficient

Efficient fine-tuning techniques

Example

Example of fine-tuning with HuggingFace Transformers

from

transformers

import

BertForSequenceClassification

,

Trainer

model

=

BertForSequenceClassification.

from_pretrained

(

'bert-base-uncased'

)

trainer

=

Trainer

(

    model

=

model

,

    args

=

training_args

,

    train_dataset

=

train_dataset

,

    eval_dataset

=

eval_dataset

)

trainer.

train

(

)

Comparison of common fine-tuning strategies

Method Advantages Disadvantages
Full-parameter fine-tuning Best performance High computational cost
Feature extraction (frozen BERT) Computationally efficient Suboptimal performance
Adapter Parameter efficient Requires architecture modifications
Prompt learning (Prompt) Good performance with few samples Requires designing prompt templates

Mainstream BERT variant models

RoBERTa (Robustly Optimized BERT)

- Larger batch (8k vs 256) - Longer training time - Remove the NSP task - Dynamic masking pattern

ALBERT (A Lite BERT)

- Parameter sharing (sharing attention parameters across layers) - Embedding factorization (decomposing the word embedding into two small matrices)

Other important variants

  1. DistilBERT: compress the model via knowledge distillation
  2. ELECTRA: replace MLM with a generator-discriminator architecture
  3. SpanBERT: improve the modeling of text spans

Chinese BERT models

Overview of Chinese pre-trained models

Model Institution Feature
BERT-wwm Harbin Institute of Technology Whole Word Masking
RoBERTa-wwm-ext Harbin Institute of Technology Expanded training data
ERNIE (Baidu) Baidu Incorporate knowledge graphs
NEZHA Huawei Relative position encoding

Chinese BERT usage example

Example

from

transformers

import

BertTokenizer

,

BertModel

tokenizer

=

BertTokenizer.

from_pretrained

(

'bert-base-chinese'

)

model

=

BertModel.

from_pretrained

(

'bert-base-chinese'

)

inputs

=

tokenizer

(

"Natural language processing is interesting"

,

return_tensors

=

"pt"

)

outputs

=

model

(

**inputs

)

Tips for fine-tuning on Chinese tasks

  1. Using the whole word masking (wwm) version works better
  2. Pay attention to Chinese word segmentation boundary issues
  3. For specialized domains, consider domain-adaptive pre-training

Practical suggestions and resources

Learning roadmap

Recommended resources

  1. Papers:
  2. Original BERT paper (arXiv:1810.04805)
  3. Variant papers such as RoBERTa and ALBERT
  4. - Original BERT paper (arXiv:1810.04805) - Variant papers such as RoBERTa and ALBERT
    1. Code repositories:
    2. HuggingFace Transformers
    3. GitHub implementations of Chinese BERT
    4. - HuggingFace Transformers - GitHub implementations of Chinese BERT
      1. Online courses:
      2. Coursera Natural Language Processing Specialization
      3. Hung-yi Lee's Deep Learning Course
      4. - Coursera Natural Language Processing Specialization - Hung-yi Lee's Deep Learning Course

        Through systematic study and practice, the BERT series models can become a powerful tool for you to solve NLP problems. It is recommended to start with the basic version and gradually explore more advanced variants and optimization techniques.