UKPLab / sentence-transformers

State-of-the-Art Text Embeddings
https://www.sbert.net
Apache License 2.0
15k stars 2.45k forks source link

Query/Document/etc. templates #2362

Closed michaelfeil closed 6 months ago

michaelfeil commented 10 months ago

A wide number of MTEB models achieve SotA by using some query / document / passage template: https://huggingface.co/spaces/mteb/leaderboard

The special tokens for query/passage is up to the model author. They are important to match, and usually, there are only few options (2).

e.g. https://huggingface.co/BAAI/bge-small-en

from sentence_transformers import SentenceTransformer
queries = ['query_1', 'query_2']
passages = ["样例文档-1", "样例文档-2"]
instruction = "为这个句子生成表示以用于检索相关文章:"

model = SentenceTransformer('BAAI/bge-large-zh-v1.5')
q_embeddings = model.encode([instruction+q for q in queries], normalize_embeddings=True)
p_embeddings = model.encode(passages, normalize_embeddings=True)
scores = q_embeddings @ p_embeddings.T

e5-large uses:

input_texts = ['query: how much protein should a female eat',
               'query: summit define',
               "passage: 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.",
               "passage: 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."]

tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-large-v2')
model = AutoModel.from_pretrained('intfloat/e5-large-v2')

I would suggest to have an optional field in one of the config fields. config.json -> https://huggingface.co/thenlper/gte-large/blob/main/config.json sentence_bert_config.json -> https://huggingface.co/thenlper/gte-large/blob/main/sentence_bert_config.json

discussion

With this, also a RestAPI could take the field:

"inputs": [
    {
        "input":"how much protein should a female eat", 
        "type": "query"
    },
    {
        "input":"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.", 
        "type": "passage"
    }
]

Related: https://github.com/michaelfeil/infinity/issues/34 @arbi-dev

@tomaarsen and maybe maintainers of https://github.com/huggingface/text-embeddings-inference

tomaarsen commented 8 months ago

I'm certainly in favor of this idea. See also #2439 which is very much related.

michaelfeil commented 6 months ago

Closing this in favor of #2439 Thanks Tom!