fb700 commited on
Commit
961fd98
1 Parent(s): fb5377c

Upload 4 files

Browse files
Files changed (4) hide show
  1. .flake8 +21 -0
  2. .gitignore +0 -0
  3. app.py +315 -30
  4. requirements.txt +4 -6
.flake8 ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [flake8]
2
+ ignore =
3
+ # E203 whitespace before ':'
4
+ E203
5
+ D203,
6
+ # line too long
7
+ E501
8
+ per-file-ignores =
9
+ # imported but unused
10
+ # __init__.py: F401
11
+ test_*.py: F401
12
+ exclude =
13
+ .git,
14
+ __pycache__,
15
+ docs/source/conf.py,
16
+ old,
17
+ build,
18
+ dist,
19
+ .venv
20
+ pad*.py
21
+ max-complexity = 25
.gitignore ADDED
File without changes
app.py CHANGED
@@ -1,14 +1,41 @@
1
- from transformers import AutoModel, AutoTokenizer
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
  import mdtex2html
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- checkpoint = "fb700/chatglm-fitness-RLHF"
6
 
7
- tokenizer = AutoTokenizer.from_pretrained(checkpoint, trust_remote_code=True)
8
- model = AutoModel.from_pretrained(checkpoint, trust_remote_code=True).quantize(4).half().cuda()
 
 
 
 
 
9
  model = model.eval()
10
 
11
- """Override Chatbot.postprocess"""
12
 
13
 
14
  def postprocess(self, y):
@@ -26,22 +53,21 @@ gr.Chatbot.postprocess = postprocess
26
 
27
 
28
  def parse_text(text):
