Spaces:
Configuration error
Configuration error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#llama 3.2 3b IT
|
2 |
+
import os
|
3 |
+
from threading import Thread
|
4 |
+
from typing import Iterator
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
#import spaces
|
8 |
+
import torch
|
9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
10 |
+
|
11 |
+
DESCRIPTION = """\
|
12 |
+
# Llama 3.2 3B Instruct
|
13 |
+
Llama 3.2 3B is Meta's latest iteration of open LLMs.
|
14 |
+
This is a demo of [`meta-llama/Llama-3.2-3B-Instruct`](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct), fine-tuned for instruction following.
|
15 |
+
For more details, please check [our post](https://huggingface.co/blog/llama32).
|
16 |
+
"""
|
17 |
+
|
18 |
+
MAX_MAX_NEW_TOKENS = 2048
|
19 |
+
DEFAULT_MAX_NEW_TOKENS = 1024
|
20 |
+
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
21 |
+
|
22 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
23 |
+
|
24 |
+
# Download model from Huggingface Hub
|
25 |
+
# Change this to meta-llama or the correct org name from Huggingface Hub
|
26 |
+
model_id = "meta-internal/Llama-3.2-3B-Instruct"
|
27 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
28 |
+
model = AutoModelForCausalLM.from_pretrained(
|
29 |
+
model_id,
|
30 |
+
device_map="auto",
|
31 |
+
torch_dtype=torch.bfloat16,
|
32 |
+
)
|
33 |
+
model.eval()
|
34 |
+
|
35 |
+
# Main Gradio inference function
|
36 |
+
def generate(
|
37 |
+
message: str,
|
38 |
+
chat_history: list[tuple[str, str]],
|
39 |
+
max_new_tokens: int = 1024,
|
40 |
+
temperature: float = 0.6,
|
41 |
+
top_p: float = 0.9,
|
42 |
+
top_k: int = 50,
|
43 |
+
repetition_penalty: float = 1.2,
|
44 |
+
) -> Iterator[str]:
|
45 |
+
|
46 |
+
conversation = [{k: v for k, v in d.items() if k != 'metadata'} for d in chat_history]
|
47 |
+
conversation.append({"role": "user", "content": message})
|
48 |
+
|
49 |
+
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
|
50 |
+
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
51 |
+
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
52 |
+
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
53 |
+
input_ids = input_ids.to(model.device)
|
54 |
+
|
55 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
|
56 |
+
generate_kwargs = dict(
|
57 |
+
{"input_ids": input_ids},
|
58 |
+
streamer=streamer,
|
59 |
+
max_new_tokens=max_new_tokens,
|
60 |
+
do_sample=True,
|
61 |
+
top_p=top_p,
|
62 |
+
top_k=top_k,
|
63 |
+
temperature=temperature,
|
64 |
+
num_beams=1,
|
65 |
+
repetition_penalty=repetition_penalty,
|
66 |
+
)
|
67 |
+
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
68 |
+
t.start()
|
69 |
+
|
70 |
+
conversation.append({"role": "assistant", "content": ""})
|
71 |
+
outputs = []
|
72 |
+
for text in streamer:
|
73 |
+
outputs.append(text)
|
74 |
+
bot_response = "".join(outputs)
|
75 |
+
conversation[-1]['content'] = bot_response
|
76 |
+
yield "", conversation
|
77 |
+
|
78 |
+
|
79 |
+
# Implementing Gradio 5 features and building a ChatInterface UI yourself
|
80 |
+
PLACEHOLDER = """<div style="padding: 20px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
81 |
+
<img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/c21ff9c8e7ecb2f7d957a72f2ef03c610ac7bbc4/Meta_lockup_positive%20primary_RGB_small.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; margin-bottom: 10px;">
|
82 |
+
<h1 style="font-size: 28px; margin: 0;">Meta llama3.2</h1>
|
83 |
+
<p style="font-size: 18px; margin: 5px 0 0; opacity: 0.65;">
|
84 |
+
<a href="https://huggingface.co/blog/llama32" target="_blank" style="color: inherit; text-decoration: none;">Learn more about Llama 3.2</a>
|
85 |
+
</p>
|
86 |
+
</div>"""
|
87 |
+
|
88 |
+
|
89 |
+
def handle_retry(history, retry_data: gr.RetryData):
|
90 |
+
new_history = history[:retry_data.index]
|
91 |
+
previous_prompt = history[retry_data.index]['content']
|
92 |
+
yield from generate(previous_prompt, chat_history = new_history, max_new_tokens = 1024, temperature = 0.6, top_p = 0.9, top_k = 50, repetition_penalty = 1.2)
|
93 |
+
|
94 |
+
def handle_like(data: gr.LikeData):
|
95 |
+
if data.liked:
|
96 |
+
print("You upvoted this response: ", data.value)
|
97 |
+
else:
|
98 |
+
print("You downvoted this response: ", data.value)
|
99 |
+
|
100 |
+
def handle_undo(history, undo_data: gr.UndoData):
|
101 |
+
chatbot = history[:undo_data.index]
|
102 |
+
prompt = history[undo_data.index]['content']
|
103 |
+
return chatbot, prompt
|
104 |
+
|
105 |
+
def chat_examples_fill(data: gr.SelectData):
|
106 |
+
yield from generate(data.value['text'], chat_history = [], max_new_tokens = 1024, temperature = 0.6, top_p = 0.9, top_k = 50, repetition_penalty = 1.2)
|
107 |
+
|
108 |
+
|
109 |
+
with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as demo:
|
110 |
+
with gr.Column(elem_id="container", scale=1):
|
111 |
+
chatbot = gr.Chatbot(
|
112 |
+
label="Llama3.2 3B Instruct Chatbotw using Gradio 5",
|
113 |
+
show_label=False,
|
114 |
+
type="messages",
|
115 |
+
scale=1,
|
116 |
+
suggestions = [
|
117 |
+
{"text": "How many R are there in a Strawberry?"},
|
118 |
+
{"text": "What is the meaning of life for an AI?"},
|
119 |
+
{"text": "Are tomatoes vegetables?"},
|
120 |
+
{"text": "There's a llama in my garden 😱 What should I do?"},
|
121 |
+
{"text": "What is the best way to open a can of worms?"},
|
122 |
+
{"text": "The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. "},
|
123 |
+
{"text": 'How to setup a human base on Mars? Give short answer.'},
|
124 |
+
{"text": 'Explain theory of relativity to me like I’m 8 years old.'},
|
125 |
+
{"text": 'What is 9,000 * 9,000?'},
|
126 |
+
{"text": 'Write a pun-filled happy birthday message to my friend Alex.'},
|
127 |
+
{"text": 'Justify why a penguin might make a good king of the jungle.'}
|
128 |
+
],
|
129 |
+
placeholder = PLACEHOLDER,
|
130 |
+
)
|
131 |
+
|
132 |
+
msg = gr.Textbox(submit_btn=True, show_label=False)
|
133 |
+
with gr.Accordion('Additional inputs', open=False):
|
134 |
+
max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=10, step=1, value=23, )
|
135 |
+
temperature = gr.Slider(label="Temperature",minimum=0.1, maximum=4.0, step=0.1, value=0.6,)
|
136 |
+
top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9, )
|
137 |
+
top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50, )
|
138 |
+
repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2, )
|
139 |
+
|
140 |
+
msg.submit(generate, [msg, chatbot, max_new_tokens, temperature, top_p, top_k, repetition_penalty], [msg, chatbot])
|
141 |
+
chatbot.retry(handle_retry, chatbot, [msg, chatbot])
|
142 |
+
chatbot.like(handle_like, None, None)
|
143 |
+
chatbot.undo(handle_undo, chatbot, [chatbot, msg])
|
144 |
+
chatbot.suggestion_select(chat_examples_fill, None, [msg, chatbot] )
|
145 |
+
|
146 |
+
|
147 |
+
demo.launch()
|