Spaces:
Runtime error
Runtime error
Init
Browse files
app.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from threading import Thread
|
2 |
+
from typing import Iterator
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import spaces
|
6 |
+
import torch
|
7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
8 |
+
|
9 |
+
MAX_MAX_NEW_TOKENS = 2048
|
10 |
+
DEFAULT_MAX_NEW_TOKENS = 1024
|
11 |
+
MAX_INPUT_TOKEN_LENGTH = 4096
|
12 |
+
|
13 |
+
DESCRIPTION = """\
|
14 |
+
# Llama-2 7B Chat
|
15 |
+
|
16 |
+
This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
|
17 |
+
|
18 |
+
🔎 For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
|
19 |
+
|
20 |
+
🔨 Looking for an even more powerful model? Check out the [13B version](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat) or the large [70B model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
|
21 |
+
"""
|
22 |
+
|
23 |
+
LICENSE = """
|
24 |
+
<p/>
|
25 |
+
|
26 |
+
---
|
27 |
+
As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta,
|
28 |
+
this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/USE_POLICY.md).
|
29 |
+
"""
|
30 |
+
|
31 |
+
if not torch.cuda.is_available():
|
32 |
+
DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
|
33 |
+
|
34 |
+
|
35 |
+
if torch.cuda.is_available():
|
36 |
+
model_id = "DAMO-NLP-SG/CLEX-7b-Chat-16K"
|
37 |
+
# from CLEX import LlamaForCausalLM
|
38 |
+
from transformers import AutoModelForCausalLM
|
39 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
|
40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
41 |
+
tokenizer.use_default_system_prompt = False
|
42 |
+
|
43 |
+
import PyPDF2
|
44 |
+
from io import BytesIO
|
45 |
+
|
46 |
+
def process_pdf(input_pdf):
|
47 |
+
# Read the binary data from the input_pdf
|
48 |
+
# pdf_data = BytesIO(input_pdf)
|
49 |
+
# if pdf_data.getvalue().strip() == b'':
|
50 |
+
# return ""
|
51 |
+
# Create a PDF reader object
|
52 |
+
reader = PyPDF2.PdfReader(input_pdf.name)
|
53 |
+
# Extract the text from each page of the PDF
|
54 |
+
text = ""
|
55 |
+
for page in reader.pages:
|
56 |
+
text += page.extract_text()
|
57 |
+
# Close the PDF reader and reset the pointer
|
58 |
+
# reader.close()
|
59 |
+
# pdf_data.seek(0)
|
60 |
+
# Return the extracted text
|
61 |
+
return text
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
+
def build_chat():
|
66 |
+
from fastchat.model import get_conversation_template
|
67 |
+
conv = get_conversation_template("vicuna")
|
68 |
+
conv.append_message(conv.roles[0], prompt)
|
69 |
+
conv.append_message(conv.roles[1], None)
|
70 |
+
prompt = conv.get_prompt()
|
71 |
+
return prompt
|
72 |
+
|
73 |
+
@spaces.GPU
|
74 |
+
def generate(
|
75 |
+
message: str,
|
76 |
+
chat_history: list[tuple[str, str]],
|
77 |
+
system_prompt: str,
|
78 |
+
max_new_tokens: int = 1024,
|
79 |
+
temperature: float = 0.6,
|
80 |
+
top_p: float = 0.9,
|
81 |
+
top_k: int = 50,
|
82 |
+
repetition_penalty: float = 1.2,
|
83 |
+
) -> Iterator[str]:
|
84 |
+
conversation = []
|
85 |
+
if system_prompt:
|
86 |
+
conversation.append({"role": "system", "content": system_prompt})
|
87 |
+
for user, assistant in chat_history:
|
88 |
+
conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
|
89 |
+
conversation.append({"role": "user", "content": message})
|
90 |
+
|
91 |
+
chat = tokenizer.apply_chat_template(conversation, tokenize=False)
|
92 |
+
inputs = tokenizer(chat, return_tensors="pt", add_special_tokens=False).to("cuda")
|
93 |
+
if len(inputs) > MAX_INPUT_TOKEN_LENGTH:
|
94 |
+
inputs = inputs[-MAX_INPUT_TOKEN_LENGTH:]
|
95 |
+
gr.Warning("Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
96 |
+
|
97 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
98 |
+
generate_kwargs = dict(
|
99 |
+
inputs,
|
100 |
+
streamer=streamer,
|
101 |
+
max_new_tokens=max_new_tokens,
|
102 |
+
do_sample=True,
|
103 |
+
top_p=top_p,
|
104 |
+
top_k=top_k,
|
105 |
+
temperature=temperature,
|
106 |
+
num_beams=1,
|
107 |
+
repetition_penalty=repetition_penalty,
|
108 |
+
)
|
109 |
+
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
110 |
+
t.start()
|
111 |
+
|
112 |
+
outputs = []
|
113 |
+
for text in streamer:
|
114 |
+
outputs.append(text)
|
115 |
+
yield "".join(outputs)
|
116 |
+
|
117 |
+
|
118 |
+
def generate_with_pdf(
|
119 |
+
message: str,
|
120 |
+
chat_history: list[tuple[str, str]],
|
121 |
+
system_prompt: str,
|
122 |
+
input_pdf: BytesIO = None,
|
123 |
+
max_new_tokens: int = 1024,
|
124 |
+
temperature: float = 0.6,
|
125 |
+
top_p: float = 0.9,
|
126 |
+
top_k: int = 50,
|
127 |
+
repetition_penalty: float = 1.2,
|
128 |
+
) -> Iterator[str]:
|
129 |
+
if input_pdf is not None:
|
130 |
+
pdf_text = process_pdf(input_pdf)
|
131 |
+
# print(pdf_text)
|
132 |
+
message += f"\nThis is the beginning of a pdf\n{pdf_text}This is the end of a pdf\n"
|
133 |
+
yield from generate(
|
134 |
+
message,
|
135 |
+
chat_history,
|
136 |
+
system_prompt,
|
137 |
+
max_new_tokens,
|
138 |
+
temperature,
|
139 |
+
top_p,
|
140 |
+
top_k,
|
141 |
+
repetition_penalty
|
142 |
+
)
|
143 |
+
|
144 |
+
chat_interface = gr.ChatInterface(
|
145 |
+
fn=generate_with_pdf,
|
146 |
+
additional_inputs=[
|
147 |
+
gr.Textbox(label="System prompt", lines=6),
|
148 |
+
gr.File(label="PDF File", accept=".pdf"),
|
149 |
+
gr.Slider(
|
150 |
+
label="Max new tokens",
|
151 |
+
minimum=1,
|
152 |
+
maximum=MAX_MAX_NEW_TOKENS,
|
153 |
+
step=1,
|
154 |
+
value=DEFAULT_MAX_NEW_TOKENS,
|
155 |
+
),
|
156 |
+
gr.Slider(
|
157 |
+
label="Temperature",
|
158 |
+
minimum=0.1,
|
159 |
+
maximum=4.0,
|
160 |
+
step=0.1,
|
161 |
+
value=0.6,
|
162 |
+
),
|
163 |
+
gr.Slider(
|
164 |
+
label="Top-p (nucleus sampling)",
|
165 |
+
minimum=0.05,
|
166 |
+
maximum=1.0,
|
167 |
+
step=0.05,
|
168 |
+
value=0.9,
|
169 |
+
),
|
170 |
+
gr.Slider(
|
171 |
+
label="Top-k",
|
172 |
+
minimum=1,
|
173 |
+
maximum=1000,
|
174 |
+
step=1,
|
175 |
+
value=50,
|
176 |
+
),
|
177 |
+
gr.Slider(
|
178 |
+
label="Repetition penalty",
|
179 |
+
minimum=1.0,
|
180 |
+
maximum=2.0,
|
181 |
+
step=0.05,
|
182 |
+
value=1.2,
|
183 |
+
),
|
184 |
+
],
|
185 |
+
stop_btn=None,
|
186 |
+
examples=[
|
187 |
+
["Hello there! How are you doing?"],
|
188 |
+
["Can you explain briefly to me what is the Python programming language?"],
|
189 |
+
["Explain the plot of Cinderella in a sentence."],
|
190 |
+
["How many hours does it take a man to eat a Helicopter?"],
|
191 |
+
["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
|
192 |
+
],
|
193 |
+
)
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
with gr.Blocks(css="style.css") as demo:
|
198 |
+
gr.Markdown(DESCRIPTION)
|
199 |
+
gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
|
200 |
+
|
201 |
+
chat_interface.render()
|
202 |
+
gr.Markdown(LICENSE)
|
203 |
+
|
204 |
+
if __name__ == "__main__":
|
205 |
+
demo.queue(max_size=20).launch(share=False)
|
style.css
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
h1 {
|
2 |
+
text-align: center;
|
3 |
+
}
|
4 |
+
|
5 |
+
#duplicate-button {
|
6 |
+
margin: auto;
|
7 |
+
color: white;
|
8 |
+
background: #1565c0;
|
9 |
+
border-radius: 100vh;
|
10 |
+
}
|
11 |
+
|
12 |
+
.contain {
|
13 |
+
max-width: 900px;
|
14 |
+
margin: auto;
|
15 |
+
padding-top: 1.5rem;
|
16 |
+
}
|