29
- """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
30
  lines = text.split("\n")
31
  lines = [line for line in lines if line != ""]
32
  count = 0
33
  for i, line in enumerate(lines):
34
  if "```" in line:
35
  count += 1
36
- items = line.split('`')
37
  if count % 2 == 1:
38
  lines[i] = f'<pre><code class="language-{items[-1]}">'
39
  else:
40
- lines[i] = f'<br></code></pre>'
41
  else:
42
  if i > 0:
43
  if count % 2 == 1:
44
- line = line.replace("`", "\`")
45
  line = line.replace("<", "&lt;")
46
  line = line.replace(">", "&gt;")
47
  line = line.replace(" ", "&nbsp;")
@@ -53,51 +79,310 @@ def parse_text(text):
53
  line = line.replace("(", "&#40;")
54
  line = line.replace(")", "&#41;")
55
  line = line.replace("$", "&#36;")
56
- lines[i] = "<br>"+line
57
  text = "".join(lines)
58
  return text
59
 
60
 
61
- def predict(input, chatbot, max_length, top_p, temperature, history):
62
- chatbot.append((parse_text(input), ""))
63
- for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
64
- temperature=temperature):
65
- chatbot[-1] = (parse_text(input), parse_text(response))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- yield chatbot, history
68
 
69
 
70
  def reset_user_input():
71
- return gr.update(value='')
72
 
73
 
74
  def reset_state():
75
- return [], []
76
 
77
 
78
- with gr.Blocks() as demo:
79
- gr.HTML("""<h1 align="center">帛凡 ChatGLM-6b-fitness-RLHF 演示 </h1>""")
 
 
 
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  chatbot = gr.Chatbot()
82
  with gr.Row():
83
  with gr.Column(scale=4):
84
  with gr.Column(scale=12):
85
- user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(
86
- container=False)
 
 
 
87
  with gr.Column(min_width=32, scale=1):
88
- submitBtn = gr.Button("Submit", variant="primary")
 
 
 
89
  with gr.Column(scale=1):
90
  emptyBtn = gr.Button("Clear History")
91
- max_length = gr.Slider(0, 40960, value=20480, step=1.0, label="Maximum length", interactive=True)
92
- top_p = gr.Slider(0, 1, value=0.7, step=0.01, label="Top P", interactive=True)
93
- temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  history = gr.State([])
 
96
 
97
- submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history], [chatbot, history],
98
- show_progress=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  submitBtn.click(reset_user_input, [], [user_input])
100
 
101
- emptyBtn.click(reset_state, outputs=[chatbot, history], show_progress=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- demo.queue().launch(share=False, inbrowser=True)
 
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 = "fb700/chatglm-fitness-RLHF"
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 = model.eval()
37
 
38
+ _ = """Override Chatbot.postprocess"""
39
 
40
 
41
  def postprocess(self, y):
 
53
 
54
 
55
  def parse_text(text):
 
56
  lines = text.split("\n")
57
  lines = [line for line in lines if line != ""]
58
  count = 0
59
  for i, line in enumerate(lines):
60
  if "```" in line:
61
  count += 1
62
+ items = line.split("`")
63
  if count % 2 == 1:
64
  lines[i] = f'<pre><code class="language-{items[-1]}">'
65
  else:
66
+ lines[i] = "<br></code></pre>"
67
  else:
68
  if i > 0:
69
  if count % 2 == 1:
70
+ line = line.replace("`", r"\`")
71
  line = line.replace("<", "&lt;")
72
  line = line.replace(">", "&gt;")
73
  line = line.replace(" ", "&nbsp;")
 
79
  line = line.replace("(", "&#40;")
80
  line = line.replace(")", "&#41;")
81
  line = line.replace("$", "&#36;")
82
+ lines[i] = "<br>" + line
83
  text = "".join(lines)
84
  return text
85
 
86
 
87
+ def predict(
88
+ RETRY_FLAG, input, chatbot, max_length, top_p, temperature, history, past_key_values
89
+ ):
90
+ try:
91
+ chatbot.append((parse_text(input), ""))
92
+ except Exception as exc:
93
+ logger.error(exc)
94
+ logger.debug(f"{chatbot=}")
95
+ _ = """
96
+ if chatbot:
97
+ chatbot[-1] = (parse_text(input), str(exc))
98
+ yield chatbot, history, past_key_values
99
+ # """
100
+ yield chatbot, history, past_key_values
101
+
102
+ for response, history, past_key_values in model.stream_chat(
103
+ tokenizer,
104
+ input,
105
+ history,
106
+ past_key_values=past_key_values,
107
+ return_past_key_values=True,
108
+ max_length=max_length,
109
+ top_p=top_p,
110
+ temperature=temperature,
111
+ ):
112
+ chatbot[-1] = (parse_text(input), parse_text(response))
113
+
114
+ yield chatbot, history, past_key_values
115
+
116
+
117
+ def trans_api(input, max_length=40960, top_p=0.7, temperature=0.95):
118
+ if max_length < 10:
119
+ max_length = 40960
120
+ if top_p < 0.1 or top_p > 1:
121
+ top_p = 0.7
122
+ if temperature <= 0 or temperature > 1:
123
+ temperature = 0.01
124
+ try:
125
+ res, _ = model.chat(
126
+ tokenizer,
127
+ input,
128
+ history=[],
129
+ past_key_values=None,
130
+ max_length=max_length,
131
+ top_p=top_p,
132
+ temperature=temperature,
133
+ )
134
+ # logger.debug(f"{res=} \n{_=}")
135
+ except Exception as exc:
136
+ logger.error(f"{exc=}")
137
+ res = str(exc)
138
 
139
+ return res
140
 
141
 
142
  def reset_user_input():
143
+ return gr.update(value="")
144
 
145
 
146
  def reset_state():
147
+ return [], [], None
148
 
149
 
150
+ # Delete last turn
151
+ def delete_last_turn(chat, history):
152
+ if chat and history:
153
+ chat.pop(-1)
154
+ history.pop(-1)
155
+ return chat, history
156
 
