Xieyiyiyi commited on
Commit
0fe477d
1 Parent(s): c58fe8b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +290 -0
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RWKV RNN Model - Gradio Space for HuggingFace
3
+ YT - Mean Gene Hacks - https://www.youtube.com/@MeanGeneHacks
4
+ (C) Gene Ruebsamen - 2/7/2023
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU General Public License for more details.
13
+ You should have received a copy of the GNU General Public License
14
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
15
+ """
16
+
17
+ import gradio as gr
18
+ import codecs
19
+ from ast import literal_eval
20
+ from datetime import datetime
21
+ from rwkvstic.load import RWKV
22
+ from config import config, title
23
+ import torch
24
+ import gc
25
+
26
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+ desc = '''<p>RNN with Transformer-level LLM Performance (<a href='https://github.com/BlinkDL/RWKV-LM'>github</a>).
29
+ According to the author: "It combines the best of RNN and transformers - great performance, fast inference, saves VRAM, fast training, "infinite" ctx_len, and free sentence embedding."'''
30
+
31
+ thanks = '''<p>Thanks to <a href='https://github.com/gururise/rwkv_gradio'>Gururise</a> for this template</p>'''
32
+
33
+
34
+ def to_md(text):
35
+ return text.replace("\n", "<br />")
36
+
37
+
38
+ def get_model():
39
+ model = None
40
+ model = RWKV(
41
+ **config
42
+ )
43
+ return model
44
+
45
+
46
+ model = get_model()
47
+
48
+
49
+
50
+ def infer(
51
+ prompt,
52
+ mode="generative",
53
+ max_new_tokens=10,
54
+ temperature=0.1,
55
+ top_p=1.0,
56
+ stop="<|endoftext|>",
57
+ end_adj=0.0,
58
+ seed=42,
59
+ ):
60
+ global model
61
+
62
+ if model == None:
63
+ gc.collect()
64
+ if (DEVICE == "cuda"):
65
+ torch.cuda.empty_cache()
66
+ model = get_model()
67
+
68
+ max_new_tokens = int(max_new_tokens)
69
+ temperature = float(temperature)
70
+ end_adj = float(end_adj)
71
+ top_p = float(top_p)
72
+ stop = [x.strip(' ') for x in stop.split(',')]
73
+ seed = seed
74
+
75
+ assert 1 <= max_new_tokens <= 512
76
+ assert 0.0 <= temperature <= 5.0
77
+ assert 0.0 <= top_p <= 1.0
78
+
79
+ temperature = max(0.05, temperature)
80
+ if prompt == "":
81
+ prompt = " "
82
+
83
+ # Clear model state for generative mode
84
+ model.resetState()
85
+ if (mode == "Q/A"):
86
+ prompt = f"\nQ: {prompt}\n\nA:"
87
+ if (mode == "ELDR"):
88
+ prompt = f"\n{prompt}\n\nExpert Long Detailed Response:\n\nHi, thanks for reaching out, we would be happy to answer your question"
89
+ if (mode == "Expert"):
90
+ prompt = f"\n{prompt}\n\nExpert Full Response:\n\nHi, thanks for reaching out, we would be happy to answer your question.\n"
91
+ if (mode == "EFA"):
92
+ prompt = f'\nAsk Expert\n\nQuestion:\n{prompt}\n\nExpert Full Answer:\n'
93
+ if (mode == "BFR"):
94
+ prompt = f"Task given:\n\n{prompt}\n\nBest Full Response:"
95
+
96
+ print(f"PROMPT ({datetime.now()}):\n-------\n{prompt}")
97
+ print(f"OUTPUT ({datetime.now()}):\n-------\n")
98
+ # Load prompt
99
+ model.loadContext(newctx=prompt)
100
+ generated_text = ""
101
+ done = False
102
+ with torch.no_grad():
103
+ for _ in range(max_new_tokens):
104
+ char = model.forward(stopStrings=stop, temp=temperature, top_p_usual=top_p, end_adj=end_adj)[
105
+ "output"]
106
+ print(char, end='', flush=True)
107
+ generated_text += char
108
+ generated_text = generated_text.lstrip("\n ")
109
+
110
+ for stop_word in stop:
111
+ stop_word = codecs.getdecoder("unicode_escape")(stop_word)[0]
112
+ if stop_word != '' and stop_word in generated_text:
113
+ done = True
114
+ break
115
+ yield generated_text
116
+ if done:
117
+ print("<stopped>\n")
118
+ break
119
+
120
+ # print(f"{generated_text}")
121
+
122
+ for stop_word in stop:
123
+ stop_word = codecs.getdecoder("unicode_escape")(stop_word)[0]
124
+ if stop_word != '' and stop_word in generated_text:
125
+ generated_text = generated_text[:generated_text.find(stop_word)]
126
+
127
+ gc.collect()
128
+ yield generated_text
129
+ username = "USER"
130
+ intro = f'''The following is a verbose and detailed conversation between an AI assistant called FRITZ, and a human user called USER. FRITZ is intelligent, knowledgeable, wise and polite.
131
+ {username}: What year was the french revolution?
132
+ FRITZ: The French Revolution started in 1789, and lasted 10 years until 1799.
133
+ {username}: 3+5=?
134
+ FRITZ: The answer is 8.
135
+ {username}: What year did the Berlin Wall fall?
136
+ FRITZ: The Berlin wall stood for 28 years and fell in 1989.
137
+ {username}: solve for a: 9-a=2
138
+ FRITZ: The answer is a=7, because 9-7 = 2.
139
+ {username}: wat is lhc
140
+ FRITZ: The Large Hadron Collider (LHC) is a high-energy particle collider, built by CERN, and completed in 2008. It was used to confirm the existence of the Higgs boson in 2012.
141
+ {username}: Tell me about yourself.
142
+ FRITZ: My name is Fritz. I am an RNN based Large Language Model (LLM).
143
+ '''
144
+
145
+ model.loadContext(newctx=intro)
146
+ chatState = model.getState()
147
+ model.resetState()
148
+ def chat(
149
+ prompt,
150
+ history,
151
+ max_new_tokens=10,
152
+ temperature=0.1,
153
+ top_p=1.0,
154
+ seed=42,
155
+ ):
156
+ global model
157
+ global username
158
+ history = history or []
159
+
160
+ intro = ""
161
+
162
+ if model == None:
163
+ gc.collect()
164
+ if (DEVICE == "cuda"):
165
+ torch.cuda.empty_cache()
166
+ model = get_model()
167
+
168
+ username = username.strip()
169
+ username = username or "USER"
170
+
171
+
172
+
173
+ if len(history) == 0:
174
+ # no history, so lets reset chat state
175
+ model.setState(chatState)
176
+ history = [[], model.emptyState]
177
+ print("reset chat state")
178
+ else:
179
+ if (history[0][0][0].split(':')[0] != username):
180
+ model.setState(chatState)
181
+ history = [[], model.chatState]
182
+ print("username changed, reset state")
183
+ else:
184
+ model.setState(history[1])
185
+ intro = ""
186
+
187
+ max_new_tokens = int(max_new_tokens)
188
+ temperature = float(temperature)
189
+ top_p = float(top_p)
190
+ seed = seed
191
+
192
+ assert 1 <= max_new_tokens <= 512
193
+ assert 0.0 <= temperature <= 3.0
194
+ assert 0.0 <= top_p <= 1.0
195
+
196
+ temperature = max(0.05, temperature)
197
+
198
+ prompt = f"{username}: " + prompt + "\n"
199
+ print(f"CHAT ({datetime.now()}):\n-------\n{prompt}")
200
+ print(f"OUTPUT ({datetime.now()}):\n-------\n")
201
+ # Load prompt
202
+
203
+ model.loadContext(newctx=prompt)
204
+
205
+ out = model.forward(number=max_new_tokens, stopStrings=[
206
+ "<|endoftext|>", username+":"], temp=temperature, top_p_usual=top_p)
207
+
208
+ generated_text = out["output"].lstrip("\n ")
209
+ generated_text = generated_text.rstrip(username+":")
210
+ print(f"{generated_text}")
211
+
212
+ gc.collect()
213
+ history[0].append((prompt, generated_text))
214
+ return history[0], [history[0], out["state"]]
215
+
216
+
217
+ examples = [
218
+ [
219
+ # Question Answering
220
+ '''What is the capital of Germany?''', "Q/A", 25, 0.2, 1.0, "<|endoftext|>"],
221
+ [
222
+ # Question Answering
223
+ '''Are humans good or bad?''', "Q/A", 150, 0.8, 0.8, "<|endoftext|>"],
224
+ [
225
+ # Question Answering
226
+ '''What is the purpose of Vitamin A?''', "Q/A", 50, 0.2, 0.8, "<|endoftext|>"],
227
+ [
228
+ # Chatbot
229
+ '''This is a conversation between two AI large language models named Alex and Fritz. They are exploring each other's capabilities, and trying to ask interesting questions of one another to explore the limits of each others AI.
230
+ Conversation:
231
+ Alex: Good morning, Fritz, what type of LLM are you based upon?
232
+ Fritz: Morning Alex, I am an RNN with transformer level performance. My language model is 100% attention free.
233
+ Alex:''', "generative", 220, 0.9, 0.9, "\\n\\n,<|endoftext|>"],
234
+ [
235
+ # Generate List
236
+ '''Task given:
237
+ Please Write a Short story about a cat learning python
238
+ Best Full Response:
239
+ ''', "generative", 140, 0.85, 0.8, "<|endoftext|>"],
240
+ [
241
+ # Natural Language Interface
242
+ '''Here is a short story (in the style of Tolkien) in which Aiden attacks a robot with a sword:
243
+ ''', "generative", 140, 0.85, 0.8, "<|endoftext|>"]
244
+ ]
245
+
246
+
247
+ iface = gr.Interface(
248
+ fn=infer,
249
+ description=f'''<h3>Generative and Question/Answer</h3>{desc}{thanks}''',
250
+ allow_flagging="never",
251
+ inputs=[
252
+ gr.Textbox(lines=20, label="Prompt"), # prompt
253
+ gr.Radio(["Freeform", "Q/A","ELDR","Expert","EFR","BFR"],
254
+ value="Expert", label="Choose Mode"),
255
+ gr.Slider(1, 512, value=40), # max_tokens
256
+ gr.Slider(0.0, 5.0, value=0.9), # temperature
257
+ gr.Slider(0.0, 1.0, value=0.85), # top_p
258
+ gr.Textbox(lines=1, value="<|endoftext|>"), # stop
259
+ gr.Slider(-999, 0.0, value=0.0), # end_adj
260
+
261
+ ],
262
+ outputs=gr.Textbox(label="Generated Output", lines=25),
263
+ examples=examples,
264
+ cache_examples=False,
265
+ ).queue()
266
+
267
+ chatiface = gr.Interface(
268
+ fn=chat,
269
+ description=f'''<h3>Chatbot</h3><h4>Refresh page or change name to reset memory context</h4>{desc}{thanks}''',
270
+ allow_flagging="never",
271
+ inputs=[
272
+ gr.Textbox(lines=5, label="Message"), # prompt
273
+ "state",
274
+ gr.Slider(1, 256, value=60), # max_tokens
275
+ gr.Slider(0.0, 1.0, value=0.8), # temperature
276
+ gr.Slider(0.0, 1.0, value=0.85) # top_p
277
+ ],
278
+ outputs=[gr.Chatbot(label="Chat Log", color_map=(
279
+ "green", "pink")), "state"],
280
+ ).queue()
281
+
282
+ demo = gr.TabbedInterface(
283
+
284
+ [iface, chatiface], ["Q/A", "Chatbot"],
285
+ title=title,
286
+
287
+ )
288
+
289
+ demo.queue()
290
+ demo.launch(share=False)