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}
}