157
+
158
+ # Regenerate response
159
+ def retry_last_answer(
160
+ user_input, chatbot, max_length, top_p, temperature, history, past_key_values
161
+ ):
162
+ if chatbot and history:
163
+ # Removing the previous conversation from chat
164
+ chatbot.pop(-1)
165
+ # Setting up a flag to capture a retry
166
+ RETRY_FLAG = True
167
+ # Getting last message from user
168
+ user_input = history[-1][0]
169
+ # Removing bot response from the history
170
+ history.pop(-1)
171
+
172
+ yield from predict(
173
+ RETRY_FLAG, # type: ignore
174
+ user_input,
175
+ chatbot,
176
+ max_length,
177
+ top_p,
178
+ temperature,
179
+ history,
180
+ past_key_values,
181
+ )
182
+
183
+
184
+ with gr.Blocks(title="ChatGLM2-6B-int4", theme=gr.themes.Soft(text_size="sm")) as demo:
185
+ # gr.HTML("""<h1 align="center">ChatGLM2-6B-int4</h1>""")
186
+ gr.HTML(
187
+ """<center><a href="https://huggingface.co/spaces/mikeee/chatglm2-6b-4bit?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>It's beyond Fitness,模型由[帛凡]基于ChatGLM-6b进行微调后,在健康(全科)、心理等领域达至少60分的专业水准,而且中文总结能力超越了GPT3.5各版本。</center>"""
188
+ """<center><免责声明:本应用仅为模型能力演示,无任何商业行为,部署资源为huggingface官方免费提供,任何通过此项目产生的知识仅用于学术参考,作者和网站均不承担任何责任 。</center>"""
189
+ """<h1 align="center">帛凡 Fitness AI 演示</h1>"""
190
+ )
191
+
192
+ with gr.Accordion("🎈 Info", open=False):
193
+ _ = f"""
194
+ ## {model_name}
195
+
196
+ ChatGLM-6B 是开源中英双语对话模型,本次训练基于ChatGLM-6B 的第一代版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上开展训练。
197
+
198
+ 本项目经过多位网友实测,中文总结能力超越了GPT3.5各版本,健康咨询水平优于其它同量级模型,且经优化目前可以支持无限context,远大于4k、8K、16K......,可能是任何个人和中小企业首选模型。
199
+
200
+ *首先,用40万条高质量数据进行强化训练,以提高模型的基础能力;
201
+
202
+ *第二,使用30万条人类反馈数据,构建一个表达方式规范优雅的语言模式(RM模型);
203
+
204
+ *第三,在保留SFT阶段三分之一训练数据的同时,增加了30万条fitness数据,叠加RM模型,对ChatGLM-6B进行强化训练。
205
+
206
+ 通过训练我们对模型有了更深刻的认知,LLM在一直在进化,好的方法和数据可以挖掘出模型的更大潜能。
207
+ 训练中特别强化了中英文学术论文的翻译和总结,可以成为普通用户和科研人员的得力助手。
208
+
209
+ 免责声明:本应用仅为模型能力演示,无任何商业行为,部署资源为huggingface官方免费提供,任何通过此项目产生的知识仅用于学术参考,作者和网站均不承担任何责任 。
210
+
211
+ The T4 GPU is sponsored by a community GPU grant from Huggingface. Thanks a lot!
212
+
213
+ [模型下载地址](https://huggingface.co/fb700/chatglm-fitness-RLHF)
214
+
215
+
216
+ """
217
+ gr.Markdown(dedent(_))
218
  chatbot = gr.Chatbot()
219
  with gr.Row():
220
  with gr.Column(scale=4):
221
  with gr.Column(scale=12):
222
+ user_input = gr.Textbox(
223
+ show_label=False,
224
+ placeholder="Input...",
225
+ ).style(container=False)
226
+ RETRY_FLAG = gr.Checkbox(value=False, visible=False)
227
  with gr.Column(min_width=32, scale=1):
228
+ with gr.Row():
229
+ submitBtn = gr.Button("Submit", variant="primary")
230
+ deleteBtn = gr.Button("删除最后一条对话", variant="secondary")
231
+ retryBtn = gr.Button("重新生成Regenerate", variant="secondary")
232
  with gr.Column(scale=1):
233
  emptyBtn = gr.Button("Clear History")
234
+ max_length = gr.Slider(
235
+ 0,
236
+ 32768,
237
+ value=8192,
238
+ step=1.0,
239
+ label="Maximum length",
240
+ interactive=True,
241
+ )
242
+ top_p = gr.Slider(
243
+ 0, 1, value=0.85, step=0.01, label="Top P", interactive=True
244
+ )
245
+ temperature = gr.Slider(
246
+ 0.01, 1, value=0.95, step=0.01, label="Temperature", interactive=True
247
+ )
248
 
