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)
- Input sequence: text composed of words (or subwords), for example
[W₁, W₂, W₃, [MASK], W₅, W₆, W₇, W₂, W₃, W₄, W₅]. [MASK]is the word randomly masked by BERT during pre-training (as in the original textW₄was replaced by[MASK]).
- Embedding layer: converts each word into a fixed-dimension vector representation (e.g., 768 dimensions), including:
- 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
- Multiple Transformer blocks: details are not expanded in the figure, but each block contains:
- 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.
- Output: the context-dependent vector representation corresponding to each input word (e.g.
O₁, O₂, ..., O₅).
3. Masked Language Modeling (MLM) task
- Goals: predict the masked word
[MASK]the corresponding original word (in the figureW₄). - Classification Layer:
- 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:
- Masked Language Model (MLM): randomly mask 15% of the input tokens and predict the masked words
- 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
- Adding a task adaptation layer: add a classification/regression layer according to the downstream task
- Learning rate setting: usually use a small learning rate (2e-5 to 5e-5)
- Batch size: 16 or 32 are common choices
- 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)
- Improvements:
- Larger batch (8k vs 256)
- Longer training time
- Remove the NSP task
- Dynamic masking pattern
- Performance: an average improvement of 2-3% on the GLUE benchmark
ALBERT (A Lite BERT)
- Core innovations:
- Parameter sharing (sharing attention parameters across layers)
- Embedding factorization (decomposing the word embedding into two small matrices)
- effect: 89% fewer parameters and a 1.7x speedup
Other important variants
- DistilBERT: compress the model via knowledge distillation
- ELECTRA: replace MLM with a generator-discriminator architecture
- 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
- Using the whole word masking (wwm) version works better
- Pay attention to Chinese word segmentation boundary issues
- For specialized domains, consider domain-adaptive pre-training
Practical suggestions and resources
Learning roadmap

Recommended resources
- Papers:
- Code repositories:
- Online courses:
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.