SebastianSchramm's picture
fix link in title and add one example
5257ec0
import os
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, TextIteratorStreamer
import torch
from threading import Thread
from huggingface_hub import Repository
import json
theme = gr.themes.Monochrome(
primary_hue="indigo",
secondary_hue="blue",
neutral_hue="slate",
radius_size=gr.themes.sizes.radius_sm,
font=[gr.themes.GoogleFont("Open Sans"), "ui-sans-serif", "system-ui", "sans-serif"],
)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Load peft config for pre-trained checkpoint etc.
device = "cuda" if torch.cuda.is_available() else "cpu"
model_id = "SebastianSchramm/Cerebras-GPT-111M-instruction"
if device == "cpu":
model = AutoModelForCausalLM.from_pretrained(model_id)
else:
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
prompt_template = "Below is an instruction that describes a task, paired with an input that provides further context.\n" \
"Write a response that appropriately completes the request.\n\n" \
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
def generate(instruction, input='', temperature=1.0, max_new_tokens=256, top_p=0.9, length_penalty=1.0):
formatted_instruction = prompt_template.format(instruction=instruction, input=input)
# make sure temperature top_p and length_penalty are floats
temperature = float(temperature)
top_p = float(top_p)
length_penalty = float(length_penalty)
# STREAMING BASED ON git+https://github.com/gante/transformers.git@streamer_iterator
# streaming
streamer = TextIteratorStreamer(tokenizer)
model_inputs = tokenizer(formatted_instruction, return_tensors="pt", truncation=True, max_length=2048)
# move to gpu
model_inputs = {k: v.to(device) for k, v in model_inputs.items()}
generate_kwargs = dict(
top_p=top_p,
top_k=0,
temperature=temperature,
do_sample=True,
max_new_tokens=max_new_tokens,
early_stopping=True,
length_penalty=length_penalty,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)
t = Thread(target=model.generate, kwargs={**dict(model_inputs, streamer=streamer), **generate_kwargs})
t.start()
output = ""
hidden_output = ""
for new_text in streamer:
# skip streaming until new text is available
if len(hidden_output) <= len(formatted_instruction):
hidden_output += new_text
continue
# replace eos token
if tokenizer.eos_token in new_text:
new_text = new_text.replace(tokenizer.eos_token, "")
output += new_text
yield output
return output
examples = []
def process_example(args):
for x in generate(args):
pass
return x
with gr.Blocks(theme=theme) as demo:
with gr.Column():
gr.Markdown(
"""<h1><center>Instruction-tuned Cerebras GPT 111M Language Model for Text</center></h1>
<p>
Link to model: [Cerebras-GPT-111M-instruction](SebastianSchramm/Cerebras-GPT-111M-instruction)
</p>
"""
)
with gr.Row():
with gr.Column(scale=3):
instruction = gr.Textbox(placeholder="Instruction...", label="Instruction")
input = gr.Textbox(placeholder="Input...", label="Input")
output = gr.Textbox(
interactive=False,
lines=8,
label="Response",
placeholder="Response will be shown here...",
)
submit = gr.Button("Generate", variant="primary")
gr.Examples(
examples=examples,
inputs=[instruction, input],
cache_examples=True,
fn=process_example,
outputs=[output],
)
with gr.Column(scale=1):
temperature = gr.Slider(
label="Temperature",
value=1.0,
minimum=0.01,
maximum=1.0,
step=0.1,
interactive=True,
info="The higher more random",
)
max_new_tokens = gr.Slider(
label="Max new tokens",
value=256,
minimum=0,
maximum=2048,
step=5,
interactive=True,
info="The maximum numbers of new tokens",
)
top_p = gr.Slider(
label="Top p",
value=0.9,
minimum=0.01,
maximum=1,
step=0.05,
interactive=True,
info="probabilities that add up are kept",
)
length_penalty = gr.Slider(
label="Length penalty",
value=1.0,
minimum=-10.0,
maximum=10.0,
step=0.1,
interactive=True,
info="> 0.0 longer, < 0.0 shorter",
)
submit.click(generate, inputs=[instruction, input, temperature, max_new_tokens, top_p, length_penalty], outputs=[output])
instruction.submit(
generate, inputs=[instruction, input, temperature, max_new_tokens, top_p, length_penalty], outputs=[output]
)
demo.queue(concurrency_count=1)
demo.launch(enable_queue=True)