249
  history = gr.State([])
250
+ past_key_values = gr.State(None)
251
 
252
+ user_input.submit(
253
+ predict,
254
+ [
255
+ RETRY_FLAG,
256
+ user_input,
257
+ chatbot,
258
+ max_length,
259
+ top_p,
260
+ temperature,
261
+ history,
262
+ past_key_values,
263
+ ],
264
+ [chatbot, history, past_key_values],
265
+ show_progress="full",
266
+ )
267
+ submitBtn.click(
268
+ predict,
269
+ [
270
+ RETRY_FLAG,
271
+ user_input,
272
+ chatbot,
273
+ max_length,
274
+ top_p,
275
+ temperature,
276
+ history,
277
+ past_key_values,
278
+ ],
279
+ [chatbot, history, past_key_values],
280
+ show_progress="full",
281
+ api_name="predict",
282
+ )
283
  submitBtn.click(reset_user_input, [], [user_input])
284
 
285
+ emptyBtn.click(
286
+ reset_state, outputs=[chatbot, history, past_key_values], show_progress="full"
287
+ )
288
+
289
+ retryBtn.click(
290
+ retry_last_answer,
291
+ inputs=[
292
+ user_input,
293
+ chatbot,
294
+ max_length,
295
+ top_p,
296
+ temperature,
297
+ history,
298
+ past_key_values,
299
+ ],
300
+ # outputs = [chatbot, history, last_user_message, user_message]
301
+ outputs=[chatbot, history, past_key_values],
302
+ )
303
+ deleteBtn.click(delete_last_turn, [chatbot, history], [chatbot, history])
304
+
305
+ with gr.Accordion("Example inputs", open=True):
306
+ 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. """
307
+ etext1 = """云南大学(Yunnan University),简称云大(YNU),位于云南省昆明市,是教育部与云南省“以部为主、部省合建”的全国重点大学,国家“双一流”建设高校 [31] 、211工程、一省一校、中西部高校基础能力建设工程,云南省重点支持的国家一流大学建设高校,“111计划”、卓越法律人才教育培养计划、卓越工程师教育培养计划、国家建设高水平大学公派研究生项目、中国政府奖学金来华留学生接收院校、全国深化创新创业教育改革示范高校,为中西部“一省一校”国家重点建设大学(Z14)联盟、南亚东南亚大学联盟牵头单位。 [1]
308
+ 云南大学始建于1922年,时为私立东陆大学。1930年,改为省立东陆大学。1934年更名为省立云南大学。1938年改为国立云南大学。1946年,《不列颠百科全书》将云南大学列为中国15所在世界最具影响的大学之一。1950年定名为云南大学。1958年,云南大学由中央高教部划归云南省管理。1978年,云南大学被国务院确定为88所全国重点大学之一。1996年首批列入国家“211工程”重点建设大学。1999年,云南政法高等专科学校并入云南大学。 [2] [23]
309
+ 截至2023年6月,学校有呈贡、东陆两校区,占地面积4367亩,校舍建筑面积133余万平方米,馆藏书400万余册;设有28个学院,本科专业84个;有博士后科研流动站14个,22个一级学科博士学位授权点,1个专业博士学位授权,42个一级学科硕士学位授权,26个专业硕士学位授权;教职员工3000余人,全日制本科生近17000人,全日制硕士研究生近12000人,博士研究生1500余人。 """
310
+ examples = gr.Examples(
311
+ examples=[
312
+ ["熬夜对身体有什么危害? "],
313
+ ["新冠肺炎怎么预防"],
314
+ ["系统性红斑狼疮的危害和治疗方法是什么?"],
315
+ [
316
+ "我经常感觉郁闷,而且控制不住情绪,经常对周围的人喊叫,怎么办?"
317
+ ],
318
+ ["太阳为什么会发热? "],
319
+ ["指南针是怎么工作的?"],
320
+ ["在野外怎么辨别方向?"],
321
+ [
322
+ "世界最长的桥是那一座?"
323
+ ],
324
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born? "],
325
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born? Think step by step."],
326
+ ["Explain the plot of Cinderella in a sentence."],
327
+ [
328
+ "How long does it take to become proficient in French, and what are the best methods for retaining information?"
329
+ ],
330
+ ["What are some common mistakes to avoid when writing code?"],
331
+ ["Build a prompt to generate a beautiful portrait of a horse"],
332
+ ["Suggest four metaphors to describe the benefits of AI"],
333
+ ["Write a pop song about leaving home for the sandy beaches."],
334
+ ["Write a summary demonstrating my ability to tame lions"],
335
+ ["鲁迅和周树人什么关系"],
336
+ ["从前有一头牛,这头牛后面有什么?"],
337
+ ["正无穷大加一大于正无穷大吗?"],
338
+ ["正无穷大加正无穷大大于正无穷大吗?"],
339
+ ["-2的平方根等于什么"],
340
+ ["树上有5只鸟,猎人开枪打死了一只。树上还有几只鸟?Think step by step."],
341
+ ["树上有11只鸟,猎人开枪打死了一只。树上还有几只鸟?提示:需考虑鸟可能受惊吓飞走。Think step by step."],
342
+ ["鲁迅和周树人什么关系 用英文回答"],
343
+ ["以红楼梦的行文风格写一张委婉的请假条。不少于320字。"],
344
+ [f"{etext1} 总结这篇文章的主要内容和文章结构"],
345
+ [f"{etext} 翻成中文,列出3个版本"],
346
+ [f"{etext} \n 翻成中文,保留原意,但使用文学性的语言。不要写解释。列出3个版本"],
347
+ ["js 判断一个数是不是质数"],
348
+ ["js 实现python 的 range(10)"],
349
+ ["js 实现python 的 [*(range(10)]"],
350
+ ["假定 1 + 2 = 4, 试求 7 + 8,Think step by step." ],
351
+ ["2023年云南大学成立100周年,它是哪一年成立的?" ],
352
+ ["Erkläre die Handlung von Cinderella in einem Satz."],
353
+ ["Erkläre die Handlung von Cinderella in einem Satz. Auf Deutsch"],
354
+ ],
355
+ inputs=[user_input],
356
+ examples_per_page=50,
357
+ )
358
+
359
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
360
+ input_text = gr.Text()
361
+ tr_btn = gr.Button("Go", variant="primary")
362
+ out_text = gr.Text()
363
+ tr_btn.click(
364
+ trans_api,
365
+ [input_text, max_length, top_p, temperature],
366
+ out_text,
367
+ # show_progress="full",
368
+ api_name="tr",
369
+ )
370
+ _ = """
371
+ input_text.submit(
372
+ trans_api,
373
+ [input_text, max_length, top_p, temperature],
374
+ out_text,
375
+ show_progress="full",
376
+ api_name="tr1",
377
+ )
378
+ # """
379
+
380
+ # demo.queue().launch(share=False, inbrowser=True)
381
+ # demo.queue().launch(share=True, inbrowser=True, debug=True)
382
+
383
+ # concurrency_count > 1 requires more memory, max_size: queue size
384
+ # T4 medium: 30GB, model size: ~4G concurrency_count = 6
385
+ # leave one for api access
386
+ # reduce to 5 if OOM occurs to often
387
 
388
+ demo.queue(concurrency_count=6, max_size=30).launch(debug=True)
requirements.txt CHANGED
@@ -1,11 +1,9 @@
1
  protobuf
2
- transformers==4.27.1
3
  cpm_kernels
4
- torch>=1.10
5
- gradio
6
  mdtex2html
7
  sentencepiece
8
  accelerate
9
- peft
10
- streamlit
11
- streamlit_chat
 
1
  protobuf
2
+ transformers==4.30.2
3
  cpm_kernels
4
+ torch>=2.0
5
+ # gradio
6
  mdtex2html
7
  sentencepiece
8
  accelerate
9
+ loguru