chuhac commited on
Commit
f12abf4
1 Parent(s): 7c74a7f

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +92 -1
README.md CHANGED
@@ -8,4 +8,95 @@ tags:
8
  license: apache-2.0
9
  ---
10
 
11
- Unofficial bf16 Implementation of bge-en-icl.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  license: apache-2.0
9
  ---
10
 
11
+ **Unofficial bf16 Implementation of bge-en-icl.**
12
+
13
+ ## Using HuggingFace Transformers
14
+ With the transformers package, you can use the model like this: First, you pass your input through the transformer model, then you select the last hidden state of the first token (i.e., [CLS]) as the sentence embedding.
15
+
16
+ ```python
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+
21
+ from torch import Tensor
22
+ from transformers import AutoTokenizer, AutoModel
23
+
24
+
25
+ def last_token_pool(last_hidden_states: Tensor,
26
+ attention_mask: Tensor) -> Tensor:
27
+ left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
28
+ if left_padding:
29
+ return last_hidden_states[:, -1]
30
+ else:
31
+ sequence_lengths = attention_mask.sum(dim=1) - 1
32
+ batch_size = last_hidden_states.shape[0]
33
+ return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
34
+
35
+
36
+ def get_detailed_instruct(task_description: str, query: str) -> str:
37
+ return f'<instruct>{task_description}\n<query>{query}'
38
+
39
+ def get_detailed_example(task_description: str, query: str, response: str) -> str:
40
+ return f'<instruct>{task_description}\n<query>{query}\n<response>{response}'
41
+
42
+ def get_new_queries(queries, query_max_len, examples_prefix, tokenizer):
43
+ inputs = tokenizer(
44
+ queries,
45
+ max_length=query_max_len - len(tokenizer('<s>', add_special_tokens=False)['input_ids']) - len(
46
+ tokenizer('\n<response></s>', add_special_tokens=False)['input_ids']),
47
+ return_token_type_ids=False,
48
+ truncation=True,
49
+ return_tensors=None,
50
+ add_special_tokens=False
51
+ )
52
+ prefix_ids = tokenizer(examples_prefix, add_special_tokens=False)['input_ids']
53
+ suffix_ids = tokenizer('\n<response>', add_special_tokens=False)['input_ids']
54
+ new_max_length = (len(prefix_ids) + len(suffix_ids) + query_max_len + 8) // 8 * 8 + 8
55
+ new_queries = tokenizer.batch_decode(inputs['input_ids'])
56
+ for i in range(len(new_queries)):
57
+ new_queries[i] = examples_prefix + new_queries[i] + '\n<response>'
58
+ return new_max_length, new_queries
59
+
60
+ task = 'Given a web search query, retrieve relevant passages that answer the query.'
61
+ examples = [
62
+ {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
63
+ 'query': 'what is a virtual interface',
64
+ 'response': "A virtual interface is a software-defined abstraction that mimics the behavior and characteristics of a physical network interface. It allows multiple logical network connections to share the same physical network interface, enabling efficient utilization of network resources. Virtual interfaces are commonly used in virtualization technologies such as virtual machines and containers to provide network connectivity without requiring dedicated hardware. They facilitate flexible network configurations and help in isolating network traffic for security and management purposes."},
65
+ {'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
66
+ 'query': 'causes of back pain in female for a week',
67
+ 'response': "Back pain in females lasting a week can stem from various factors. Common causes include muscle strain due to lifting heavy objects or improper posture, spinal issues like herniated discs or osteoporosis, menstrual cramps causing referred pain, urinary tract infections, or pelvic inflammatory disease. Pregnancy-related changes can also contribute. Stress and lack of physical activity may exacerbate symptoms. Proper diagnosis by a healthcare professional is crucial for effective treatment and management."}
68
+ ]
69
+ examples = [get_detailed_example(e['instruct'], e['query'], e['response']) for e in examples]
70
+ examples_prefix = '\n\n'.join(examples) + '\n\n' # if there not exists any examples, just set examples_prefix = ''
71
+ queries = [
72
+ get_detailed_instruct(task, 'how much protein should a female eat'),
73
+ get_detailed_instruct(task, 'summit define')
74
+ ]
75
+ documents = [
76
+ "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.",
77
+ "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."
78
+ ]
79
+ query_max_len, doc_max_len = 512, 512
80
+
81
+ tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-en-icl')
82
+ model = AutoModel.from_pretrained('BAAI/bge-en-icl')
83
+ model.eval()
84
+
85
+ new_query_max_len, new_queries = get_new_queries(queries, query_max_len, examples_prefix, tokenizer)
86
+
87
+ query_batch_dict = tokenizer(new_queries, max_length=new_query_max_len, padding=True, truncation=True, return_tensors='pt')
88
+ doc_batch_dict = tokenizer(documents, max_length=doc_max_len, padding=True, truncation=True, return_tensors='pt')
89
+
90
+ with torch.no_grad():
91
+ query_outputs = model(**query_batch_dict)
92
+ query_embeddings = last_token_pool(query_outputs.last_hidden_state, query_batch_dict['attention_mask'])
93
+ doc_outputs = model(**doc_batch_dict)
94
+ doc_embeddings = last_token_pool(doc_outputs.last_hidden_state, doc_batch_dict['attention_mask'])
95
+
96
+ # normalize embeddings
97
+ query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
98
+ doc_embeddings = F.normalize(doc_embeddings, p=2, dim=1)
99
+ scores = (query_embeddings @ doc_embeddings.T) * 100
100
+ print(scores.tolist())
101
+
102
+ ```