wangrongsheng commited on
Commit
7b61043
·
1 Parent(s): a4e7b41

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +371 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Credit to https://github.com/THUDM/ChatGLM2-6B/blob/main/web_demo.py while mistakes are mine."""
2
+ # pylint: disable=broad-exception-caught, redefined-outer-name, missing-function-docstring, missing-module-docstring, too-many-arguments, line-too-long, invalid-name, redefined-builtin, redefined-argument-from-local
3
+ # import gradio as gr
4
+
5
+ # model_name = "models/THUDM/chatglm2-6b-int4"
6
+ # gr.load(model_name).lauch()
7
+
8
+ # %%writefile demo-4bit.py
9
+
10
+ import os
11
+ import time
12
+ from textwrap import dedent
13
+
14
+ import gradio as gr
15
+ import mdtex2html
16
+ import torch
17
+ from loguru import logger
18
+ from transformers import AutoModel, AutoTokenizer
19
+
20
+ # fix timezone in Linux
21
+ os.environ["TZ"] = "Asia/Shanghai"
22
+ try:
23
+ time.tzset() # type: ignore # pylint: disable=no-member
24
+ except Exception:
25
+ # Windows
26
+ logger.warning("Windows, cant run time.tzset()")
27
+
28
+
29
+
30
+ model_name = "wangrongsheng/Med-InternLM"
31
+
32
+ RETRY_FLAG = False
33
+
34
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
35
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True).quantize(4).half().cuda()
36
+ #model = AutoModel.from_pretrained(model_name, trust_remote_code=True).half().cuda()
37
+ model = model.eval()
38
+
39
+ _ = """Override Chatbot.postprocess"""
40
+
41
+
42
+ def postprocess(self, y):
43
+ if y is None:
44
+ return []
45
+ for i, (message, response) in enumerate(y):
46
+ y[i] = (
47
+ None if message is None else mdtex2html.convert((message)),
48
+ None if response is None else mdtex2html.convert(response),
49
+ )
50
+ return y
51
+
52
+
53
+ gr.Chatbot.postprocess = postprocess
54
+
55
+
56
+ def parse_text(text):
57
+ lines = text.split("\n")
58
+ lines = [line for line in lines if line != ""]
59
+ count = 0
60
+ for i, line in enumerate(lines):
61
+ if "```" in line:
62
+ count += 1
63
+ items = line.split("`")
64
+ if count % 2 == 1:
65
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
66
+ else:
67
+ lines[i] = "<br></code></pre>"
68
+ else:
69
+ if i > 0:
70
+ if count % 2 == 1:
71
+ line = line.replace("`", r"\`")
72
+ line = line.replace("<", "&lt;")
73
+ line = line.replace(">", "&gt;")
74
+ line = line.replace(" ", "&nbsp;")
75
+ line = line.replace("*", "&ast;")
76
+ line = line.replace("_", "&lowbar;")
77
+ line = line.replace("-", "&#45;")
78
+ line = line.replace(".", "&#46;")
79
+ line = line.replace("!", "&#33;")
80
+ line = line.replace("(", "&#40;")
81
+ line = line.replace(")", "&#41;")
82
+ line = line.replace("$", "&#36;")
83
+ lines[i] = "<br>" + line
84
+ text = "".join(lines)
85
+ return text
86
+
87
+
88
+ def predict(
89
+ RETRY_FLAG, input, chatbot, max_length, top_p, temperature, history, past_key_values
90
+ ):
91
+ try:
92
+ chatbot.append((parse_text(input), ""))
93
+ except Exception as exc:
94
+ logger.error(exc)
95
+ logger.debug(f"{chatbot=}")
96
+ _ = """
97
+ if chatbot:
98
+ chatbot[-1] = (parse_text(input), str(exc))
99
+ yield chatbot, history, past_key_values
100
+ # """
101
+ yield chatbot, history, past_key_values
102
+ """
103
+ for response, history, past_key_values in model.stream_chat(
104
+ tokenizer,
105
+ input,
106
+ history,
107
+ past_key_values=past_key_values,
108
+ return_past_key_values=True,
109
+ max_length=max_length,
110
+ top_p=top_p,
111
+ temperature=temperature,
112
+ ):
113
+ """
114
+ for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
115
+ temperature=temperature):
116
+ chatbot[-1] = (parse_text(input), parse_text(response))
117
+
118
+ yield chatbot, history, past_key_values
119
+
120
+
121
+ def trans_api(input, max_length=40960, top_p=0.7, temperature=0.95):
122
+ if max_length < 10:
123
+ max_length = 40960
124
+ if top_p < 0.1 or top_p > 1:
125
+ top_p = 0.7
126
+ if temperature <= 0 or temperature > 1:
127
+ temperature = 0.01
128
+ try:
129
+ res, _ = model.chat(
130
+ tokenizer,
131
+ input,
132
+ history=[],
133
+ past_key_values=None,
134
+ max_length=max_length,
135
+ top_p=top_p,
136
+ temperature=temperature,
137
+ )
138
+ # logger.debug(f"{res=} \n{_=}")
139
+ except Exception as exc:
140
+ logger.error(f"{exc=}")
141
+ res = str(exc)
142
+
143
+ return res
144
+
145
+
146
+ def reset_user_input():
147
+ return gr.update(value="")
148
+
149
+
150
+ def reset_state():
151
+ return [], [], None
152
+
153
+
154
+ # Delete last turn
155
+ def delete_last_turn(chat, history):
156
+ if chat and history:
157
+ chat.pop(-1)
158
+ history.pop(-1)
159
+ return chat, history
160
+
161
+
162
+ # Regenerate response
163
+ def retry_last_answer(
164
+ user_input, chatbot, max_length, top_p, temperature, history, past_key_values
165
+ ):
166
+ if chatbot and history:
167
+ # Removing the previous conversation from chat
168
+ chatbot.pop(-1)
169
+ # Setting up a flag to capture a retry
170
+ RETRY_FLAG = True
171
+ # Getting last message from user
172
+ user_input = history[-1][0]
173
+ # Removing bot response from the history
174
+ history.pop(-1)
175
+
176
+ yield from predict(
177
+ RETRY_FLAG, # type: ignore
178
+ user_input,
179
+ chatbot,
180
+ max_length,
181
+ top_p,
182
+ temperature,
183
+ history,
184
+ past_key_values,
185
+ )
186
+
187
+
188
+ with gr.Blocks(title="ChatGLM2-6B-int4", theme=gr.themes.Soft(text_size="sm")) as demo:
189
+ # gr.HTML("""<h1 align="center">ChatGLM2-6B-int4</h1>""")
190
+ gr.HTML(
191
+ """<h1 align="center">Med-InternLM-7B</h1>"""
192
+ )
193
+
194
+ with gr.Accordion("🎈 Info", open=False):
195
+ _ = f"""
196
+ ## 欢迎体验Med-InternLM-7B
197
+
198
+ [模型下载地址](https://huggingface.co/wangrongsheng/Med-InternLM)
199
+ """
200
+ gr.Markdown(dedent(_))
201
+ chatbot = gr.Chatbot()
202
+ with gr.Row():
203
+ with gr.Column(scale=4):
204
+ with gr.Column(scale=12):
205
+ user_input = gr.Textbox(
206
+ show_label=False,
207
+ placeholder="Input...",
208
+ ).style(container=False)
209
+ RETRY_FLAG = gr.Checkbox(value=False, visible=False)
210
+ with gr.Column(min_width=32, scale=1):
211
+ with gr.Row():
212
+ submitBtn = gr.Button("Submit", variant="primary")
213
+ deleteBtn = gr.Button("删除最后一条对话", variant="secondary")
214
+ retryBtn = gr.Button("重新生成Regenerate", variant="secondary")
215
+ with gr.Column(scale=1):
216
+ emptyBtn = gr.Button("Clear History")
217
+ max_length = gr.Slider(
218
+ 0,
219
+ 32768,
220
+ value=8192,
221
+ step=1.0,
222
+ label="Maximum length",
223
+ interactive=True,
224
+ )
225
+ top_p = gr.Slider(
226
+ 0, 1, value=0.85, step=0.01, label="Top P", interactive=True
227
+ )
228
+ temperature = gr.Slider(
229
+ 0.01, 1, value=0.95, step=0.01, label="Temperature", interactive=True
230
+ )
231
+
232
+ history = gr.State([])
233
+ past_key_values = gr.State(None)
234
+
235
+ user_input.submit(
236
+ predict,
237
+ [
238
+ RETRY_FLAG,
239
+ user_input,
240
+ chatbot,
241
+ max_length,
242
+ top_p,
243
+ temperature,
244
+ history,
245
+ past_key_values,
246
+ ],
247
+ [chatbot, history, past_key_values],
248
+ show_progress="full",
249
+ )
250
+ submitBtn.click(
251
+ predict,
252
+ [
253
+ RETRY_FLAG,
254
+ user_input,
255
+ chatbot,
256
+ max_length,
257
+ top_p,
258
+ temperature,
259
+ history,
260
+ past_key_values,
261
+ ],
262
+ [chatbot, history, past_key_values],
263
+ show_progress="full",
264
+ api_name="predict",
265
+ )
266
+ submitBtn.click(reset_user_input, [], [user_input])
267
+
268
+ emptyBtn.click(
269
+ reset_state, outputs=[chatbot, history, past_key_values], show_progress="full"
270
+ )
271
+
272
+ retryBtn.click(
273
+ retry_last_answer,
274
+ inputs=[
275
+ user_input,
276
+ chatbot,
277
+ max_length,
278
+ top_p,
279
+ temperature,
280
+ history,
281
+ past_key_values,
282
+ ],
283
+ # outputs = [chatbot, history, last_user_message, user_message]
284
+ outputs=[chatbot, history, past_key_values],
285
+ )
286
+ deleteBtn.click(delete_last_turn, [chatbot, history], [chatbot, history])
287
+
288
+ with gr.Accordion("Example inputs", open=True):
289
+ etext = """In America, where cars are an important part of the national psyche, a decade ago people had suddenly started to drive less, which had not happened since the oil shocks of the 1970s. """
290
+ etext1 = """云南大学(Yunnan University),简称云大(YNU),位于云南省昆明市,是教育部与云南省“以部为主、部省合建”的全国重点大学,国家“双一流”建设高校 [31] 、211工程、一省一校、中西部高校基础能力建设工程,云南省重点支持的国家一流大学建设高校,“111计划”、卓越法律人才教育培养计划、卓越工程师教育培养计划、国家建设高水平大学公派研究生项目、中国政府奖学金来华留学生接收院校、全国深化创新创业教育改革示范高校,为中西部“一省一校”国家重点建设大学(Z14)联盟、南亚东南亚大学联盟牵头单位。 [1]
291
+ 云南大学始建于1922年,时为私立东陆大学。1930年,改为省立东陆大学。1934年更名为省立云南大学。1938年改为国立云南大学。1946年,《不列颠百科全书》将云南大学列为中国15所在世界最具影响的大学之一。1950年定名为云南大学。1958年,云南大学由中央高教部划归云南省管理。1978年,云南大学被国务院确定为88所全国重点大学之一。1996年首批列入国家“211工程”重点建设大学。1999年,云南政法高等专科学校并入云南大学。 [2] [23]
292
+ 截至2023年6月,学校有呈贡、东陆两校区,占地面积4367亩,校舍建筑面积133余万平方米,馆藏书400万余册;设有28个学院,本科专业84个;有博士后科研流动站14个,22个一级学科博士学位授权点,1个专业博士学位授权,42个一级学科硕士学位授权,26个专业硕士学位授权;教职员工3000余人,全日制本科生近17000人,全日制硕士研究生近12000人,博士研究生1500余人。 """
293
+ examples = gr.Examples(
294
+ examples=[
295
+ ["熬夜对身体有什么危害? "],
296
+ ["新冠肺炎怎么预防"],
297
+ ["系统性红斑狼疮的危害和治疗方法是什么?"],
298
+ [
299
+ "我经常感觉郁闷,而且控制不住情绪,经常对周围的人喊叫,怎么办?"
300
+ ],
301
+ ["太阳为什么会发热? "],
302
+ ["指南针是怎么工作的?"],
303
+ ["在野外怎么辨别方向?"],
304
+ [
305
+ "世界最长的桥是那一座?"
306
+ ],
307
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born? "],
308
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born? Think step by step."],
309
+ ["Explain the plot of Cinderella in a sentence."],
310
+ [
311
+ "How long does it take to become proficient in French, and what are the best methods for retaining information?"
312
+ ],
313
+ ["What are some common mistakes to avoid when writing code?"],
314
+ ["Build a prompt to generate a beautiful portrait of a horse"],
315
+ ["Suggest four metaphors to describe the benefits of AI"],
316
+ ["Write a pop song about leaving home for the sandy beaches."],
317
+ ["Write a summary demonstrating my ability to tame lions"],
318
+ ["鲁迅和周树人什么关系"],
319
+ ["从前有一头牛,这头牛后面有什么?"],
320
+ ["正无穷大加一大于正无穷大吗?"],
321
+ ["正无穷大加正无穷大大于正无穷大吗?"],
322
+ ["-2的平方根等于什么"],
323
+ ["树上有5只鸟,猎人开枪打死了一只。树上还有几只鸟?Think step by step."],
324
+ ["树上有11只鸟,猎人开枪打死了一只。树上还有几只鸟?提示:需考虑鸟可能受惊吓飞走。Think step by step."],
325
+ ["鲁迅和周树人什么关系 用英文回答"],
326
+ ["以红楼梦的行文风格写一张委婉的请假条。不少于320字。"],
327
+ [f"{etext1} 总结这篇文章的主要内容和文章结构"],
328
+ [f"{etext} 翻成中文,列出3个版本"],
329
+ [f"{etext} \n 翻成中文,保留原意,但使用文学性的语言。不要写解释。列出3个版本"],
330
+ ["js 判断一个数是不是质数"],
331
+ ["js 实现python 的 range(10)"],
332
+ ["js 实现python 的 [*(range(10)]"],
333
+ ["假定 1 + 2 = 4, 试求 7 + 8,Think step by step." ],
334
+ ["2023年云南大学成立100周年,它是哪一年成立的?" ],
335
+ ["Erkläre die Handlung von Cinderella in einem Satz."],
336
+ ["Erkläre die Handlung von Cinderella in einem Satz. Auf Deutsch"],
337
+ ],
338
+ inputs=[user_input],
339
+ examples_per_page=50,
340
+ )
341
+
342
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
343
+ input_text = gr.Text()
344
+ tr_btn = gr.Button("Go", variant="primary")
345
+ out_text = gr.Text()
346
+ tr_btn.click(
347
+ trans_api,
348
+ [input_text, max_length, top_p, temperature],
349
+ out_text,
350
+ # show_progress="full",
351
+ api_name="tr",
352
+ )
353
+ _ = """
354
+ input_text.submit(
355
+ trans_api,
356
+ [input_text, max_length, top_p, temperature],
357
+ out_text,
358
+ show_progress="full",
359
+ api_name="tr1",
360
+ )
361
+ # """
362
+
363
+ # demo.queue().launch(share=False, inbrowser=True)
364
+ # demo.queue().launch(share=True, inbrowser=True, debug=True)
365
+
366
+ # concurrency_count > 1 requires more memory, max_size: queue size
367
+ # T4 medium: 30GB, model size: ~4G concurrency_count = 6
368
+ # leave one for api access
369
+ # reduce to 5 if OOM occurs to often
370
+
371
+ demo.queue(concurrency_count=6, max_size=30).launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ protobuf
2
+ transformers==4.30.2
3
+ cpm_kernels
4
+ torch>=2.0
5
+ # gradio
6
+ mdtex2html
7
+ sentencepiece
8
+ accelerate
9
+ loguru