Views
No views yet
LLM2Vec is a simple recipe to convert decoder-only LLMs into text encoders. It consists of 3 simple steps: 1) enabling bidirectional attention, 2) masked next token prediction, and 3) unsupervised contrastive learning. The model can be further fine-tuned to achieve state-of-the-art performance.
pip install llm2vec1from llm2vec import LLM2Vec
2
3import torch
4from transformers import AutoTokenizer, AutoModel, AutoConfig
5from peft import PeftModel
6
7# Loading base Mistral model, along with custom code that enables bidirectional connections in decoder-only LLMs. MNTP LoRA weights are merged into the base model.
8tokenizer = AutoTokenizer.from_pretrained(
9 "McGill-NLP/LLM2Vec-Llama-2-7b-chat-hf-mntp"
10)
11config = AutoConfig.from_pretrained(
12 "McGill-NLP/LLM2Vec-Llama-2-7b-chat-hf-mntp", trust_remote_code=True
13)
14model = AutoModel.from_pretrained(
15 "McGill-NLP/LLM2Vec-Llama-2-7b-chat-hf-mntp",
16 trust_remote_code=True,
17 config=config,
18 torch_dtype=torch.bfloat16,
19 device_map="cuda" if torch.cuda.is_available() else "cpu",
20)
21model = PeftModel.from_pretrained(
22 model,
23 "McGill-NLP/LLM2Vec-Llama-2-7b-chat-hf-mntp",
24)
25model = model.merge_and_unload() # This can take several minutes on cpu
26
27# Loading supervised model. This loads the trained LoRA weights on top of MNTP model. Hence the final weights are -- Base model + MNTP (LoRA) + supervised (LoRA).
28model = PeftModel.from_pretrained(
29 model, "McGill-NLP/LLM2Vec-Llama-2-7b-chat-hf-mntp-supervised"
30)
31
32# Wrapper for encoding and pooling operations
33l2v = LLM2Vec(model, tokenizer, pooling_mode="mean", max_length=512)
34
35# Encoding queries using instructions
36instruction = (
37 "Given a web search query, retrieve relevant passages that answer the query:"
38)
39queries = [
40 [instruction, "how much protein should a female eat"],
41 [instruction, "summit define"],
42]
43q_reps = l2v.encode(queries)
44
45# Encoding documents. Instruction are not required for documents
46documents = [
47 "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.",
48 "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.",
49]
50d_reps = l2v.encode(documents)
51
52# Compute cosine similarity
53q_reps_norm = torch.nn.functional.normalize(q_reps, p=2, dim=1)
54d_reps_norm = torch.nn.functional.normalize(d_reps, p=2, dim=1)
55cos_sim = torch.mm(q_reps_norm, d_reps_norm.transpose(0, 1))
56
57print(cos_sim)
58"""
59tensor([[0.5417, 0.0780],
60 [0.0627, 0.5726]])
61"""parishad.behnamghader@mila.quebec) and Vaibhav (vaibhav.adlakha@mila.quebec).