how to extract embedding for retrieval task
how can i use this model for retreival task , idont see any example for this other mask modelling
can i use this way
'import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
def average_pool(last_hidden_states: Tensor,
attention_mask: Tensor) -> Tensor:
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
def get_detailed_instruct(task_description: str, query: str) -> str:
return f'Instruct: {task_description}\nQuery: {query}'
Each query must come with a one-sentence instruction that describes the task
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, 'ๅ็็ๅฎถๅธธๅๆณ')
]
No need to add instruction for retrieval documents
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.",
"1.ๆธ
็ๅ็ไธ ๅๆ:ๅซฉๅ็ๅไธช ่ฐๆ:่ฑใ็ใ็ฝ็ณใ้ธก็ฒพ ๅๆณ: 1ใๅ็็จๅ่่็ๅๅป่กจ้ขไธๅฑ็ฎ,็จๅบๅญๅฎๅป็ค 2ใๆฆๆ็ปไธ(ๆฒกๆๆฆ่ๆฟๅฐฑ็จๅๆ
ขๆ
ขๅๆ็ปไธ) 3ใ้
็ง็ญๆพๆฒน,ๅ
ฅ่ฑ่ฑ็
ธๅบ้ฆๅณ 4ใๅ
ฅๅ็ไธๅฟซ้็ฟป็ไธๅ้ๅทฆๅณ,ๆพ็ใไธ็น็ฝ็ณๅ้ธก็ฒพ่ฐๅณๅบ้
2.้ฆ่ฑ็ๅ็ ๅๆ:ๅ็1ๅช ่ฐๆ:้ฆ่ฑใ่ๆซใๆฉๆฆๆฒนใ็ ๅๆณ: 1ใๅฐๅ็ๅป็ฎ,ๅๆ็ 2ใๆฒน้
8ๆ็ญๅ,ๅฐ่ๆซๆพๅ
ฅ็้ฆ 3ใ็้ฆๅ,ๅฐๅ็็ๆพๅ
ฅ,็ฟป็ 4ใๅจ็ฟป็็ๅๆถ,ๅฏไปฅไธๆถๅฐๅพ้
้ๅ ๆฐด,ไฝไธ่ฆๅคชๅค 5ใๆพๅ
ฅ็,็ๅ 6ใๅ็ๅทฎไธๅค่ฝฏๅ็ปตไบไนๅ,ๅฐฑๅฏไปฅๅ
ณ็ซ 7ใๆๅ
ฅ้ฆ่ฑ,ๅณๅฏๅบ้
"
]
input_texts = queries + documents
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id)
Tokenize the input texts
batch_dict = tokenizer(input_texts, max_length=512, padding=True, truncation=True, return_tensors='pt')
outputs = model(**batch_dict)
embeddings = average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
normalize embeddings
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T) * 100
print(scores.tolist())
=> [[91.92852783203125, 67.580322265625], [70.3814468383789, 92.1330795288086]]
'
Hello!
This model is currently only good at "mask filling", i.e. if you have a sentence like "I love going to [MASK]", it can predict the mask.
To turn this into an embedding model that's good for retrieval, someone has to finetune it on a question-answer or information retrieval dataset, e.g. with Sentence Transformers: https://sbert.net/
Currently, this has only been done for Arabic models: https://huggingface.co/models?library=sentence-transformers&other=eurobert&sort=trending
- Tom Aarsen