maxisz254 commited on
Commit
402afe5
1 Parent(s): 706c33a

new app.py

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