RerankerModel可以提供
“平滑”的“绝对”相关性分数
,
“平滑”对排序友好
,
“绝对”分数用于过滤低质量passage
,低质量passage过滤阈值推荐0.35或0.4。(RerankerModel provides
"smooth" (for reranking) and "meaningful" (for filtering bad passages with a threshold of 0.35 or 0.4) similarity score
, which help you figure out how relavent the query and passages are!)
最佳实践(Best practice)
:embedding召回top50-100片段,reranker对这50-100片段精排,最后取top5-10片段。(1. Get top 50-100 passages with
bce-embedding-base_v1
for "
recall
"; 2. Rerank passages with
bce-reranker-base_v1
and get top 5-10 for "
precision
" finally. )
B
ilingual and
C
rosslingual
Embedding
(
BCEmbedding
), developed by NetEase Youdao, encompasses
EmbeddingModel
and
RerankerModel
. The
EmbeddingModel
specializes in generating semantic vectors, playing a crucial role in semantic search and question-answering, and the
RerankerModel
excels at refining search results and ranking tasks.
BCEmbedding
serves as the cornerstone of Youdao's Retrieval Augmented Generation (RAG) implmentation, notably
QAnything
[
github
], an open-source implementation widely integrated in various Youdao products like
Youdao Speed Reading
and
Youdao Translation
.
Distinguished for its bilingual and crosslingual proficiency,
BCEmbedding
excels in bridging Chinese and English linguistic gaps, which achieves
Existing embedding models often encounter performance challenges in bilingual and crosslingual scenarios, particularly in Chinese, English and their crosslingual tasks.
BCEmbedding
, leveraging the strength of Youdao's translation engine, excels in delivering superior performance across monolingual, bilingual, and crosslingual settings.
EmbeddingModel
supports
Chinese (ch) and English (en)
(more languages support will come soon), while
RerankerModel
supports
Chinese (ch), English (en), Japanese (ja) and Korean (ko)
.
Bilingual and Crosslingual Proficiency
: Powered by Youdao's translation engine, excelling in Chinese, English and their crosslingual retrieval task, with upcoming support for additional languages.
RAG-Optimized
: Tailored for diverse RAG tasks including
translation, summarization, and question answering
, ensuring accurate
query understanding
. See
RAG Evaluations in LlamaIndex
.
Efficient and Precise Retrieval
: Dual-encoder for efficient retrieval of
EmbeddingModel
in first stage, and cross-encoder of
RerankerModel
for enhanced precision and deeper semantic analysis in second stage.
Broad Domain Adaptability
: Trained on diverse datasets for superior performance across various fields.
User-Friendly Design
: Instruction-free, versatile use for multiple tasks without specifying query instruction for each task.
Meaningful Reranking Scores
:
RerankerModel
provides relevant scores to improve result quality and optimize large language model performance.
Proven in Production
: Successfully implemented and validated in Youdao's products.
from BCEmbedding import EmbeddingModel
# list of sentences
sentences = ['sentence_0', 'sentence_1', ...]
# init embedding model
model = EmbeddingModel(model_name_or_path="maidalun1020/bce-embedding-base_v1")
# extract embeddings
embeddings = model.encode(sentences)
Use
RerankerModel
to calculate relevant scores and rerank:
from BCEmbedding import RerankerModel
# your query and corresponding passages
query = 'input_query'
passages = ['passage_0', 'passage_1', ...]
# construct sentence pairs
sentence_pairs = [[query, passage] for passage in passages]
# init reranker model
model = RerankerModel(model_name_or_path="maidalun1020/bce-reranker-base_v1")
# method 0: calculate scores of sentence pairs
scores = model.compute_score(sentence_pairs)
# method 1: rerank passages
rerank_results = model.rerank(query, passages)
NOTE:
In
RerankerModel.rerank
method, we provide an advanced preproccess that we use in production for making
sentence_pairs
, when "passages" are very long.
2. Based on
transformers
For
EmbeddingModel
:
from transformers import AutoModel, AutoTokenizer
# list of sentences
sentences = ['sentence_0', 'sentence_1', ...]
# init model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('maidalun1020/bce-embedding-base_v1')
model = AutoModel.from_pretrained('maidalun1020/bce-embedding-base_v1')
device = 'cuda'# if no GPU, set "cpu"
model.to(device)
# get inputs
inputs = tokenizer(sentences, padding=True, truncation=True, max_length=512, return_tensors="pt")
inputs_on_device = {k: v.to(self.device) for k, v in inputs.items()}
# get embeddings
outputs = model(**inputs_on_device, return_dict=True)
embeddings = outputs.last_hidden_state[:, 0] # cls pooler
embeddings = embeddings / embeddings.norm(dim=1, keepdim=True) # normalize
For
RerankerModel
:
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# init model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('maidalun1020/bce-reranker-base_v1')
model = AutoModelForSequenceClassification.from_pretrained('maidalun1020/bce-reranker-base_v1')
device = 'cuda'# if no GPU, set "cpu"
model.to(device)
# get inputs
inputs = tokenizer(sentence_pairs, padding=True, truncation=True, max_length=512, return_tensors="pt")
inputs_on_device = {k: v.to(device) for k, v in inputs.items()}
# calculate scores
scores = model(**inputs_on_device, return_dict=True).logits.view(-1,).float()
scores = torch.sigmoid(scores)
3. Based on
sentence_transformers
For
EmbeddingModel
:
from sentence_transformers import SentenceTransformer
# list of sentences
sentences = ['sentence_0', 'sentence_1', ...]
# init embedding model## New update for sentence-trnasformers. So clean up your "`SENTENCE_TRANSFORMERS_HOME`/maidalun1020_bce-embedding-base_v1" or "~/.cache/torch/sentence_transformers/maidalun1020_bce-embedding-base_v1" first for downloading new version.
model = SentenceTransformer("maidalun1020/bce-embedding-base_v1")
# extract embeddings
embeddings = model.encode(sentences, normalize_embeddings=True)
For
RerankerModel
:
from sentence_transformers import CrossEncoder
# init reranker model
model = CrossEncoder('maidalun1020/bce-reranker-base_v1', max_length=512)
# calculate scores of sentence pairs
scores = model.predict(sentence_pairs)
Integrations for RAG Frameworks
1. Used in
langchain
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.vectorstores.utils import DistanceStrategy
query = 'apples'
passages = [
'I like apples',
'I like oranges',
'Apples and oranges are fruits'
]
# init embedding model
model_name = 'maidalun1020/bce-embedding-base_v1'
model_kwargs = {'device': 'cuda'}
encode_kwargs = {'batch_size': 64, 'normalize_embeddings': True, 'show_progress_bar': False}
embed_model = HuggingFaceEmbeddings(
model_name=model_name,
model_kwargs=model_kwargs,
encode_kwargs=encode_kwargs
)
# example #1. extract embeddings
query_embedding = embed_model.embed_query(query)
passages_embeddings = embed_model.embed_documents(passages)
# example #2. langchain retriever example
faiss_vectorstore = FAISS.from_texts(passages, embed_model, distance_strategy=DistanceStrategy.MAX_INNER_PRODUCT)
retriever = faiss_vectorstore.as_retriever(search_type="similarity", search_kwargs={"score_threshold": 0.5, "k": 3})
related_passages = retriever.get_relevant_documents(query)
2. Used in
llama_index
from llama_index.embeddings import HuggingFaceEmbedding
from llama_index import VectorStoreIndex, ServiceContext, SimpleDirectoryReader
from llama_index.node_parser import SimpleNodeParser
from llama_index.llms import OpenAI
query = 'apples'
passages = [
'I like apples',
'I like oranges',
'Apples and oranges are fruits'
]
# init embedding model
model_args = {'model_name': 'maidalun1020/bce-embedding-base_v1', 'max_length': 512, 'embed_batch_size': 64, 'device': 'cuda'}
embed_model = HuggingFaceEmbedding(**model_args)
# example #1. extract embeddings
query_embedding = embed_model.get_query_embedding(query)
passages_embeddings = embed_model.get_text_embedding_batch(passages)
# example #2. rag example
llm = OpenAI(model='gpt-3.5-turbo-0613', api_key=os.environ.get('OPENAI_API_KEY'), api_base=os.environ.get('OPENAI_BASE_URL'))
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
documents = SimpleDirectoryReader(input_files=["BCEmbedding/tools/eval_rag/eval_pdfs/Comp_en_llama2.pdf"]).load_data()
node_parser = SimpleNodeParser.from_defaults(chunk_size=512)
nodes = node_parser.get_nodes_from_documents(documents[0:36])
index = VectorStoreIndex(nodes, service_context=service_context)
query_engine = index.as_query_engine()
response = query_engine.query("What is llama?")
⚙️ Evaluation
Evaluate Semantic Representation by MTEB
We provide evaluateion tools for
embedding
and
reranker
models, based on
MTEB
and
C_MTEB
.
Just run following cmd to evaluate
your_embedding_model
(e.g.
maidalun1020/bce-embedding-base_v1
) in
bilingual and crosslingual settings
(e.g.
["en", "zh", "en-zh", "zh-en"]
).
Run following cmd to evaluate
your_reranker_model
(e.g. "maidalun1020/bce-reranker-base_v1") in
bilingual and crosslingual settings
(e.g.
["en", "zh", "en-zh", "zh-en"]
).
LlamaIndex
is a famous data framework for LLM-based applications, particularly in RAG. Recently, the
LlamaIndex Blog
has evaluated the popular embedding and reranker models in RAG pipeline and attract great attention. Now, we follow its pipeline to evaluate our
BCEmbedding
.
Hit rate calculates the fraction of queries where the correct answer is found within the top-k retrieved documents. In simpler terms, it's about how often our system gets it right within the top few guesses.
The larger, the better.
Mean Reciprocal Rank (MRR):
For each query, MRR evaluates the system's accuracy by looking at the rank of the highest-placed relevant document. Specifically, it's the average of the reciprocals of these ranks across all the queries. So, if the first relevant document is the top result, the reciprocal rank is 1; if it's second, the reciprocal rank is 1/2, and so on.
The larger, the better.
In order to compare our
BCEmbedding
with other embedding and reranker models fairly, we provide a one-click script to reproduce results of the LlamaIndex Blog, including our
BCEmbedding
:
The evaluation of
LlamaIndex Blog
is
monolingual, small amount of data, and specific domain
(just including "llama2" paper). In order to evaluate the
broad domain adaptability, bilingual and crosslingual capability
, we follow the blog to build a multiple domains evaluation dataset (includding "Computer Science", "Physics", "Biology", "Economics", "Math", and "Quantitative Finance"), named
CrosslingualMultiDomainsDataset
,
by OpenAI
gpt-4-1106-preview
for high quality
.
For users who prefer a hassle-free experience without the need to download and configure the model on their own systems,
BCEmbedding
is readily accessible through Youdao's API. This option offers a streamlined and efficient way to integrate BCEmbedding into your projects, bypassing the complexities of manual setup and maintenance. Detailed instructions and comprehensive API documentation are available at
Youdao BCEmbedding API
. Here, you'll find all the necessary guidance to easily implement
BCEmbedding
across a variety of use cases, ensuring a smooth and effective integration for optimal results.
对于那些更喜欢直接调用api的用户,有道提供方便的
BCEmbedding
调用api。该方式是一种简化和高效的方式,将
BCEmbedding
集成到您的项目中,避开了手动设置和系统维护的复杂性。更详细的api调用接口说明详见
有道BCEmbedding API
。
🧲 WeChat Group
Welcome to scan the QR code below and join the WeChat group.
欢迎大家扫码加入官方微信交流群。
✏️ Citation
If you use
BCEmbedding
in your research or project, please feel free to cite and star it:
如果在您的研究或任何项目中使用本工作,烦请按照下方进行引用,并打个小星星~
@misc{youdao_bcembedding_2023,
title={BCEmbedding: Bilingual and Crosslingual Embedding for RAG},
author={NetEase Youdao, Inc.},
year={2023},
howpublished={\url{https://github.com/netease-youdao/BCEmbedding}}
}
bce-reranker-base_v1-GGUF huggingface.co is an AI model on huggingface.co that provides bce-reranker-base_v1-GGUF's model effect (), which can be used instantly with this gpustack bce-reranker-base_v1-GGUF model. huggingface.co supports a free trial of the bce-reranker-base_v1-GGUF model, and also provides paid use of the bce-reranker-base_v1-GGUF. Support call bce-reranker-base_v1-GGUF model through api, including Node.js, Python, http.
bce-reranker-base_v1-GGUF huggingface.co is an online trial and call api platform, which integrates bce-reranker-base_v1-GGUF's modeling effects, including api services, and provides a free online trial of bce-reranker-base_v1-GGUF, you can try bce-reranker-base_v1-GGUF online for free by clicking the link below.
gpustack bce-reranker-base_v1-GGUF online free url in huggingface.co:
bce-reranker-base_v1-GGUF is an open source model from GitHub that offers a free installation service, and any user can find bce-reranker-base_v1-GGUF on GitHub to install. At the same time, huggingface.co provides the effect of bce-reranker-base_v1-GGUF install, users can directly use bce-reranker-base_v1-GGUF installed effect in huggingface.co for debugging and trial. It also supports api for free installation.
bce-reranker-base_v1-GGUF install url in huggingface.co: