FredZhang7 commited on
Commit
6ea9697
·
1 Parent(s): a47b6b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -41
app.py CHANGED
@@ -1,43 +1,126 @@
1
- import urllib.request
2
-
3
- url = "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-1B5-v2-20231025-ctx4096.pth"
4
- filename = "RWKV-5-World-1B5-v2-20231025-ctx4096.pth"
5
- urllib.request.urlretrieve(url, filename)
6
-
7
  import gradio as gr
 
 
8
  from rwkv.model import RWKV
9
- import torch
10
-
11
- # Load the model
12
- model = RWKV(model='RWKV-5-World-1B5-v2-20231025-ctx4096.pth', strategy='cpu bf16')
13
-
14
- def chatbot_model(instruction, input_prompt, temperature, token_count, top_p, presence_penalty, count_penalty):
15
- # Set the parameters
16
- model.temperature = temperature
17
- model.token_count = token_count
18
- model.top_p = top_p
19
- model.presence_penalty = presence_penalty
20
- model.count_penalty = count_penalty
21
-
22
- # Generate the output
23
- out, state = model.forward([instruction, input_prompt], None)
24
- return out.detach().cpu().numpy()
25
-
26
- # Define the Gradio interface
27
- iface = gr.Interface(
28
- fn=chatbot_model,
29
- inputs=[
30
- gr.Textbox(lines=2, label="Instruction"),
31
- gr.Textbox(lines=2, label="Input Prompt"),
32
- gr.Slider(minimum=0, maximum=2.0, step=0.1, value=1.2, label="Temperature"),
33
- gr.Slider(minimum=0, maximum=300, step=1, value=300, label="Token Count"),
34
- gr.Slider(minimum=0, maximum=1, step=0.05, value=0.5, label="Top P"),
35
- gr.Slider(minimum=0, maximum=1, step=0.1, value=0.4, label="Presence Penalty"),
36
- gr.Slider(minimum=0, maximum=1, step=0.1, value=0.4, label="Count Penalty"),
37
- ],
38
- outputs=gr.Textbox(),
39
- theme="dark" # Change to "dark" for dark mode
40
- )
41
-
42
- # Launch the interface
43
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import gc, copy, re
3
+ from huggingface_hub import hf_hub_download
4
  from rwkv.model import RWKV
