Spaces:
Runtime error
Runtime error
File size: 10,897 Bytes
76d3fa1 1880ac6 76d3fa1 3ce130a 1880ac6 76d3fa1 1880ac6 76d3fa1 1880ac6 76d3fa1 33a0edf 1880ac6 33a0edf 1880ac6 33a0edf 1880ac6 33a0edf 76d3fa1 3ce130a f325d08 33a0edf f325d08 33a0edf 76d3fa1 f325d08 76d3fa1 1880ac6 76d3fa1 2600030 76d3fa1 1880ac6 76d3fa1 1880ac6 76d3fa1 1880ac6 76d3fa1 6774d89 33a0edf 76d3fa1 f325d08 76d3fa1 2600030 76d3fa1 f325d08 33a0edf 1880ac6 76d3fa1 2600030 76d3fa1 2600030 76d3fa1 2600030 76d3fa1 47a5c6c 76d3fa1 33a0edf 76d3fa1 3ce130a 6774d89 1880ac6 f325d08 6774d89 f325d08 3ce130a 1880ac6 3ce130a 1880ac6 6774d89 1880ac6 6774d89 76d3fa1 1880ac6 6774d89 f325d08 33a0edf 1880ac6 33a0edf f325d08 33a0edf f325d08 33a0edf 1880ac6 33a0edf 1880ac6 33a0edf 1880ac6 33a0edf 1880ac6 33a0edf 76d3fa1 f325d08 33a0edf 1880ac6 76d3fa1 3ce130a 1880ac6 3ce130a 76d3fa1 33a0edf f325d08 76d3fa1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
import os
from dataclasses import dataclass
from uuid import uuid4
import gradio as gr
import torch
import transformers
from peft import PeftConfig, PeftModel
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
)
from utils import Agent, format_sotopia_prompt, get_starter_prompt
DEPLOYED = os.getenv("DEPLOYED", "true").lower() == "true"
def prepare_sotopia_info():
human_agent = Agent(
name="Ethan Johnson",
background="Ethan Johnson is a 34-year-old male chef. He/him pronouns. Ethan Johnson is famous for cooking Italian food.",
goal="Uknown",
secrets="Uknown",
personality="Ethan Johnson, a creative yet somewhat reserved individual, values power and fairness. He likes to analyse situations before deciding.",
)
machine_agent = Agent(
name="Benjamin Jackson",
background="Benjamin Jackson is a 24-year-old male environmental activist. He/him pronouns. Benjamin Jackson is well-known for his impassioned speeches.",
goal="Figure out why they estranged you recently, and maintain the existing friendship (Extra information: you notice that your friend has been intentionally avoiding you, you would like to figure out why. You value your friendship with the friend and don't want to lose it.)",
secrets="Descendant of a wealthy oil tycoon, rejects family fortune",
personality="Benjamin Jackson, expressive and imaginative, leans towards self-direction and liberty. His decisions aim for societal betterment.",
)
scenario = (
"Conversation between two friends, where one is upset and crying"
)
instructions = get_starter_prompt(machine_agent, human_agent, scenario)
return human_agent, machine_agent, scenario, instructions
def prepare(model_name):
compute_type = torch.float16
config_dict = PeftConfig.from_json_file("peft_config.json")
config = PeftConfig.from_peft_type(**config_dict)
if 'mistral'in model_name:
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1").to("cuda")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")
model = PeftModel.from_pretrained(model, model_name, config=config).to(compute_type).to("cuda")
else:
tokenizer = AutoTokenizer.from_pretrained(model_name)
return model, tokenizer
def introduction():
with gr.Column(scale=2):
gr.Image(
"images/sotopia.jpg", elem_id="banner-image", show_label=False
)
with gr.Column(scale=5):
gr.Markdown(
"""# Sotopia-Pi Demo
**Chat with [Sotopia-Pi](https://github.com/sotopia-lab/sotopia-pi), brainstorm ideas, discuss your holiday plans, and more!**
➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [sotopia-pi-mistral-7b-BC_SR](https://huggingface.co/cmu-lti/sotopia-pi-mistral-7b-BC_SR)/
⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words.
🗄️ **Disclaimer**: User prompts and generated replies from the model may be collected by TII solely for the purpose of enhancing and refining our models. TII will not store any personally identifiable information associated with your inputs. By using this demo, users implicitly agree to these terms.
"""
)
def param_accordion(according_visible=True):
with gr.Accordion("Parameters", open=False, visible=according_visible):
model_name = gr.Dropdown(
choices=["cmu-lti/sotopia-pi-mistral-7b-BC_SR", "mistralai/Mistral-7B-Instruct-v0.1", "GPT3.5"], # Example model choices
value="cmu-lti/sotopia-pi-mistral-7b-BC_SR", # Default value
interactive=True,
label="Model Selection",
)
temperature = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.7,
step=0.1,
interactive=True,
label="Temperature",
)
max_tokens = gr.Slider(
minimum=1024,
maximum=4096,
value=1024,
step=1,
interactive=True,
label="Max Tokens",
)
session_id = gr.Textbox(
value=uuid4,
interactive=False,
visible=False,
label="Session ID",
)
return temperature, session_id, max_tokens, model_name
def sotopia_info_accordion(
human_agent, machine_agent, scenario, according_visible=True
):
with gr.Accordion(
"Sotopia Information", open=False, visible=according_visible
):
with gr.Row():
with gr.Column():
user_name = gr.Textbox(
lines=1,
label="username",
value=human_agent.name,
interactive=True,
placeholder=f"{human_agent.name}: ",
show_label=False,
max_lines=1,
)
with gr.Column():
bot_name = gr.Textbox(
lines=1,
value=machine_agent.name,
interactive=True,
placeholder=f"{machine_agent.name}: ",
show_label=False,
max_lines=1,
visible=False,
)
with gr.Column():
scenario = gr.Textbox(
lines=4,
value=scenario,
interactive=False,
placeholder="Scenario",
show_label=False,
max_lines=4,
visible=False,
)
return user_name, bot_name, scenario
def instructions_accordion(instructions, according_visible=False):
with gr.Accordion("Instructions", open=False, visible=according_visible):
instructions = gr.Textbox(
lines=10,
value=instructions,
interactive=False,
placeholder="Instructions",
show_label=False,
max_lines=10,
visible=False,
)
return instructions
# history are input output pairs
def run_chat(
message: str,
history,
instructions: str,
user_name: str,
bot_name: str,
temperature: float,
top_p: float,
max_tokens: int,
model_selection:str
):
model, tokenizer = prepare(model_selection)
prompt = format_sotopia_prompt(
message, history, instructions, user_name, bot_name
)
input_tokens = tokenizer(
prompt, return_tensors="pt", padding="do_not_pad"
).input_ids.to("cuda")
input_length = input_tokens.shape[-1]
output_tokens = model.generate(
input_tokens,
temperature=temperature,
top_p=top_p,
max_length=max_tokens,
pad_token_id=tokenizer.eos_token_id,
num_return_sequences=1,
)
output_tokens = output_tokens[:, input_length:]
text_output = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
return text_output
def chat_tab():
#model, tokenizer = prepare()
human_agent, machine_agent, scenario, instructions = prepare_sotopia_info()
# history are input output pairs
def run_chat(
message: str,
history,
instructions: str,
user_name: str,
bot_name: str,
temperature: float,
top_p: float,
max_tokens: int,
model_selection:str
):
model, tokenizer = prepare(model_selection)
prompt = format_sotopia_prompt(
message, history, instructions, user_name, bot_name
)
input_tokens = tokenizer(
prompt, return_tensors="pt", padding="do_not_pad"
).input_ids.to("cuda")
input_length = input_tokens.shape[-1]
output_tokens = model.generate(
input_tokens,
temperature=temperature,
top_p=top_p,
max_length=max_tokens,
pad_token_id=tokenizer.eos_token_id,
num_return_sequences=1,
)
output_tokens = output_tokens[:, input_length:]
text_output = tokenizer.decode(
output_tokens[0], skip_special_tokens=True
)
return text_output
with gr.Column():
with gr.Row():
temperature, session_id, max_tokens, model = param_accordion()
user_name, bot_name, scenario = sotopia_info_accordion(human_agent, machine_agent, scenario)
instructions = instructions_accordion(instructions)
with gr.Column():
with gr.Blocks():
gr.ChatInterface(
fn=run_chat,
chatbot=gr.Chatbot(
height=620,
render=False,
show_label=False,
rtl=False,
avatar_images=(
"images/profile1.jpg",
"images/profile2.jpg",
),
),
textbox=gr.Textbox(
placeholder="Write your message here...",
render=False,
scale=7,
rtl=False,
),
additional_inputs=[
instructions,
user_name,
bot_name,
temperature,
session_id,
max_tokens,
model,
],
submit_btn="Send",
stop_btn="Stop",
retry_btn="🔄 Retry",
undo_btn="↩️ Delete",
clear_btn="🗑️ Clear",
)
def main():
with gr.Blocks(
css="""#chat_container {height: 820px; width: 1000px; margin-left: auto; margin-right: auto;}
#chatbot {height: 600px; overflow: auto;}
#create_container {height: 750px; margin-left: 0px; margin-right: 0px;}
#tokenizer_renderer span {white-space: pre-wrap}
"""
) as demo:
with gr.Row():
introduction()
with gr.Row():
chat_tab()
return demo
def start_demo():
demo = main()
if DEPLOYED:
demo.queue(api_open=False).launch(show_api=False)
else:
demo.queue()
demo.launch(share=False, server_name="0.0.0.0")
if __name__ == "__main__":
start_demo()
|