Views
No views yet
1import torch
2import torch.nn.functional as F
3from transformers import AutoTokenizer, AutoModel
4
5# Each query needs to be accompanied by an corresponding instruction describing the task.
6task_name_to_instruct = {"example": "Given a question, retrieve passages that answer the question",}
7
8query_prefix = "Instruct: "+task_name_to_instruct["example"]+"\nQuery: "
9queries = [
10 'are judo throws allowed in wrestling?',
11 'how to become a radiology technician in michigan?'
12 ]
13
14# No instruction needed for retrieval passages
15passage_prefix = ""
16passages = [
17 "Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.",
18 "Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan."
19]
20
21# load model with tokenizer
22model = AutoModel.from_pretrained('nvidia/NV-Embed-v2', trust_remote_code=True)
23
24# get the embeddings
25max_length = 32768
26query_embeddings = model.encode(queries, instruction=query_prefix, max_length=max_length)
27passage_embeddings = model.encode(passages, instruction=passage_prefix, max_length=max_length)
28
29# normalize embeddings
30query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
31passage_embeddings = F.normalize(passage_embeddings, p=2, dim=1)
32
33# get the embeddings with DataLoader (spliting the datasets into multiple mini-batches)
34# batch_size=2
35# query_embeddings = model._do_encode(queries, batch_size=batch_size, instruction=query_prefix, max_length=max_length, num_workers=32, return_numpy=True)
36# passage_embeddings = model._do_encode(passages, batch_size=batch_size, instruction=passage_prefix, max_length=max_length, num_workers=32, return_numpy=True)
37
38scores = (query_embeddings @ passage_embeddings.T) * 100
39print(scores.tolist())
40# [[87.42693328857422, 0.46283677220344543], [0.965264618396759, 86.03721618652344]]1import torch
2from sentence_transformers import SentenceTransformer
3
4# Each query needs to be accompanied by an corresponding instruction describing the task.
5task_name_to_instruct = {"example": "Given a question, retrieve passages that answer the question",}
6
7query_prefix = "Instruct: "+task_name_to_instruct["example"]+"\nQuery: "
8queries = [
9 'are judo throws allowed in wrestling?',
10 'how to become a radiology technician in michigan?'
11 ]
12
13# No instruction needed for retrieval passages
14passages = [
15 "Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.",
16 "Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan."
17]
18
19# load model with tokenizer
20model = SentenceTransformer('nvidia/NV-Embed-v2', trust_remote_code=True)
21model.max_seq_length = 32768
22model.tokenizer.padding_side="right"
23
24def add_eos(input_examples):
25 input_examples = [input_example + model.tokenizer.eos_token for input_example in input_examples]
26 return input_examples
27
28# get the embeddings
29batch_size = 2
30query_embeddings = model.encode(add_eos(queries), batch_size=batch_size, prompt=query_prefix, normalize_embeddings=True)
31passage_embeddings = model.encode(add_eos(passages), batch_size=batch_size, normalize_embeddings=True)
32
33scores = (query_embeddings @ passage_embeddings.T) * 100
34print(scores.tolist())1@article{lee2024nv,
2 title={NV-Embed: Improved Techniques for Training LLMs as Generalist Embedding Models},
3 author={Lee, Chankyu and Roy, Rajarshi and Xu, Mengyao and Raiman, Jonathan and Shoeybi, Mohammad and Catanzaro, Bryan and Ping, Wei},
4 journal={arXiv preprint arXiv:2405.17428},
5 year={2024}
6}1@article{moreira2024nv,
2 title={NV-Retriever: Improving text embedding models with effective hard-negative mining},
3 author={Moreira, Gabriel de Souza P and Osmulski, Radek and Xu, Mengyao and Ak, Ronay and Schifferer, Benedikt and Oldridge, Even},
4 journal={arXiv preprint arXiv:2407.15831},
5 year={2024}
6}1pip uninstall -y transformer-engine
2pip install torch==2.2.0
3pip install transformers==4.42.4
4pip install flash-attn==2.2.0
5pip install sentence-transformers==2.7.01from transformers import AutoModel
2from torch.nn import DataParallel
3
4embedding_model = AutoModel.from_pretrained("nvidia/NV-Embed-v2")
5for module_key, module in embedding_model._modules.items():
6 embedding_model._modules[module_key] = DataParallel(module)1git clone https://github.com/UKPLab/sentence-transformers.git
2cd sentence-transformers
3git checkout v2.7-release
4# Modify L353 in SentenceTransformer.py to **'extra_features["prompt_length"] = tokenized_prompt["input_ids"].shape[-1]'**.
5pip install -e .