节前,我们星球组织了一场算法岗技术&面试讨论会,邀请了一些互联网大厂朋友、参加社招和校招面试的同学.
针对算法岗技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备、面试常考点分享等热门话题进行了深入的讨论。
本文将会介绍如何使用 Sentence Transformers 对开源的Embedding模型bge-base-zh-v1.5
进行微调,并验证 Embedding 模型微调后的效果。
在RAG框架或者语义相似度计算任务时,Embedding模型是我们常常会打交道的模型。
Sentence Transformers
是一个 Python 库,用于使用和训练各种应用的Embedding模型,例如检索增强生成 (RAG)、语义搜索、语义文本相似度、释义挖掘 (paraphrase mining) 等等。其 3.0 版本的更新是该工程自创建以来最大的一次,引入了一种新的训练方法。
本文将会以智源研究院(BAAI)开源的Embedding模型bge-base-zh-v1.5
作为基准模型,展示如何使用Sentence Transformers
进行评估,并对其进行微调,验证微调后的模型效果会有所提升。
评估指标Baseline
使用LlamaIndex框架对RAG流程中的各种Retrieve算法,包括Embedding模型召回,进行了评估,评估指标采用Hit Rate
和MRR
。本文将继续使用这篇文章中给出的数据集进行评估。
示例评估代码如下:
# -*- coding: utf-8 -*-
# @file: bge_base_zh_eval.py
import os
import json
import time
import torch
from pprint import pprint
from sentence_transformers import SentenceTransformer
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sentence_transformers.util import cos_sim
project_dir = os.path.dirname(os.path.abspath(__file__)).split('/src')[0]
# data process
# load dataset, get corpus, queries, relevant_docs
with open(os.path.join(project_dir, "data/doc_qa.json"), "r", encoding="utf-8") as f:
content = json.loads(f.read())
corpus = content['corpus']
queries = content['queries']
relevant_docs = content['relevant_docs']
# # Load a model
# 替换成自己的模型完整路径或使用huggingface modl id
model_name = "bge-base-zh-v1.5"
model_path = os.path.join(project_dir, f"models/{model_name}")
model = SentenceTransformer(model_path, device="cuda" if torch.cuda.is_available() else "cpu")
print("Model loaded")
s_time = time.time()
# # Evaluate the model
evaluator = InformationRetrievalEvaluator(
queries=queries,
corpus=corpus,
relevant_docs=relevant_docs,
name=f"{os.path.basename(model_path)}",
score_functions={"cosine": cos_sim}
)
# Evaluate the model
result = evaluator(model)
pprint(result)
print(f"Time cost: {time.time() - s_time:.2f}s")
我们在评估器中传入queries, corpus, relevant_docs字典,加载完模型后即可进行评估。
评估结果在下文中给出,作为baseline(基准)指标。