Views
No views yet
Alibaba-NLP/gte-large-en-v1.5 and Alibaba-NLP/gte-Qwen2-1.5B-instruct. Thanks for
their contributions!Instruct: Given a web search query, retrieve relevant passages that answer the query.\nQuery: {query}Instruct: Retrieve semantically similar text.\nQuery: {query}2_Dense_{dims}
folders, where dims represents the final vector dimension.2_Dense_256 folder stores Linear weights that convert vector dimensions to 256 dimensions.
Please refer to the following chapters for specific instructions on how to use them.SentenceTransformers or transformers library to encode text.1from sentence_transformers import SentenceTransformer
2
3# This model supports two prompts: "s2p_query" and "s2s_query" for sentence-to-passage and sentence-to-sentence tasks, respectively.
4# They are defined in `config_sentence_transformers.json`
5query_prompt_name = "s2p_query"
6queries = [
7 "What are some ways to reduce stress?",
8 "What are the benefits of drinking green tea?",
9]
10# docs do not need any prompts
11docs = [
12 "There are many effective ways to reduce stress. Some common techniques include deep breathing, meditation, and physical activity. Engaging in hobbies, spending time in nature, and connecting with loved ones can also help alleviate stress. Additionally, setting boundaries, practicing self-care, and learning to say no can prevent stress from building up.",
13 "Green tea has been consumed for centuries and is known for its potential health benefits. It contains antioxidants that may help protect the body against damage caused by free radicals. Regular consumption of green tea has been associated with improved heart health, enhanced cognitive function, and a reduced risk of certain types of cancer. The polyphenols in green tea may also have anti-inflammatory and weight loss properties.",
14]
15
16# !The default dimension is 1024, if you need other dimensions, please clone the model and modify `modules.json` to replace `2_Dense_1024` with another dimension, e.g. `2_Dense_256` or `2_Dense_8192` !
17# on gpu
18model = SentenceTransformer("dunzhang/stella_en_400M_v5", trust_remote_code=True).cuda()
19# you can also use this model without the features of `use_memory_efficient_attention` and `unpad_inputs`. It can be worked in CPU.
20# model = SentenceTransformer(
21# "dunzhang/stella_en_400M_v5",
22# trust_remote_code=True,
23# device="cpu",
24# config_kwargs={"use_memory_efficient_attention": False, "unpad_inputs": False}
25# )
26query_embeddings = model.encode(queries, prompt_name=query_prompt_name)
27doc_embeddings = model.encode(docs)
28print(query_embeddings.shape, doc_embeddings.shape)
29# (2, 1024) (2, 1024)
30
31similarities = model.similarity(query_embeddings, doc_embeddings)
32print(similarities)
33# tensor([[0.8398, 0.2990],
34# [0.3282, 0.8095]])1import os
2import torch
3from transformers import AutoModel, AutoTokenizer
4from sklearn.preprocessing import normalize
5
6query_prompt = "Instruct: Given a web search query, retrieve relevant passages that answer the query.\nQuery: "
7queries = [
8 "What are some ways to reduce stress?",
9 "What are the benefits of drinking green tea?",
10]
11queries = [query_prompt + query for query in queries]
12# docs do not need any prompts
13docs = [
14 "There are many effective ways to reduce stress. Some common techniques include deep breathing, meditation, and physical activity. Engaging in hobbies, spending time in nature, and connecting with loved ones can also help alleviate stress. Additionally, setting boundaries, practicing self-care, and learning to say no can prevent stress from building up.",
15 "Green tea has been consumed for centuries and is known for its potential health benefits. It contains antioxidants that may help protect the body against damage caused by free radicals. Regular consumption of green tea has been associated with improved heart health, enhanced cognitive function, and a reduced risk of certain types of cancer. The polyphenols in green tea may also have anti-inflammatory and weight loss properties.",
16]
17
18# The path of your model after cloning it
19model_dir = "{Your MODEL_PATH}"
20
21vector_dim = 1024
22vector_linear_directory = f"2_Dense_{vector_dim}"
23model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).cuda().eval()
24# you can also use this model without the features of `use_memory_efficient_attention` and `unpad_inputs`. It can be worked in CPU.
25# model = AutoModel.from_pretrained(model_dir, trust_remote_code=True,use_memory_efficient_attention=False,unpad_inputs=False).cuda().eval()
26tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
27vector_linear = torch.nn.Linear(in_features=model.config.hidden_size, out_features=vector_dim)
28vector_linear_dict = {
29 k.replace("linear.", ""): v for k, v in
30 torch.load(os.path.join(model_dir, f"{vector_linear_directory}/pytorch_model.bin")).items()
31}
32vector_linear.load_state_dict(vector_linear_dict)
33vector_linear.cuda()
34
35# Embed the queries
36with torch.no_grad():
37 input_data = tokenizer(queries, padding="longest", truncation=True, max_length=512, return_tensors="pt")
38 input_data = {k: v.cuda() for k, v in input_data.items()}
39 attention_mask = input_data["attention_mask"]
40 last_hidden_state = model(**input_data)[0]
41 last_hidden = last_hidden_state.masked_fill(~attention_mask[..., None].bool(), 0.0)
42 query_vectors = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
43 query_vectors = normalize(vector_linear(query_vectors).cpu().numpy())
44
45# Embed the documents
46with torch.no_grad():
47 input_data = tokenizer(docs, padding="longest", truncation=True, max_length=512, return_tensors="pt")
48 input_data = {k: v.cuda() for k, v in input_data.items()}
49 attention_mask = input_data["attention_mask"]
50 last_hidden_state = model(**input_data)[0]
51 last_hidden = last_hidden_state.masked_fill(~attention_mask[..., None].bool(), 0.0)
52 docs_vectors = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
53 docs_vectors = normalize(vector_linear(docs_vectors).cpu().numpy())
54
55print(query_vectors.shape, docs_vectors.shape)
56# (2, 1024) (2, 1024)
57
58similarities = query_vectors @ docs_vectors.T
59print(similarities)
60# [[0.8397531 0.29900077]
61# [0.32818374 0.80954516]]Alibaba-NLP/gte-Qwen2-1.5B-instruct or intfloat/e5-mistral-7b-instruct