Spaces:
Sleeping
Sleeping
Angelawork
commited on
Commit
·
5b06045
1
Parent(s):
51e6078
main app for topk responses API
Browse files- app.py +136 -0
- requirements.txt +7 -0
app.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import urllib.request
|
3 |
+
import gradio as gr
|
4 |
+
from transformers import T5Tokenizer, T5ForConditionalGeneration
|
5 |
+
import huggingface_hub
|
6 |
+
import re
|
7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
8 |
+
import torch
|
9 |
+
import time
|
10 |
+
import transformers
|
11 |
+
import requests
|
12 |
+
import globals
|
13 |
+
from utility import *
|
14 |
+
|
15 |
+
"""set up"""
|
16 |
+
huggingface_hub.login(token=globals.HF_TOKEN)
|
17 |
+
gemma_tokenizer = AutoTokenizer.from_pretrained(globals.gemma_2b_URL)
|
18 |
+
gemma_model = AutoModelForCausalLM.from_pretrained(globals.gemma_2b_URL)
|
19 |
+
|
20 |
+
falcon_tokenizer = AutoTokenizer.from_pretrained(globals.falcon_7b_URL, trust_remote_code=True, device_map=globals.device_map, offload_folder="offload")
|
21 |
+
falcon_model = AutoModelForCausalLM.from_pretrained(globals.falcon_7b_URL, trust_remote_code=True,
|
22 |
+
torch_dtype=torch.bfloat16, device_map=globals.device_map, offload_folder="offload")
|
23 |
+
|
24 |
+
def get_model(model_typ):
|
25 |
+
if model_typ not in ["gemma", "falcon", "falcon_api", "simplet5_base", "simplet5_large"]:
|
26 |
+
raise ValueError('Invalid model type. Choose "gemma", "falcon", "falcon_api","simplet5_base", "simplet5_large".')
|
27 |
+
if model_typ=="gemma":
|
28 |
+
tokenizer = gemma_tokenizer
|
29 |
+
model = gemma_model
|
30 |
+
prefix = globals.gemma_PREFIX
|
31 |
+
elif model_typ=="falcon_api":
|
32 |
+
prefix = globals.falcon_PREFIX
|
33 |
+
model=None
|
34 |
+
tokenizer = None
|
35 |
+
elif model_typ=="falcon":
|
36 |
+
tokenizer = falcon_tokenizer
|
37 |
+
model = falcon_model
|
38 |
+
prefix = globals.falcon_PREFIX
|
39 |
+
elif model_typ in ["simplet5_base","simplet5_large"]:
|
40 |
+
prefix = globals.simplet5_PREFIX
|
41 |
+
URL = globals.simplet5_base_URL if model_typ=="simplet5_base" else globals.simplet5_large_URL
|
42 |
+
T5_MODEL_PATH = f"https://huggingface.co/{URL}/resolve/main/{globals.T5_FILE_NAME}"
|
43 |
+
fetch_model(T5_MODEL_PATH, globals.T5_FILE_NAME)
|
44 |
+
tokenizer = T5Tokenizer.from_pretrained(URL)
|
45 |
+
model = T5ForConditionalGeneration.from_pretrained(URL)
|
46 |
+
return model, tokenizer, prefix
|
47 |
+
|
48 |
+
def topk_query(model_typ="gemma",prompt="She has a heart of gold",temperature=0.7,max_length=256):
|
49 |
+
if model_typ not in ["gemma","simplet5_base", "simplet5_large"]:
|
50 |
+
raise ValueError('Invalid model type. Choose "gemma", "simplet5_base", "simplet5_large".')
|
51 |
+
model, tokenizer, prefix = get_model(model_typ)
|
52 |
+
|
53 |
+
start_time = time.time()
|
54 |
+
input = prefix.replace("{fig}", prompt)
|
55 |
+
print(f"Input to model: \n{input}")
|
56 |
+
|
57 |
+
if model_typ in ["simplet5_base", "simplet5_large"]:
|
58 |
+
inputs = tokenizer(input, return_tensors="pt")
|
59 |
+
outputs = model.generate(
|
60 |
+
inputs["input_ids"],
|
61 |
+
temperature=temperature,
|
62 |
+
max_length=max_length,
|
63 |
+
num_beams=5,
|
64 |
+
num_return_sequences=5, # Generate 5 responses
|
65 |
+
early_stopping=True
|
66 |
+
)
|
67 |
+
|
68 |
+
response = [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
|
69 |
+
answer = [response.replace(input, "").strip() for response in response]
|
70 |
+
|
71 |
+
elif model_typ=="gemma":
|
72 |
+
inputs = tokenizer(input, return_tensors="pt")
|
73 |
+
generate_ids = gemma_model.generate(
|
74 |
+
inputs.input_ids,
|
75 |
+
max_length=max_length,
|
76 |
+
do_sample=True,
|
77 |
+
top_k=50,
|
78 |
+
temperature=temperature,
|
79 |
+
num_return_sequences=5,
|
80 |
+
eos_token_id=gemma_tokenizer.eos_token_id
|
81 |
+
)
|
82 |
+
outputs = gemma_tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
83 |
+
print(f"Model original output:{outputs}\n")
|
84 |
+
answer = [post_process(output,input).replace("\n", "") for output in outputs]
|
85 |
+
|
86 |
+
# TODO: falcon's outputs dont have much differences, not used in topk response
|
87 |
+
# elif model_typ=="falcon_api":
|
88 |
+
# API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
|
89 |
+
# headers = {"Authorization": f"Bearer {access_token}"}
|
90 |
+
# response = api_query(API_URL=API_URL, headers=headers, payload={
|
91 |
+
# "inputs": input,
|
92 |
+
# "parameters": {
|
93 |
+
# "temperature": temperature,
|
94 |
+
# "top_k": 50,
|
95 |
+
# "num_return_sequences": 5
|
96 |
+
# }
|
97 |
+
# })
|
98 |
+
# print(response)
|
99 |
+
# answer = [post_process(item["generated_text"], input) for item in response]
|
100 |
+
else:
|
101 |
+
raise ValueError('Invalid model type. Choose "gemma", "simplet5_base", "simplet5_large".')
|
102 |
+
|
103 |
+
print(f"Time taken: {time.time()-start_time:.2f} seconds")
|
104 |
+
print(f"processed model output: {answer}")
|
105 |
+
|
106 |
+
return answer
|
107 |
+
|
108 |
+
topk_iface = gr.Interface(
|
109 |
+
fn=topk_query,
|
110 |
+
inputs=[
|
111 |
+
gr.Dropdown(
|
112 |
+
choices=["gemma", "simplet5_base", "simplet5_large"],
|
113 |
+
label="Model Type",
|
114 |
+
value="gemma"
|
115 |
+
),
|
116 |
+
gr.Textbox(label="Prompt", placeholder="Enter your prompt here"),
|
117 |
+
gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.7, label="Temperature"),
|
118 |
+
gr.Slider(minimum=50, maximum=512, step=10, value=256, label="Max Length")
|
119 |
+
],
|
120 |
+
outputs=[
|
121 |
+
gr.Textbox(label="Response 1"),
|
122 |
+
gr.Textbox(label="Response 2"),
|
123 |
+
gr.Textbox(label="Response 3"),
|
124 |
+
gr.Textbox(label="Response 4"),
|
125 |
+
gr.Textbox(label="Response 5")
|
126 |
+
],theme=gr.themes.Soft(),
|
127 |
+
title=globals.TITLE,
|
128 |
+
description="Generate multiple responses (top 5) based on input sentence, prefix, and temperature. Literal meanings/explanations are provided based on the input figurative sentence.",
|
129 |
+
examples=[
|
130 |
+
["gemma", "Time flies when you're having fun",0.7],
|
131 |
+
["simplet5_large", "She has a heart of gold",0.5],
|
132 |
+
["gemma", "The sky is the limit",0.6]
|
133 |
+
]
|
134 |
+
)
|
135 |
+
if __name__ == '__main__':
|
136 |
+
topk_iface.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub>=0.23.2
|
2 |
+
llama-cpp-python==0.1.62
|
3 |
+
transformers==4.42.4
|
4 |
+
sentence_transformers
|
5 |
+
sentencepiece
|
6 |
+
accelerate==0.32.1
|
7 |
+
bitsandbytes==0.43.3
|