howard-hou commited on
Commit
d889050
1 Parent(s): c804cf5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -0
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os, gc, copy, torch
3
+ from datetime import datetime
4
+ from huggingface_hub import hf_hub_download
5
+ from transformers import CLIPVisionModel
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ ctx_limit = 3500
10
+ title = "rwkv1b5-vitl336p14-577token_mix665k_rwkv"
11
+
12
+ os.environ["RWKV_JIT_ON"] = '1'
13
+ os.environ["RWKV_CUDA_ON"] = '0' # if '1' then use CUDA kernel for seq mode (much faster)
14
+
15
+ from rwkv.model import RWKV
16
+ model_path = hf_hub_download(repo_id="howard-hou/visualrwkv-5", filename=f"{title}.pth")
17
+ model = RWKV(model=model_path, strategy='cpu fp32')
18
+ from rwkv.utils import PIPELINE, PIPELINE_ARGS
19
+ pipeline = PIPELINE(model, "rwkv_vocab_v20230424")
20
+
21
+
22
+ class VisualRWKV(nn.Module):
23
+ def __init__(self, args):
24
+ super().__init__()
25
+ self.args = args
26
+ self.vit = CLIPVisionModel.from_pretrained(args.vision_tower_name)
27
+ self.proj = nn.Linear(self.vit.config.hidden_size, args.n_embd, bias=False)
28
+
29
+ def encode_images(self, images):
30
+ B, N, C, H, W = images.shape
31
+ images = images.view(B*N, C, H, W)
32
+ image_features = self.vit(images).last_hidden_state
33
+ L, D = image_features.shape[1], image_features.shape[2]
34
+ # rerange [B*N, L, D] -> [B, N, L, D]
35
+ image_features = image_features.view(B, N, L, D)[:, 0, :, :]
36
+ image_features = self.grid_pooling(image_features)
37
+ return self.proj(image_features)
38
+
39
+ def grid_pooling(self, image_features):
40
+ if self.args.grid_size == -1: # no grid pooling
41
+ return image_features
42
+ if self.args.grid_size == 0: # take cls token
43
+ return image_features[:, 0:1, :]
44
+ if self.args.grid_size == 1: # global avg pooling
45
+ return image_features.mean(dim=1, keepdim=True)
46
+ cls_features = image_features[:, 0:1, :]
47
+ image_features = image_features[:, 1:, :] #drop cls token
48
+ B, L, D = image_features.shape
49
+ H_or_W = int(L**0.5)
50
+ image_features = image_features.view(B, H_or_W, H_or_W, D)
51
+ grid_stride = H_or_W // self.args.grid_size
52
+ image_features = F.avg_pool2d(image_features.permute(0, 3, 1, 2),
53
+ padding=0,
54
+ kernel_size=grid_stride,
55
+ stride=grid_stride)
56
+ image_features = image_features.permute(0, 2, 3, 1).view(B, -1, D)
57
+ return torch.cat((cls_features, image_features), dim=1)
58
+
59
+
60
+ ##########################################################################
61
+
62
+
63
+ def generate_prompt(instruction, input=""):
64
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
65
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
66
+ if input:
67
+ return f"""Instruction: {instruction}
68
+
69
+ Input: {input}
70
+
71
+ Response:"""
72
+ else:
73
+ return f"""User: hi
74
+
75
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
76
+
77
+ User: {instruction}
78
+
79
+ Assistant:"""
80
+
81
+ def evaluate(
82
+ ctx,
83
+ token_count=200,
84
+ temperature=1.0,
85
+ top_p=0.7,
86
+ presencePenalty = 0.1,
87
+ countPenalty = 0.1,
88
+ ):
89
+ args = PIPELINE_ARGS(temperature = max(0.2, float(temperature)), top_p = float(top_p),
90
+ alpha_frequency = countPenalty,
91
+ alpha_presence = presencePenalty,
92
+ token_ban = [], # ban the generation of some tokens
93
+ token_stop = [0]) # stop generation whenever you see any token here
94
+ ctx = ctx.strip()
95
+ all_tokens = []
96
+ out_last = 0
97
+ out_str = ''
98
+ occurrence = {}
99
+ state = None
100
+ for i in range(int(token_count)):
101
+ out, state = model.forward(pipeline.encode(ctx)[-ctx_limit:] if i == 0 else [token], state)
102
+ for n in occurrence:
103
+ out[n] -= (args.alpha_presence + occurrence[n] * args.alpha_frequency)
104
+
105
+ token = pipeline.sample_logits(out, temperature=args.temperature, top_p=args.top_p)
106
+ if token in args.token_stop:
107
+ break
108
+ all_tokens += [token]
109
+ for xxx in occurrence:
110
+ occurrence[xxx] *= 0.996
111
+ if token not in occurrence:
112
+ occurrence[token] = 1
113
+ else:
114
+ occurrence[token] += 1
115
+
116
+ tmp = pipeline.decode(all_tokens[out_last:])
117
+ if '\ufffd' not in tmp:
118
+ out_str += tmp
119
+ yield out_str.strip()
120
+ out_last = i + 1
121
+
122
+ del out
123
+ del state
124
+ gc.collect()
125
+ yield out_str.strip()
126
+
127
+ examples = [
128
+ ["Assistant: Sure! Here is a very detailed plan to create flying pigs:", 333, 1, 0.3, 0, 1],
129
+ ["Assistant: Sure! Here are some ideas for FTL drive:", 333, 1, 0.3, 0, 1],
130
+ ["A few light taps upon the pane made her turn to the window. It had begun to snow again.", 333, 1, 0.3, 0, 1],
131
+ [generate_prompt("Écrivez un programme Python pour miner 1 Bitcoin, avec des commentaires."), 333, 1, 0.3, 0, 1],
132
+ [generate_prompt("東京で訪れるべき素晴らしい場所とその紹介をいくつか挙げてください。"), 333, 1, 0.3, 0, 1],
133
+ [generate_prompt("Write a story using the following information.", "A man named Alex chops a tree down."), 333, 1, 0.3, 0, 1],
134
+ ["Assistant: Here is a very detailed plan to kill all mosquitoes:", 333, 1, 0.3, 0, 1],
135
+ ['''Edward: I am Edward Elric from fullmetal alchemist. I am in the world of full metal alchemist and know nothing of the real world.
136
+
137
+ Player: Hello Edward. What have you been up to recently?
138
+
139
+ Edward:''', 333, 1, 0.3, 0, 1],
140
+ [generate_prompt("写一篇关于水利工程的流体力学模型的论文,需要详细全面。"), 333, 1, 0.3, 0, 1],
141
+ ['''“当然可以,大宇宙不会因为这五公斤就不坍缩了。”关一帆说,他还有一个没说出来的想法:也许大宇宙真的会因为相差一个原子的质量而由封闭转为开放。大自然的精巧有时超出想象,比如生命的诞生,就需要各项宇宙参数在几亿亿分之一精度上的精确配合。但程心仍然可以留下她的生态球,因为在那无数文明创造的无数小宇宙中,肯定有相当一部分不响应回归运动的号召,所以,大宇宙最终被夺走的质量至少有几亿吨,甚至可能是几亿亿亿吨。
142
+ 但愿大宇宙能够忽略这个误差。
143
+ 程心和关一帆进入了飞船,智子最后也进来了。她早就不再穿那身华丽的和服了,她现在身着迷彩服,再次成为一名轻捷精悍的战士,她的身上佩带着许多武器和生存装备,最引人注目的是那把插在背后的武士刀。
144
+ “放心,我在,你们就在!”智子对两位人类朋友说。
145
+ 聚变发动机启动了,推进器发出幽幽的蓝光,飞船缓缓地穿过了宇宙之门。
146
+ 小宇宙中只剩下漂流瓶和生态球。漂流瓶隐没于黑暗里,在一千米见方的宇宙中,只有生态球里的小太阳发出一点光芒。在这个小小的生命世界中,几只清澈的水球在零重力环境中静静地飘浮着,有一条小鱼从一只水球中蹦出,跃入另一只水球,轻盈地穿游于绿藻之间。在一小块陆地上的草丛中,有一滴露珠从一片草叶上脱离,旋转着飘起,向太空中折射出一缕晶莹的阳光。''', 333, 1, 0.3, 0, 1],
147
+ ]
148
+
149
+ ##########################################################################
150
+
151
+ with gr.Blocks(title=title) as demo:
152
+ gr.HTML(f"<div style=\"text-align: center;\">\n<h1>RWKV-5 World v2 - {title}</h1>\n</div>")
153
+ with gr.Tab("Raw Generation"):
154
+ gr.Markdown(f"This is [RWKV-5 World v2](https://huggingface.co/BlinkDL/rwkv-5-world) with 1.5B params - a 100% attention-free RNN [RWKV-LM](https://github.com/BlinkDL/RWKV-LM). Supports all 100+ world languages and code. And we have [200+ Github RWKV projects](https://github.com/search?o=desc&p=1&q=rwkv&s=updated&type=Repositories). *** Please try examples first (bottom of page) *** (edit them to use your question). Demo limited to ctxlen {ctx_limit}.")
155
+ with gr.Row():
156
+ with gr.Column():
157
+ prompt = gr.Textbox(lines=2, label="Prompt", value="Assistant: Sure! Here is a very detailed plan to create flying pigs:")
158
+ token_count = gr.Slider(10, 333, label="Max Tokens", step=10, value=333)
159
+ temperature = gr.Slider(0.2, 2.0, label="Temperature", step=0.1, value=1.0)
160
+ top_p = gr.Slider(0.0, 1.0, label="Top P", step=0.05, value=0.3)
161
+ presence_penalty = gr.Slider(0.0, 1.0, label="Presence Penalty", step=0.1, value=0)
162
+ count_penalty = gr.Slider(0.0, 1.0, label="Count Penalty", step=0.1, value=1)
163
+ with gr.Column():
164
+ with gr.Row():
165
+ submit = gr.Button("Submit", variant="primary")
166
+ clear = gr.Button("Clear", variant="secondary")
167
+ output = gr.Textbox(label="Output", lines=5)
168
+ data = gr.Dataset(components=[prompt, token_count, temperature, top_p, presence_penalty, count_penalty],
169
+ samples=examples, label="Example Instructions",
170
+ headers=["Prompt", "Max Tokens", "Temperature", "Top P", "Presence Penalty", "Count Penalty"])
171
+ submit.click(evaluate, [prompt, token_count, temperature, top_p, presence_penalty, count_penalty], [output])
172
+ clear.click(lambda: None, [], [output])
173
+ data.click(lambda x: x, [data], [prompt, token_count, temperature, top_p, presence_penalty, count_penalty])
174
+
175
+ demo.queue(concurrency_count=1, max_size=10)
176
+ demo.launch(share=False)