Hazzzardous commited on
Commit
ac182ec
0 Parent(s):

Duplicate from Hazzzardous/RWKV-Instruct

Browse files
Files changed (5) hide show
  1. .gitattributes +34 -0
  2. README.md +17 -0
  3. app.py +285 -0
  4. config.py +63 -0
  5. requirements.txt +5 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RWKV Instruct
3
+ emoji: 💩
4
+ colorFrom: yellow
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 3.17.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: gpl-3.0
11
+ duplicated_from: Hazzzardous/RWKV-Instruct
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
15
+ Based on:
16
+
17
+ https://huggingface.co/spaces/yahma/rwkv
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://github.com/gururise/rwkv_gradio'>Gururise</a> for this template</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
+ end_adj = float(end_adj)
73
+ top_p = float(top_p)
74
+ stop = [x.strip(' ') for x in stop.split(',')]
75
+ seed = seed
76
+
77
+ assert 1 <= max_new_tokens <= 384
78
+ assert 0.0 <= temperature <= 1.0
79
+ assert 0.0 <= top_p <= 1.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
+ seed=42,
133
+ ):
134
+ global model
135
+ history = history or []
136
+
137
+ intro = ""
138
+
139
+ if model == None:
140
+ gc.collect()
141
+ if (DEVICE == "cuda"):
142
+ torch.cuda.empty_cache()
143
+ model = get_model()
144
+
145
+ username = username.strip()
146
+ username = username or "USER"
147
+
148
+ 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.
149
+
150
+ {username}: What year was the french revolution?
151
+ FRITZ: The French Revolution started in 1789, and lasted 10 years until 1799.
152
+ {username}: 3+5=?
153
+ FRITZ: The answer is 8.
154
+ {username}: What year did the Berlin Wall fall?
155
+ FRITZ: The Berlin wall stood for 28 years and fell in 1989.
156
+ {username}: solve for a: 9-a=2
157
+ FRITZ: The answer is a=7, because 9-7 = 2.
158
+ {username}: wat is lhc
159
+ 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.
160
+ {username}: Tell me about yourself.
161
+ FRITZ: My name is Fritz. I am an RNN based Large Language Model (LLM).
162
+ '''
163
+
164
+ if len(history) == 0:
165
+ # no history, so lets reset chat state
166
+ model.resetState()
167
+ history = [[], model.emptyState]
168
+ print("reset chat state")
169
+ else:
170
+ if (history[0][0][0].split(':')[0] != username):
171
+ model.resetState()
172
+ history = [[], model.emptyState]
173
+ print("username changed, reset state")
174
+ else:
175
+ model.setState(history[1])
176
+ intro = ""
177
+
178
+ max_new_tokens = int(max_new_tokens)
179
+ temperature = float(temperature)
180
+ top_p = float(top_p)
181
+ seed = seed
182
+
183
+ assert 1 <= max_new_tokens <= 384
184
+ assert 0.0 <= temperature <= 1.0
185
+ assert 0.0 <= top_p <= 1.0
186
+
187
+ temperature = max(0.05, temperature)
188
+
189
+ prompt = f"{username}: " + prompt + "\n"
190
+ print(f"CHAT ({datetime.now()}):\n-------\n{prompt}")
191
+ print(f"OUTPUT ({datetime.now()}):\n-------\n")
192
+ # Load prompt
193
+
194
+ model.loadContext(newctx=intro+prompt)
195
+
196
+ out = model.forward(number=max_new_tokens, stopStrings=[
197
+ "<|endoftext|>", username+":"], temp=temperature, top_p_usual=top_p)
198
+
199
+ generated_text = out["output"].lstrip("\n ")
200
+ generated_text = generated_text.rstrip("USER:")
201
+ print(f"{generated_text}")
202
+
203
+ gc.collect()
204
+ history[0].append((prompt, generated_text))
205
+ return history[0], [history[0], out["state"]]
206
+
207
+
208
+ examples = [
209
+ [
210
+ # Question Answering
211
+ '''What is the capital of Germany?''', "Q/A", 25, 0.2, 1.0, "<|endoftext|>"],
212
+ [
213
+ # Question Answering
214
+ '''Are humans good or bad?''', "Q/A", 150, 0.8, 0.8, "<|endoftext|>"],
215
+ [
216
+ # Question Answering
217
+ '''What is the purpose of Vitamin A?''', "Q/A", 50, 0.2, 0.8, "<|endoftext|>"],
218
+ [
219
+ # Chatbot
220
+ '''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.
221
+
222
+ Conversation:
223
+ Alex: Good morning, Fritz, what type of LLM are you based upon?
224
+ Fritz: Morning Alex, I am an RNN with transformer level performance. My language model is 100% attention free.
225
+ Alex:''', "generative", 220, 0.9, 0.9, "\\n\\n,<|endoftext|>"],
226
+ [
227
+ # Generate List
228
+ '''Task given:
229
+
230
+ Please Write a Short story about a cat learning python
231
+
232
+ Best Full Response:
233
+ ''', "generative", 140, 0.85, 0.8, "<|endoftext|>"],
234
+ [
235
+ # Natural Language Interface
236
+ '''Here is a short story (in the style of Tolkien) in which Aiden attacks a robot with a sword:
237
+ ''', "generative", 140, 0.85, 0.8, "<|endoftext|>"]
238
+ ]
239
+
240
+
241
+ iface = gr.Interface(
242
+ fn=infer,
243
+ description=f'''<h3>Generative and Question/Answer</h3>{desc}{thanks}''',
244
+ allow_flagging="never",
245
+ inputs=[
246
+ gr.Textbox(lines=20, label="Prompt"), # prompt
247
+ gr.Radio(["generative", "Q/A"],
248
+ value="generative", label="Choose Mode"),
249
+ gr.Slider(1, 256, value=40), # max_tokens
250
+ gr.Slider(0.0, 1.0, value=0.8), # temperature
251
+ gr.Slider(0.0, 1.0, value=0.85), # top_p
252
+ gr.Slider(-999, 0.0, value=0.0), # end_adj
253
+ gr.Textbox(lines=1, value="<|endoftext|>") # stop
254
+ ],
255
+ outputs=gr.Textbox(label="Generated Output", lines=25),
256
+ examples=examples,
257
+ cache_examples=False,
258
+ ).queue()
259
+
260
+ chatiface = gr.Interface(
261
+ fn=chat,
262
+ description=f'''<h3>Chatbot</h3><h4>Refresh page or change name to reset memory context</h4>{desc}{thanks}''',
263
+ allow_flagging="never",
264
+ inputs=[
265
+ gr.Textbox(lines=5, label="Message"), # prompt
266
+ "state",
267
+ gr.Text(lines=1, value="USER", label="Your Name",
268
+ placeholder="Enter your Name"),
269
+ gr.Slider(1, 256, value=60), # max_tokens
270
+ gr.Slider(0.0, 1.0, value=0.8), # temperature
271
+ gr.Slider(0.0, 1.0, value=0.85) # top_p
272
+ ],
273
+ outputs=[gr.Chatbot(label="Chat Log", color_map=(
274
+ "green", "pink")), "state"],
275
+ ).queue()
276
+
277
+ demo = gr.TabbedInterface(
278
+
279
+ [iface, chatiface], ["Generative", "Chatbot"],
280
+ title=title,
281
+
282
+ )
283
+
284
+ demo.queue()
285
+ demo.launch(share=False)
config.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rwkvstic.agnostic.backends import TORCH, TORCH_QUANT
2
+ import torch
3
+
4
+ quantized = {
5
+ "mode": TORCH_QUANT,
6
+ "runtimedtype": torch.bfloat16,
7
+ "useGPU": torch.cuda.is_available(),
8
+ "chunksize": 32, # larger = more accurate, but more memory
9
+ "target": 100 # your gpu max size, excess vram offloaded to cpu
10
+ }
11
+
12
+ # UNCOMMENT TO SELECT OPTIONS
13
+ # Not full list of options, see https://pypi.org/project/rwkvstic/ and https://huggingface.co/BlinkDL/ for more models/modes
14
+
15
+ # RWKV 1B5 instruct test 1 model
16
+ # Approximate
17
+ # [Vram usage: 6.0GB]
18
+ # [File size: 3.0GB]
19
+
20
+
21
+ config = {
22
+ "path":"https://huggingface.co/BlinkDL/rwkv-4-pile-7b/resolve/main/RWKV-4-Pile-7B-Instruct-test1-20230124.pth",
23
+ "mode":TORCH,
24
+ "runtimedtype":torch.bfloat16,
25
+ "useGPU":torch.cuda.is_available(),
26
+ "dtype":torch.bfloat16
27
+ }
28
+
29
+ title = "RWKV-4 (7B Instruct)"
30
+
31
+ # RWKV 1B5 instruct model quantized
32
+ # Approximate
33
+ # [Vram usage: 1.3GB]
34
+ # [File size: 3.0GB]
35
+
36
+ # config = {
37
+ # "path": "https://huggingface.co/BlinkDL/rwkv-4-pile-1b5/resolve/main/RWKV-4-Pile-1B5-Instruct-test1-20230124.pth",
38
+ # **quantized
39
+ # }
40
+
41
+ # title = "RWKV-4 (1.5b Instruct Quantized)"
42
+
43
+ # RWKV 7B instruct pre-quantized (settings baked into model)
44
+ # Approximate
45
+ # [Vram usage: 7.0GB]
46
+ # [File size: 8.0GB]
47
+
48
+ # config = {
49
+ # "path": "https://huggingface.co/Hazzzardous/RWKV-8Bit/resolve/main/RWKV-4-Pile-7B-Instruct.pqth"
50
+ # }
51
+
52
+ # title = "RWKV-4 (7b Instruct Quantized)"
53
+
54
+ # RWKV 14B quantized (latest as of feb 9)
55
+ # Approximate
56
+ # [Vram usage: 15.0GB]
57
+ # [File size: 15.0GB]
58
+
59
+ # config = {
60
+ # "path": "https://huggingface.co/Hazzzardous/RWKV-8Bit/resolve/main/RWKV-4-Pile-14B-20230204-7324.pqth"
61
+ # }
62
+
63
+ # title = "RWKV-4 (14b 94% trained, not yet instruct tuned, 8-Bit)"
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ inquirer
4
+ rwkvstic>=0.1.5
5
+ scipy