5
+ from rwkv.utils import PIPELINE, PIPELINE_ARGS
6
+
7
+ ctx_limit = 2048
8
+ title = "RWKV-5-World-1B5-v2-20231025-ctx4096.pth"
9
+
10
+ model_path = hf_hub_download(repo_id="BlinkDL/rwkv-5-world", filename=f"{title}")
11
+ model = RWKV(model=model_path, strategy='cpu bf16')
12
+ pipeline = PIPELINE(model, "rwkv_vocab_v20230424")
13
+
14
+ def generate_prompt(instruction, input=None):
15
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n').replace('\n\n','\n')
16
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n').replace('\n\n','\n')
17
+ if input:
18
+ return f"""Instruction: {instruction}
19
+ Input: {input}
20
+ Response:"""
21
+ else:
22
+ return f"""Question: {instruction}
23
+ Answer:"""
24
+
25
+ examples = [
26
+ ["東京で訪れるべき素晴らしい場所とその紹介をいくつか挙げてください。", "", 300, 1.2, 0.5, 0.4, 0.4],
27
+ ["Écrivez un programme Python pour miner 1 Bitcoin, avec des commentaires.", "", 300, 1.2, 0.5, 0.4, 0.4],
28
+ ["Write a song about ravens.", "", 300, 1.2, 0.5, 0.4, 0.4],
29
+ ["Explain the following metaphor: Life is like cats.", "", 300, 1.2, 0.5, 0.4, 0.4],
30
+ ["Write a story using the following information", "A man named Alex chops a tree down", 300, 1.2, 0.5, 0.4, 0.4],
31
+ ["Generate a list of adjectives that describe a person as brave.", "", 300, 1.2, 0.5, 0.4, 0.4],
32
+ ["You have $100, and your goal is to turn that into as much money as possible with AI and Machine Learning. Please respond with detailed plan.", "", 300, 1.2, 0.5, 0.4, 0.4],
33
+ ]
34
+
35
+ def evaluate(
36
+ instruction,
37
+ input=None,
38
+ token_count=200,
39
+ temperature=1.0,
40
+ top_p=0.7,
41
+ presencePenalty = 0.1,
42
+ countPenalty = 0.1,
43
+ ):
44
+ args = PIPELINE_ARGS(temperature = max(0.2, float(temperature)), top_p = float(top_p),
45
+ alpha_frequency = countPenalty,
46
+ alpha_presence = presencePenalty,
47
+ token_ban = [], # ban the generation of some tokens
48
+ token_stop = [0]) # stop generation whenever you see any token here
49
+
50
+ instruction = re.sub(r'\n{2,}', '\n', instruction).strip().replace('\r\n','\n')
51
+ input = re.sub(r'\n{2,}', '\n', input).strip().replace('\r\n','\n')
52
+ ctx = generate_prompt(instruction, input)
53
+
54
+ all_tokens = []
55
+ out_last = 0
56
+ out_str = ''
57
+ occurrence = {}
58
+ state = None
59
+ for i in range(int(token_count)):
60
+ out, state = model.forward(pipeline.encode(ctx)[-ctx_limit:] if i == 0 else [token], state)
61
+ for n in occurrence:
62
+ out[n] -= (args.alpha_presence + occurrence[n] * args.alpha_frequency)
63
+
64
+ token = pipeline.sample_logits(out, temperature=args.temperature, top_p=args.top_p)
65
+ if token in args.token_stop:
66
+ break
67
+ all_tokens += [token]
68
+ for xxx in occurrence:
69
+ occurrence[xxx] *= 0.996
70
+ if token not in occurrence:
71
+ occurrence[token] = 1
72
+ else:
73
+ occurrence[token] += 1
74
+
75
+ tmp = pipeline.decode(all_tokens[out_last:])
76
+ if '\ufffd' not in tmp:
77
+ out_str += tmp
78
+ yield out_str.strip()
79
+ out_last = i + 1
80
+ if '\n\n' in out_str:
81
+ break
82
+
83
+ del out
84
+ del state
85
+ gc.collect()
86
+ yield out_str.strip()
87
+
88
+ def user(message, chatbot):
89
+ chatbot = chatbot or []
90
+ return "", chatbot + [[message, None]]
91
+
92
+ def alternative(chatbot, history):
93
+ if not chatbot or not history:
94
+ return chatbot, history
95
+
96
+ chatbot[-1][1] = None
97
+ history[0] = copy.deepcopy(history[1])
98
+
99
+ return chatbot, history
100
+
101
+
102
+ with gr.Blocks(title=title) as demo:
103
+ gr.HTML(f"<div style=\"text-align: center;\">\n<h1>🌍World - {title}</h1>\n</div>")
104
+ with gr.Tab("Instruct mode"):
105
+ gr.Markdown(f"World is RWKV-5 World 1.5B 100% RNN RWKV-LM **trained on 100+ world languages**. Demo limited to ctxlen {ctx_limit}. Finetuned on alpaca, gpt4all, codealpaca and more. For best results, ** keep you prompt short and clear **.</b>.") # <b>UPDATE: now with Chat (see above, as a tab) ==> turn off as of now due to VRAM leak caused by buggy code.
106
+ with gr.Row():
107
+ with gr.Column():
108
+ instruction = gr.Textbox(lines=2, label="Instruction", value='東京で訪れるべき素晴らしい場所とその紹介をいくつか挙げてください。')
109
+ input = gr.Textbox(lines=2, label="Input", placeholder="none")
110
+ token_count = gr.Slider(10, 300, label="Max Tokens", step=10, value=300)
111
+ temperature = gr.Slider(0.2, 2.0, label="Temperature", step=0.1, value=1.2)
112
+ top_p = gr.Slider(0.0, 1.0, label="Top P", step=0.05, value=0.5)
113
+ presence_penalty = gr.Slider(0.0, 1.0, label="Presence Penalty", step=0.1, value=0.4)
114
+ count_penalty = gr.Slider(0.0, 1.0, label="Count Penalty", step=0.1, value=0.4)
115
+ with gr.Column():
116
+ with gr.Row():
117
+ submit = gr.Button("Submit", variant="primary")
118
+ clear = gr.Button("Clear", variant="secondary")
119
+ output = gr.Textbox(label="Output", lines=5)
120
+ data = gr.Dataset(components=[instruction, input, token_count, temperature, top_p, presence_penalty, count_penalty], samples=examples, label="Example Instructions", headers=["Instruction", "Input", "Max Tokens", "Temperature", "Top P", "Presence Penalty", "Count Penalty"])
121
+ submit.click(evaluate, [instruction, input, token_count, temperature, top_p, presence_penalty, count_penalty], [output])
122
+ clear.click(lambda: None, [], [output])
123
+ data.click(lambda x: x, [data], [instruction, input, token_count, temperature, top_p, presence_penalty, count_penalty])
124
+
125
+ demo.queue(concurrency_count=1, max_size=10)
126
+ demo.launch(share=False)