Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -11,15 +11,32 @@ title = """
|
|
11 |
description = """
|
12 |
You can use this Space to test out the current model [intfloat/e5-mistral-7b-instruct](https://huggingface.co/intfloat/e5-mistral-7b-instruct). e5mistral has a larger context window, a different prompting/return mechanism and generally better results than other embedding models.
|
13 |
You can also use 🐣e5-mistral🛌🏻 by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/Tonic/e5?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
|
14 |
-
Join us : 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community
|
|
|
15 |
"""
|
16 |
|
17 |
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:30'
|
18 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
|
25 |
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
|
@@ -30,17 +47,15 @@ def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tenso
|
|
30 |
batch_size = last_hidden_states.shape[0]
|
31 |
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
|
32 |
|
33 |
-
def get_detailed_instruct(task_description: str, query: str) -> str:
|
34 |
-
return f'Instruct: {task_description}\nQuery: {query}'
|
35 |
-
|
36 |
-
|
37 |
@spaces.GPU
|
38 |
-
def compute_embeddings(*input_texts):
|
39 |
-
tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-mistral-7b-instruct')
|
40 |
-
model = AutoModel.from_pretrained('intfloat/e5-mistral-7b-instruct', torch_dtype=torch.float16, device_map=device)
|
41 |
max_length = 2042
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
44 |
batch_dict = tokenizer(processed_texts, max_length=max_length - 1, return_attention_mask=False, padding=False, truncation=True)
|
45 |
batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
|
46 |
batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt')
|
@@ -55,12 +70,14 @@ def app_interface():
|
|
55 |
with gr.Blocks() as demo:
|
56 |
gr.Markdown(title)
|
57 |
gr.Markdown(description)
|
|
|
|
|
58 |
|
59 |
-
input_text_boxes =
|
60 |
|
61 |
-
compute_button = gr.Button("
|
62 |
|
63 |
-
output_display = gr.
|
64 |
|
65 |
with gr.Row():
|
66 |
with gr.Column():
|
@@ -72,7 +89,7 @@ def app_interface():
|
|
72 |
|
73 |
compute_button.click(
|
74 |
fn=compute_embeddings,
|
75 |
-
inputs=input_text_boxes,
|
76 |
outputs=output_display
|
77 |
)
|
78 |
|
|
|
11 |
description = """
|
12 |
You can use this Space to test out the current model [intfloat/e5-mistral-7b-instruct](https://huggingface.co/intfloat/e5-mistral-7b-instruct). e5mistral has a larger context window, a different prompting/return mechanism and generally better results than other embedding models.
|
13 |
You can also use 🐣e5-mistral🛌🏻 by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/Tonic/e5?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
|
14 |
+
Join us : 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community 👻[![(https://discordapp.com/api/guilds/1109943800132010065/widget.png)](https://discord.gg/GWpVpekp) On 🤗Huggingface: [TeamTonic](https://huggingface.co/TeamTonic) & [MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Polytonic](https://github.com/tonic-ai) & contribute to 🌟 [Poly](https://github.com/tonic-ai/poly) 🤗Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant 🤗
|
15 |
+
You can use this space in **two ways !** either select an embeddings mode or 'None' to speak with the e5mistral LLM 🤗
|
16 |
"""
|
17 |
|
18 |
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:30'
|
19 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
20 |
|
21 |
+
tasks = {
|
22 |
+
'ArguAna': 'Given a claim, find documents that refute the claim',
|
23 |
+
'ClimateFEVER': 'Given a claim about climate change, retrieve documents that support or refute the claim',
|
24 |
+
'DBPedia': 'Given a query, retrieve relevant entity descriptions from DBPedia',
|
25 |
+
'FEVER': 'Given a claim, retrieve documents that support or refute the claim',
|
26 |
+
'FiQA2018': 'Given a financial question, retrieve user replies that best answer the question',
|
27 |
+
'HotpotQA': 'Given a multi-hop question, retrieve documents that can help answer the question',
|
28 |
+
'MSMARCO': 'Given a web search query, retrieve relevant passages that answer the query',
|
29 |
+
'NFCorpus': 'Given a question, retrieve relevant documents that best answer the question',
|
30 |
+
'NQ': 'Given a question, retrieve Wikipedia passages that answer the question',
|
31 |
+
'QuoraRetrieval': 'Given a question, retrieve questions that are semantically equivalent to the given question',
|
32 |
+
'SCIDOCS': 'Given a scientific paper title, retrieve paper abstracts that are cited by the given paper',
|
33 |
+
'SciFact': 'Given a scientific claim, retrieve documents that support or refute the claim',
|
34 |
+
'Touche2020': 'Given a question, retrieve detailed and persuasive arguments that answer the question',
|
35 |
+
'TRECCOVID': 'Given a query on COVID-19, retrieve documents that answer the query',
|
36 |
+
}
|
37 |
+
|
38 |
+
tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-mistral-7b-instruct')
|
39 |
+
model = AutoModel.from_pretrained('intfloat/e5-mistral-7b-instruct', torch_dtype=torch.float16, device_map=device)
|
40 |
|
41 |
def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
|
42 |
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
|
|
|
47 |
batch_size = last_hidden_states.shape[0]
|
48 |
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
|
49 |
|
|
|
|
|
|
|
|
|
50 |
@spaces.GPU
|
51 |
+
def compute_embeddings(selected_task, *input_texts):
|
|
|
|
|
52 |
max_length = 2042
|
53 |
+
if selected_task:
|
54 |
+
task = tasks[selected_task]
|
55 |
+
processed_texts = [f'Instruct: {task}\nQuery: {text}' for text in input_texts]
|
56 |
+
else:
|
57 |
+
processed_texts = [f'Instruct: {system_prompt}\nQuerry: {text}' for text in input_texts]
|
58 |
+
task = tasks[selected_task]
|
59 |
batch_dict = tokenizer(processed_texts, max_length=max_length - 1, return_attention_mask=False, padding=False, truncation=True)
|
60 |
batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
|
61 |
batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt')
|
|
|
70 |
with gr.Blocks() as demo:
|
71 |
gr.Markdown(title)
|
72 |
gr.Markdown(description)
|
73 |
+
|
74 |
+
task_dropdown = gr.Dropdown(list(tasks.keys()) + ["None"], label="Select a Task (Optional)", value="None")
|
75 |
|
76 |
+
input_text_boxes = gr.Textbox(label=f"Input Text")
|
77 |
|
78 |
+
compute_button = gr.Button("Try🐣🛌🏻e5")
|
79 |
|
80 |
+
output_display = gr.Textbox(label="🐣e5-mistral🛌🏻")
|
81 |
|
82 |
with gr.Row():
|
83 |
with gr.Column():
|
|
|
89 |
|
90 |
compute_button.click(
|
91 |
fn=compute_embeddings,
|
92 |
+
inputs=[task_dropdown] + input_text_boxes,
|
93 |
outputs=output_display
|
94 |
)
|
95 |
|