Spaces:
Runtime error
Runtime error
File size: 9,266 Bytes
fdfc45e |
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 |
from strings import TITLE, ABSTRACT, BOTTOM_LINE
from strings import DEFAULT_EXAMPLES
from strings import SPECIAL_STRS
from styles import PARENT_BLOCK_CSS
from constants import num_of_characters_to_keep
import time
import gradio as gr
from model import load_model
from gen import get_output_batch, StreamModel
from utils import generate_prompt, post_processes_batch, post_process_stream, get_generation_config, common_post_process
generation_config = get_generation_config(
"./generation_config_default.yaml"
)
model, tokenizer = load_model(
base="decapoda-research/llama-13b-hf",
finetuned="chansung/alpaca-lora-13b"
)
stream_model = StreamModel(model, tokenizer)
def chat_stream(
context,
instruction,
state_chatbot,
):
if len(context) > 1000 or len(instruction) > 300:
raise gr.Error("context or prompt is too long!")
bot_summarized_response = ''
# user input should be appropriately formatted (don't be confused by the function name)
instruction_display = common_post_process(instruction)
instruction_prompt, conv_length = generate_prompt(instruction, state_chatbot, context)
if conv_length > num_of_characters_to_keep:
instruction_prompt = generate_prompt(SPECIAL_STRS["summarize"], state_chatbot, context, partial=True)[0]
state_chatbot = state_chatbot + [
(
None,
"![](https://s2.gifyu.com/images/icons8-loading-circle.gif) too long conversations, so let's summarize..."
)
]
yield (state_chatbot, state_chatbot, context)
bot_summarized_response = get_output_batch(
model, tokenizer, [instruction_prompt], generation_config
)[0]
bot_summarized_response = bot_summarized_response.split("### Response:")[-1].strip()
state_chatbot[-1] = (
None,
"✅ summarization is done and set as context"
)
print(f"bot_summarized_response: {bot_summarized_response}")
yield (state_chatbot, state_chatbot, f"{context}. {bot_summarized_response}".strip())
instruction_prompt = generate_prompt(instruction, state_chatbot, f"{context} {bot_summarized_response}")[0]
bot_response = stream_model(
instruction_prompt,
max_tokens=256,
temperature=1,
top_p=0.9
)
instruction_display = None if instruction_display == SPECIAL_STRS["continue"] else instruction_display
state_chatbot = state_chatbot + [(instruction_display, None)]
yield (state_chatbot, state_chatbot, f"{context}. {bot_summarized_response}".strip())
prev_index = 0
agg_tokens = ""
cutoff_idx = 0
for tokens in bot_response:
tokens = tokens.strip()
cur_token = tokens[prev_index:]
if "#" in cur_token and agg_tokens == "":
cutoff_idx = tokens.find("#")
agg_tokens = tokens[cutoff_idx:]
if agg_tokens != "":
if len(agg_tokens) < len("### Instruction:") :
agg_tokens = agg_tokens + cur_token
elif len(agg_tokens) >= len("### Instruction:"):
if tokens.find("### Instruction:") > -1:
processed_response, _ = post_process_stream(tokens[:tokens.find("### Instruction:")].strip())
state_chatbot[-1] = (
instruction_display,
processed_response
)
yield (state_chatbot, state_chatbot, f"{context} {bot_summarized_response}".strip())
break
else:
agg_tokens = ""
cutoff_idx = 0
if agg_tokens == "":
processed_response, to_exit = post_process_stream(tokens)
state_chatbot[-1] = (instruction_display, processed_response)
yield (state_chatbot, state_chatbot, f"{context} {bot_summarized_response}".strip())
if to_exit:
break
prev_index = len(tokens)
yield (
state_chatbot,
state_chatbot,
f"{context} {bot_summarized_response}".strip()
)
def chat_batch(
contexts,
instructions,
state_chatbots,
):
state_results = []
ctx_results = []
instruct_prompts = [
generate_prompt(instruct, histories, ctx)
for ctx, instruct, histories in zip(contexts, instructions, state_chatbots)
]
bot_responses = get_output_batch(
model, tokenizer, instruct_prompts, generation_config
)
bot_responses = post_processes_batch(bot_responses)
for ctx, instruction, bot_response, state_chatbot in zip(contexts, instructions, bot_responses, state_chatbots):
new_state_chatbot = state_chatbot + [('' if instruction == SPECIAL_STRS["continue"] else instruction, bot_response)]
ctx_results.append(gr.Textbox.update(value=bot_response) if instruction == SPECIAL_STRS["summarize"] else ctx)
state_results.append(new_state_chatbot)
return (state_results, state_results, ctx_results)
def reset_textbox():
return gr.Textbox.update(value='')
def reset_everything(
context_txtbox,
instruction_txtbox,
state_chatbot):
state_chatbot = []
return (
state_chatbot,
state_chatbot,
gr.Textbox.update(value=''),
gr.Textbox.update(value=''),
)
with gr.Blocks(css=PARENT_BLOCK_CSS) as demo:
state_chatbot = gr.State([])
with gr.Column(elem_id='col_container'):
gr.Markdown(f"## {TITLE}\n\n\n{ABSTRACT}")
with gr.Accordion("Context Setting", open=False):
context_txtbox = gr.Textbox(placeholder="Surrounding information to AI", label="Enter Context")
hidden_txtbox = gr.Textbox(placeholder="", label="Order", visible=False)
chatbot = gr.Chatbot(elem_id='chatbot', label="Alpaca-LoRA")
instruction_txtbox = gr.Textbox(placeholder="What do you want to say to AI?", label="Instruction")
with gr.Row():
cancel_btn = gr.Button(value="Cancel")
reset_btn = gr.Button(value="Reset")
with gr.Accordion("Helper Buttons", open=False):
gr.Markdown(f"`Continue` lets AI to complete the previous incomplete answers. `Summarize` lets AI to summarize the conversations so far.")
continue_txtbox = gr.Textbox(value=SPECIAL_STRS["continue"], visible=False)
summrize_txtbox = gr.Textbox(value=SPECIAL_STRS["summarize"], visible=False)
continue_btn = gr.Button(value="Continue")
summarize_btn = gr.Button(value="Summarize")
gr.Markdown("#### Examples")
for _, (category, examples) in enumerate(DEFAULT_EXAMPLES.items()):
with gr.Accordion(category, open=False):
if category == "Identity":
for item in examples:
with gr.Accordion(item["title"], open=False):
gr.Examples(
examples=item["examples"],
inputs=[
hidden_txtbox, context_txtbox, instruction_txtbox
],
label=None
)
else:
for item in examples:
with gr.Accordion(item["title"], open=False):
gr.Examples(
examples=item["examples"],
inputs=[
hidden_txtbox, instruction_txtbox
],
label=None
)
gr.Markdown(f"{BOTTOM_LINE}")
send_event = instruction_txtbox.submit(
chat_stream,
[context_txtbox, instruction_txtbox, state_chatbot],
[state_chatbot, chatbot, context_txtbox],
)
reset_event = instruction_txtbox.submit(
reset_textbox,
[],
[instruction_txtbox],
)
continue_event = continue_btn.click(
chat_stream,
[context_txtbox, continue_txtbox, state_chatbot],
[state_chatbot, chatbot, context_txtbox],
)
reset_continue_event = continue_btn.click(
reset_textbox,
[],
[instruction_txtbox],
)
summarize_event = summarize_btn.click(
chat_stream,
[context_txtbox, summrize_txtbox, state_chatbot],
[state_chatbot, chatbot, context_txtbox],
)
summarize_reset_event = summarize_btn.click(
reset_textbox,
[],
[instruction_txtbox],
)
cancel_btn.click(
None, None, None,
cancels=[
send_event, continue_event, summarize_event
]
)
reset_btn.click(
reset_everything,
[context_txtbox, instruction_txtbox, state_chatbot],
[state_chatbot, chatbot, context_txtbox, instruction_txtbox],
cancels=[
send_event, continue_event, summarize_event
]
)
demo.queue(
concurrency_count=1,
max_size=100,
).launch(
max_threads=5,
server_name="0.0.0.0",
) |