Instructions to use Tuibingu03/TABERT_SimCSE with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tuibingu03/TABERT_SimCSE with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Tuibingu03/TABERT_SimCSE", device_map="auto") - Notebooks
- Google Colab
- Kaggle
TABERT-SimCSE Vietnamese Sentence Embeddings
1. Model Overview
TABERT-SimCSE là mô hình biểu diễn câu (Sentence Embedding) dành cho tiếng Việt, được phát triển bằng cách fine-tune mô hình nền vinai/phobert-base-v2 theo phương pháp học tương phản không giám sát (Unsupervised SimCSE).
Mô hình chuyển đổi câu hoặc đoạn văn tiếng Việt thành các vector ngữ nghĩa có kích thước cố định (dense embeddings), nhằm biểu diễn nội dung ngữ nghĩa của văn bản trong không gian vector.
Supported Tasks
- Semantic Textual Similarity (STS): Đo độ tương đồng ngữ nghĩa giữa hai câu hoặc đoạn văn.
- Semantic Search: Tìm kiếm văn bản dựa trên mức độ tương đồng ngữ nghĩa.
- Information Retrieval: Biểu diễn văn bản phục vụ truy xuất thông tin.
- Text Clustering: Gom nhóm câu và đoạn văn có nội dung tương đồng.
- Text Classification: Sử dụng embedding làm đầu vào cho các mô hình phân loại phía sau.
Mô hình được huấn luyện trên các đoạn văn trích xuất từ dữ liệu báo chí tiếng Việt. Vì vậy, mô hình hướng đến việc biểu diễn các câu và đoạn văn ngắn trong miền ngôn ngữ báo chí.
2. Base Model
| Attribute | Value |
|---|---|
| Backbone | vinai/phobert-base-v2 |
| Architecture | RoBERTa-base |
| Number of layers | 12 |
| Attention heads | 12 |
| Hidden size | 768 |
| Parameters | Approximately 135M |
| Vocabulary size | 64,001 |
| Maximum sequence length | 256 tokens |
| Language | Vietnamese |
Base model: vinai/phobert-base-v2
PhoBERT sử dụng kiến trúc dựa trên RoBERTa và được tiền huấn luyện trên dữ liệu tiếng Việt quy mô lớn. Mô hình yêu cầu văn bản đầu vào được tách từ trước khi tokenization.
3. Training Method
Mô hình được fine-tune bằng phương pháp Unsupervised SimCSE (Simple Contrastive Learning of Sentence Embeddings).
3.1. Positive Pair Generation
Với mỗi đoạn văn đầu vào $x_i$, mô hình thực hiện hai lần forward pass độc lập với dropout ngẫu nhiên để tạo ra hai biểu diễn:
Trong đó:
- $f_{\theta}$: PhoBERT backbone.
- $d_1, d_2$: Hai trạng thái dropout ngẫu nhiên trong hai lần forward pass.
- $z_i, z_i'$: Hai embedding được tạo ra từ cùng một đoạn văn đầu vào.
Hai embedding này được xem là một positive pair trong quá trình huấn luyện Unsupervised SimCSE.
3.2. Dropout Configuration
| Parameter | Value |
|---|---|
| Hidden dropout | 0.3 |
| Attention dropout | 0.3 |
3.3. Projection Head
Trong quá trình huấn luyện, mô hình sử dụng một MLP projection head:
nn.Sequential(
nn.Linear(768, 768),
nn.Tanh()
)
Projection head được sử dụng để tạo biểu diễn phục vụ hàm loss tương phản.
Inference: Không sử dụng projection head. Mô hình lấy trực tiếp embedding tại vị trí [CLS] từ PhoBERT backbone đã fine-tune.
3.4. Contrastive Loss
Mô hình sử dụng hàm InfoNCE / Cross-Entropy trên ma trận cosine similarity với temperature:
[ \tau = 0.05 ]
Các biểu diễn của cùng một đoạn văn được xem là positive pair, trong khi các đoạn văn khác trong batch đóng vai trò negative samples.
3.5. Training Hyperparameters
| Hyperparameter | Value |
|---|---|
| Learning rate | 5e-6 |
| Batch size | 128 |
| Optimizer | AdamW |
| Weight decay | 0.0 |
| Scheduler | Linear schedule |
| Warmup ratio | 0.05 |
| Temperature | 0.05 |
| Hidden dropout | 0.3 |
| Attention dropout | 0.3 |
| Precision | Mixed Precision FP16/BF16 |
| Gradient scaling | torch.amp.GradScaler |
| Batch sampling | Length-based bucketing |
Length-based bucketing sampler được sử dụng nhằm nhóm các đoạn văn có độ dài tương đồng trong cùng batch, qua đó giảm lượng padding và cải thiện hiệu quả sử dụng GPU.
4. Training Data
Mô hình được huấn luyện trên tập dữ liệu các đoạn văn tiếng Việt được trích xuất từ bài báo.
4.1. Dataset Statistics
| Attribute | Value |
|---|---|
| Dataset file | paragraphs_filtered.parquet |
| Number of paragraphs | 345,863 |
| Number of articles | 28,511 |
| Language | Vietnamese |
| Domain | News / Journalism |
4.2. Preprocessing
Quy trình tiền xử lý bao gồm:
- Trích xuất các đoạn văn từ nội dung bài báo.
- Loại bỏ các đoạn văn không phù hợp và dữ liệu trùng lặp.
- Thực hiện Vietnamese Word Segmentation bằng VnCoreNLP.
- Tokenize bằng PhoBERT tokenizer.
- Lọc đoạn văn theo độ dài token.
4.3. Sequence Length Filtering
| Parameter | Value |
|---|---|
| Minimum tokens | 16 |
| Maximum tokens | 128 |
Các đoạn văn được giữ lại nếu có độ dài từ 16 đến 128 tokens sau tiền xử lý và tokenization.
Data availability: Dataset huấn luyện không được đính kèm trong repository này. Các thống kê trên được cung cấp nhằm mô tả dữ liệu và quy trình huấn luyện.
5. Evaluation
Chất lượng biểu diễn câu được đánh giá trên các bộ dữ liệu Semantic Textual Similarity (STS) tiếng Việt.
Hai chỉ số được sử dụng:
- Spearman Correlation ((\rho)): Đánh giá mức độ tương quan thứ hạng giữa cosine similarity của embedding và nhãn tương đồng.
- Pearson Correlation ((r)): Đánh giá mức độ tương quan tuyến tính giữa cosine similarity của embedding và nhãn tương đồng.
5.1. Evaluation Results
| Dataset | Number of pairs (N) | Spearman ((\rho)) | Pearson ((r)) |
|---|---|---|---|
stsb_seg |
1,035 | 0.6536 | 0.6855 |
sts_sickr_seg |
9,599 | 0.6852 | 0.7448 |
sts12_seg |
2,803 | 0.4560 | 0.5099 |
sts14_seg |
3,625 | 0.5599 | 0.6062 |
sts15_seg |
2,978 | 0.6557 | 0.6517 |
sts16_seg |
1,174 | 0.6769 | 0.6655 |
stsbenchmark_seg |
8,272 | 0.6642 | 0.6889 |
| Average (7 datasets) | 29,486 | 0.6217 | 0.6504 |
stsb_vi_merged_10000 (separate evaluation) |
10,000 | 0.7371 | 0.7462 |
Notes:
- Average được báo cáo trên 7 bộ dữ liệu STS ở trên.
stsb_vi_merged_10000được đánh giá riêng và không được đưa vào giá trị Average.- Kết quả được ghi nhận tại một checkpoint trung gian trong quá trình huấn luyện SimCSE, không nhất thiết là kết quả cuối cùng của quá trình huấn luyện.
6. Usage
6.1. Installation
pip install torch transformers py_vncorenlp
PhoBERT yêu cầu văn bản được tách từ trước khi đưa vào tokenizer.
6.2. Load Model
Thay xxx bằng Hugging Face repository ID thực tế của mô hình.
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer
MODEL_ID = "xxx"
device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
# Load fine-tuned tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
# Load fine-tuned PhoBERT backbone
model = AutoModel.from_pretrained(MODEL_ID)
model.to(device)
model.eval()
6.3. Vietnamese Word Segmentation
Sử dụng VnCoreNLP để tách từ tiếng Việt trước khi tokenization.
import py_vncorenlp
# Download VnCoreNLP model if necessary
py_vncorenlp.download_model(
save_dir="./vncorenlp"
)
# Initialize word segmenter
segmenter = py_vncorenlp.VnCoreNLP(
annotators=["wseg"],
save_dir="./vncorenlp"
)
6.4. Generate Sentence Embeddings
import torch
import torch.nn.functional as F
def encode(sentences, max_length=256):
"""
Generate normalized sentence embeddings.
Args:
sentences: List of raw Vietnamese sentences.
max_length: Maximum tokenized sequence length.
Returns:
Tensor of shape (batch_size, 768).
"""
# Vietnamese word segmentation
segmented_sentences = [
segmenter.word_segment(sentence)[0]
for sentence in sentences
]
# Tokenization
inputs = tokenizer(
segmented_sentences,
padding=True,
truncation=True,
max_length=max_length,
return_tensors="pt"
)
inputs = {
key: value.to(device)
for key, value in inputs.items()
}
# Inference
with torch.inference_mode():
outputs = model(**inputs)
# Extract CLS embeddings
embeddings = outputs.last_hidden_state[:, 0]
# L2 normalization
embeddings = F.normalize(
embeddings,
p=2,
dim=1
)
return embeddings
6.5. Example: Semantic Similarity
sentences = [
"Học sinh quay trở lại trường học sau kỳ nghỉ tết.",
"Trẻ em đến trường học tập sau thời gian nghỉ tết.",
"Thời tiết hôm nay rất đẹp và nhiều nắng."
]
embeddings = encode(sentences)
# Cosine similarity
similarity_01 = F.cosine_similarity(
embeddings[0].unsqueeze(0),
embeddings[1].unsqueeze(0)
).item()
similarity_02 = F.cosine_similarity(
embeddings[0].unsqueeze(0),
embeddings[2].unsqueeze(0)
).item()
print(f"Similarity (Sentence 1, Sentence 2): {similarity_01:.4f}")
print(f"Similarity (Sentence 1, Sentence 3): {similarity_02:.4f}")
6.6. Embedding Output
Với batch có (B) câu đầu vào, mô hình trả về:
[ E \in \mathbb{R}^{B \times 768} ]
Mỗi hàng tương ứng với embedding 768 chiều của một câu hoặc đoạn văn.
Các embedding được chuẩn hóa L2, do đó có thể sử dụng tích vô hướng để tính cosine similarity:
[ \operatorname{sim}(u,v)=u^\top v ]
7. Limitations
7.1. Vietnamese Word Segmentation
PhoBERT yêu cầu văn bản đầu vào được tách từ trước.
Ví dụ:
Raw text:
Học sinh quay trở lại trường học.
Segmented text:
Học_sinh quay trở_lại trường_học .
Nếu không thực hiện word segmentation, chất lượng biểu diễn có thể bị ảnh hưởng.
7.2. Sequence Length
- Các đoạn văn trong tập huấn luyện được lọc ở khoảng 16–128 tokens.
- PhoBERT có giới hạn độ dài đầu vào tối đa 256 tokens.
- Khi đầu vào vượt quá
max_length, phần văn bản vượt giới hạn sẽ bị cắt nếu sử dụngtruncation=True.
Mô hình chưa được tối ưu riêng cho các văn bản dài như toàn bộ bài báo hoặc tài liệu nhiều trang.
7.3. Domain Limitation
Mô hình được fine-tune trên các đoạn văn báo chí tiếng Việt. Hiệu năng có thể khác biệt trên các lĩnh vực chuyên biệt như:
- Y tế.
- Pháp lý.
- Tài chính.
- Khoa học và kỹ thuật.
Việc fine-tune bổ sung trên dữ liệu thuộc miền đích có thể cần thiết.
7.4. Evaluation Limitation
Các kết quả STS đánh giá khả năng biểu diễn và đo tương đồng ngữ nghĩa giữa các cặp văn bản. Chúng không trực tiếp chứng minh hiệu quả của mô hình trên mọi tác vụ clustering hoặc semantic search.
Cần thực hiện đánh giá riêng trên từng tác vụ thực tế trước khi triển khai.
8. License
This model is fine-tuned from:
The upstream PhoBERT Base v2 model is published under the GNU Affero General Public License v3.0 (AGPL-3.0).
This repository declares AGPL-3.0 in alignment with the upstream model's published license.
Please refer to the original model repository and the included license terms:
The training dataset is not included in this repository. Users should independently verify the rights and applicable terms governing any data they use.
9. Citation
If you use PhoBERT as the base model in academic research or other publications, please cite the original PhoBERT paper:
@inproceedings{phobert,
title = {{PhoBERT: Pre-trained language models for Vietnamese}},
author = {Nguyen, Dat Quoc and Nguyen, Anh Tuan},
booktitle = {Findings of the Association for Computational Linguistics: EMNLP 2020},
year = {2020},
pages = {1037--1042}
}
Please also cite this repository when using PhoBERT-SimCSE in your research.
10. Acknowledgements
This project builds upon the Vietnamese pretrained language model PhoBERT developed by VinAI Research.
We thank the authors and contributors of PhoBERT and the open-source NLP community for their contributions to Vietnamese Natural Language Processing.
Base Model: vinai/phobert-base-v2