Gte Qwen2 7B Instruct
模型概述
模型特點
模型能力
使用案例
🚀 gte-Qwen2-7B-instruct
gte-Qwen2-7B-instruct 是 gte(通用文本嵌入)模型家族的最新模型,截至 2024 年 6 月 16 日,該模型在大規模文本嵌入基準測試 MTEB 基準 的英文和中文評估中均排名 第一。該模型能為文本提供高質量的嵌入表示,在多種自然語言處理任務中具有廣泛的應用前景,有助於提升信息檢索、文本分類等任務的性能。
🚀 快速開始
最近,通義團隊 發佈了通義千問 2 系列模型,我們基於 Qwen2-7B 大語言模型訓練了 gte-Qwen2-7B-instruct 模型。與 gte-Qwen1.5-7B-instruct 模型相比,gte-Qwen2-7B-instruct 模型在微調階段使用了相同的訓練數據和訓練策略,唯一的區別是將基礎模型升級為 Qwen2-7B。考慮到通義千問 2 系列模型相較於通義千問 1.5 系列的改進,我們也可以期待嵌入模型的性能得到相應提升。
✨ 主要特性
- 集成雙向注意力機制,豐富了上下文理解能力。
- 僅在查詢端應用指令調優,提高效率。
- 在龐大的多語言文本語料庫上進行全面訓練,涵蓋各種領域和場景。該訓練利用了弱監督和監督數據,確保模型適用於多種語言和廣泛的下游任務。
📦 安裝指南
transformers>=4.39.2
flash_attn>=2.5.6
💻 使用示例
基礎用法
使用 Sentence Transformers 庫調用模型:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Alibaba-NLP/gte-Qwen2-7B-instruct", trust_remote_code=True)
# 如果你想減少最大長度:
model.max_seq_length = 8192
queries = [
"how much protein should a female eat",
"summit define",
]
documents = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments.",
]
query_embeddings = model.encode(queries, prompt_name="query")
document_embeddings = model.encode(documents)
scores = (query_embeddings @ document_embeddings.T) * 100
print(scores.tolist())
你可以查看 config_sentence_transformers.json 以瞭解所有預構建的提示名稱。否則,你可以使用 model.encode(queries, prompt="Instruct: ...\nQuery: "
來使用你選擇的自定義提示。
高級用法
使用 Transformers 庫調用模型:
import torch
import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
def last_token_pool(last_hidden_states: Tensor,
attention_mask: Tensor) -> Tensor:
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
if left_padding:
return last_hidden_states[:, -1]
else:
sequence_lengths = attention_mask.sum(dim=1) - 1
batch_size = last_hidden_states.shape[0]
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
def get_detailed_instruct(task_description: str, query: str) -> str:
return f'Instruct: {task_description}\nQuery: {query}'
# 每個查詢必須附帶一個描述任務的單句指令
task = 'Given a web search query, retrieve relevant passages that answer the query'
queries = [
get_detailed_instruct(task, 'how much protein should a female eat'),
get_detailed_instruct(task, 'summit define')
]
# 檢索文檔無需添加指令
documents = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
]
input_texts = queries + documents
tokenizer = AutoTokenizer.from_pretrained('Alibaba-NLP/gte-Qwen2-7B-instruct', trust_remote_code=True)
model = AutoModel.from_pretrained('Alibaba-NLP/gte-Qwen2-7B-instruct', trust_remote_code=True)
max_length = 8192
# 對輸入文本進行分詞
batch_dict = tokenizer(input_texts, max_length=max_length, padding=True, truncation=True, return_tensors='pt')
outputs = model(**batch_dict)
embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
# 歸一化嵌入向量
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T) * 100
print(scores.tolist())
通過 infinity(一個遵循 MIT 許可的推理服務器)使用模型:
# 需要約 16 - 32GB VRAM,NVIDIA 計算能力 >= 8.0
docker run \
-v $PWD/data:/app/.cache --gpus "0" -p "7997":"7997" \
michaelf34/infinity:0.0.68-trt-onnx \
v2 --model-id Alibaba-NLP/gte-Qwen2-7B-instruct --revision "refs/pr/38" --dtype bfloat16 --batch-size 8 --device cuda --engine torch --port 7997 --no-bettertransformer
📚 詳細文檔
評估
MTEB & C-MTEB
你可以使用 scripts/eval_mteb.py 來複現 gte-Qwen2-7B-instruct 在 MTEB(英文)/C-MTEB(中文)上的以下結果:
模型名稱 | MTEB(56) | C-MTEB(35) | MTEB-fr(26) | MTEB-pl(26) |
---|---|---|---|---|
bge-base-en-1.5 | 64.23 | - | - | - |
bge-large-en-1.5 | 63.55 | - | - | - |
gte-large-en-v1.5 | 65.39 | - | - | - |
gte-base-en-v1.5 | 64.11 | - | - | - |
mxbai-embed-large-v1 | 64.68 | - | - | - |
acge_text_embedding | - | 69.07 | - | - |
stella-mrl-large-zh-v3.5-1792d | - | 68.55 | - | - |
gte-large-zh | - | 66.72 | - | - |
multilingual-e5-base | 59.45 | 56.21 | - | - |
multilingual-e5-large | 61.50 | 58.81 | - | - |
e5-mistral-7b-instruct | 66.63 | 60.81 | - | - |
gte-Qwen1.5-7B-instruct | 67.34 | 69.52 | - | - |
NV-Embed-v1 | 69.32 | - | - | - |
gte-Qwen2-7B-instruct | 70.24 | 72.05 | 68.25 | 67.86 |
gte-Qwen2-1.5B-instruct | 67.16 | 67.65 | 66.60 | 64.04 |
GTE 模型
gte 系列模型一直髮布兩種類型的模型:僅編碼器模型(基於 BERT 架構)和解碼器模型(基於大語言模型架構)。
模型 | 語言 | 最大序列長度 | 維度 | 模型大小(內存使用,fp32) |
---|---|---|---|---|
GTE-large-zh | 中文 | 512 | 1024 | 1.25GB |
GTE-base-zh | 中文 | 512 | 512 | 0.41GB |
GTE-small-zh | 中文 | 512 | 512 | 0.12GB |
GTE-large | 英文 | 512 | 1024 | 1.25GB |
GTE-base | 英文 | 512 | 512 | 0.21GB |
GTE-small | 英文 | 512 | 384 | 0.10GB |
GTE-large-en-v1.5 | 英文 | 8192 | 1024 | 1.74GB |
GTE-base-en-v1.5 | 英文 | 8192 | 768 | 0.51GB |
GTE-Qwen1.5-7B-instruct | 多語言 | 32000 | 4096 | 26.45GB |
GTE-Qwen2-7B-instruct | 多語言 | 32000 | 3584 | 26.45GB |
GTE-Qwen2-1.5B-instruct | 多語言 | 32000 | 1536 | 6.62GB |
雲 API 服務
除了開源的 GTE 系列模型外,GTE 系列模型還可以在阿里雲上作為商業 API 服務使用。
請注意,商業 API 背後的模型與開源模型並不完全相同。
🔧 技術細節
模型信息
屬性 | 詳情 |
---|---|
模型類型 | 多語言文本嵌入模型 |
訓練數據 | 龐大的多語言文本語料庫,涵蓋各種領域和場景,利用了弱監督和監督數據 |
模型大小 | 7B |
嵌入維度 | 3584 |
最大輸入令牌數 | 32k |
社區支持
微調
GTE 模型可以使用第三方框架 SWIFT 進行微調。
pip install ms-swift -U
# 查看:https://swift.readthedocs.io/en/latest/BestPractices/Embedding.html
nproc_per_node=8
NPROC_PER_NODE=$nproc_per_node \
USE_HF=1 \
swift sft \
--model Alibaba-NLP/gte-Qwen2-7B-instruct \
--train_type lora \
--dataset 'sentence-transformers/stsb' \
--torch_dtype bfloat16 \
--num_train_epochs 10 \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 1 \
--gradient_accumulation_steps $(expr 64 / $nproc_per_node) \
--eval_steps 100 \
--save_steps 100 \
--eval_strategy steps \
--use_chat_template false \
--save_total_limit 5 \
--logging_steps 5 \
--output_dir output \
--warmup_ratio 0.05 \
--learning_rate 5e-6 \
--deepspeed zero3 \
--dataloader_num_workers 4 \
--task_type embedding \
--loss_type cosine_similarity \
--dataloader_drop_last true
📄 許可證
如果你覺得我們的論文或模型有幫助,請考慮引用:
@article{li2023towards,
title={Towards general text embeddings with multi-stage contrastive learning},
author={Li, Zehan and Zhang, Xin and Zhang, Yanzhao and Long, Dingkun and Xie, Pengjun and Zhang, Meishan},
journal={arXiv preprint arXiv:2308.03281},
year={2023}
}



