Tonic commited on
Commit
5171d49
·
verified ·
1 Parent(s): c5db054

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -16
app.py CHANGED
@@ -11,16 +11,33 @@ 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 👻[![Let's build the future of AI together! 🚀🤖](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
  """
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
  tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-mistral-7b-instruct')
21
  model = AutoModel.from_pretrained('intfloat/e5-mistral-7b-instruct', torch_dtype=torch.float16, device_map=device)
22
- # model.half()
23
- # model.to(device)
24
 
25
  def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
26
  left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
@@ -31,17 +48,15 @@ def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tenso
31
  batch_size = last_hidden_states.shape[0]
32
  return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
33
 
34
- def get_detailed_instruct(task_description: str, query: str) -> str:
35
- return f'Instruct: {task_description}\nQuery: {query}'
36
-
37
-
38
  @spaces.GPU
39
- def compute_embeddings(*input_texts):
40
-
41
  max_length = 2042
42
- task = 'Given a web search query, retrieve relevant passages that answer the query'
43
-
44
- processed_texts = [get_detailed_instruct(task, text) for text in input_texts]
 
 
 
45
  batch_dict = tokenizer(processed_texts, max_length=max_length - 1, return_attention_mask=False, padding=False, truncation=True)
46
  batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
47
  batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt')
@@ -56,12 +71,14 @@ def app_interface():
56
  with gr.Blocks() as demo:
57
  gr.Markdown(title)
58
  gr.Markdown(description)
 
 
59
 
60
- input_text_boxes = [gr.Textbox(label=f"Input Text {i+1}") for i in range(4)]
61
 
62
- compute_button = gr.Button("Compute Embeddings")
63
 
64
- output_display = gr.Dataframe(headers=["Embedding Value"], datatype=["number"])
65
 
66
  with gr.Row():
67
  with gr.Column():
@@ -73,7 +90,7 @@ def app_interface():
73
 
74
  compute_button.click(
75
  fn=compute_embeddings,
76
- inputs=input_text_boxes,
77
  outputs=output_display
78
  )
79
 
 
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
+
16
+ You can use this space in **two ways !** either select an embeddings mode or 'None' to speak with the e5mistral LLM 🤗
17
  """
18
 
19
  os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:30'
20
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
 
22
+ tasks = {
23
+ 'ArguAna': 'Given a claim, find documents that refute the claim',
24
+ 'ClimateFEVER': 'Given a claim about climate change, retrieve documents that support or refute the claim',
25
+ 'DBPedia': 'Given a query, retrieve relevant entity descriptions from DBPedia',
26
+ 'FEVER': 'Given a claim, retrieve documents that support or refute the claim',
27
+ 'FiQA2018': 'Given a financial question, retrieve user replies that best answer the question',
28
+ 'HotpotQA': 'Given a multi-hop question, retrieve documents that can help answer the question',
29
+ 'MSMARCO': 'Given a web search query, retrieve relevant passages that answer the query',
30
+ 'NFCorpus': 'Given a question, retrieve relevant documents that best answer the question',
31
+ 'NQ': 'Given a question, retrieve Wikipedia passages that answer the question',
32
+ 'QuoraRetrieval': 'Given a question, retrieve questions that are semantically equivalent to the given question',
33
+ 'SCIDOCS': 'Given a scientific paper title, retrieve paper abstracts that are cited by the given paper',
34
+ 'SciFact': 'Given a scientific claim, retrieve documents that support or refute the claim',
35
+ 'Touche2020': 'Given a question, retrieve detailed and persuasive arguments that answer the question',
36
+ 'TRECCOVID': 'Given a query on COVID-19, retrieve documents that answer the query',
37
+ }
38
+
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
 
42
  def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
43
  left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
 
48
  batch_size = last_hidden_states.shape[0]
49
  return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
50
 
 
 
 
 
51
  @spaces.GPU
52
+ def compute_embeddings(selected_task, *input_texts):
 
53
  max_length = 2042
54
+ if selected_task:
55
+ task = tasks[selected_task]
56
+ processed_texts = [f'Instruct: {task}\nQuery: {text}' for text in input_texts]
57
+ else:
58
+ processed_texts = [f'Instruct: {system_prompt}\nQuerry: {text}' for text in input_texts]
59
+ task = tasks[selected_task]
60
  batch_dict = tokenizer(processed_texts, max_length=max_length - 1, return_attention_mask=False, padding=False, truncation=True)
61
  batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
62
  batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt')
 
71
  with gr.Blocks() as demo:
72
  gr.Markdown(title)
73
  gr.Markdown(description)
74
+
75
+ task_dropdown = gr.Dropdown(list(tasks.keys()) + ["None"], label="Select a Task (Optional)", value="None")
76
 
77
+ input_text_boxes = gr.Textbox(label=f"Input Text")
78
 
79
+ compute_button = gr.Button("Try🐣🛌🏻e5")
80
 
81
+ output_display = gr.Textbox(label="🐣e5-mistral🛌🏻")
82
 
83
  with gr.Row():
84
  with gr.Column():
 
90
 
91
  compute_button.click(
92
  fn=compute_embeddings,
93
+ inputs=[task_dropdown] + input_text_boxes,
94
  outputs=output_display
95
  )
96