tradequant commited on
Commit
7b3da90
1 Parent(s): 083abee

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +8 -4
  2. app.py +378 -0
  3. flake8.txt +21 -0
  4. gitattributes.txt +35 -0
  5. gitignore.txt +1 -0
  6. requirements.txt +9 -0
README.md CHANGED
@@ -1,10 +1,14 @@
1
  ---
2
- title: Chat
3
- emoji: 📉
4
- colorFrom: blue
5
  colorTo: blue
6
- sdk: docker
 
 
7
  pinned: false
 
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: chatglm2 6b int4
3
+ emoji: 🌖
4
+ colorFrom: purple
5
  colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.35.2
8
+ app_file: app.py
9
  pinned: false
10
+ license: mit
11
+ duplicated_from: mikeee/chatglm2-6b-4bit
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Credit to https://github.com/THUDM/ChatGLM2-6B/blob/main/web_demo.py
2
+ while mistakes are mine
3
+ """
4
+ # 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
5
+ # import gradio as gr
6
+
7
+ # model_name = "models/THUDM/chatglm2-6b-int4"
8
+ # gr.load(model_name).lauch()
9
+
10
+ # %%writefile demo-4bit.py
11
+
12
+ import os
13
+ import time
14
+ from textwrap import dedent
15
+
16
+ import gradio as gr
17
+ import mdtex2html
18
+ import torch
19
+ from loguru import logger
20
+ from transformers import AutoModel, AutoTokenizer
21
+
22
+ # fix timezone in Linux
23
+ os.environ["TZ"] = "Asia/Shanghai"
24
+ try:
25
+ time.tzset() # type: ignore # pylint: disable=no-member
26
+ except Exception:
27
+ # Windows
28
+ logger.warning("Windows, cant run time.tzset()")
29
+
30
+ # model_name = "THUDM/chatglm2-6b"
31
+ model_name = "THUDM/chatglm2-6b-int4"
32
+
33
+ RETRY_FLAG = False
34
+
35
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
36
+
37
+ # model = AutoModel.from_pretrained(model_name, trust_remote_code=True).cuda()
38
+
39
+ # 4/8 bit
40
+ # model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).quantize(4).cuda()
41
+
42
+ # has_cuda = torch.cuda.is_available()
43
+ has_cuda = False # force cpu
44
+
45
+ if has_cuda:
46
+ model = (
47
+ AutoModel.from_pretrained(model_name, trust_remote_code=True).cuda().half()
48
+ ) # 3.92G
49
+ else:
50
+ model = AutoModel.from_pretrained(
51
+ model_name, trust_remote_code=True
52
+ ).float() # .float() .half().float()
53
+
54
+ model = model.eval()
55
+
56
+ _ = """Override Chatbot.postprocess"""
57
+
58
+
59
+ def postprocess(self, y):
60
+ if y is None:
61
+ return []
62
+ for i, (message, response) in enumerate(y):
63
+ y[i] = (
64
+ None if message is None else mdtex2html.convert((message)),
65
+ None if response is None else mdtex2html.convert(response),
66
+ )
67
+ return y
68
+
69
+
70
+ gr.Chatbot.postprocess = postprocess
71
+
72
+
73
+ def parse_text(text):
74
+ """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
75
+ lines = text.split("\n")
76
+ lines = [line for line in lines if line != ""]
77
+ count = 0
78
+ for i, line in enumerate(lines):
79
+ if "```" in line:
80
+ count += 1
81
+ items = line.split("`")
82
+ if count % 2 == 1:
83
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
84
+ else:
85
+ lines[i] = "<br></code></pre>"
86
+ else:
87
+ if i > 0:
88
+ if count % 2 == 1:
89
+ line = line.replace("`", r"\`")
90
+ line = line.replace("<", "&lt;")
91
+ line = line.replace(">", "&gt;")
92
+ line = line.replace(" ", "&nbsp;")
93
+ line = line.replace("*", "&ast;")
94
+ line = line.replace("_", "&lowbar;")
95
+ line = line.replace("-", "&#45;")
96
+ line = line.replace(".", "&#46;")
97
+ line = line.replace("!", "&#33;")
98
+ line = line.replace("(", "&#40;")
99
+ line = line.replace(")", "&#41;")
100
+ line = line.replace("$", "&#36;")
101
+ lines[i] = "<br>" + line
102
+ text = "".join(lines)
103
+ return text
104
+
105
+
106
+ def predict(
107
+ RETRY_FLAG, input, chatbot, max_length, top_p, temperature, history, past_key_values
108
+ ):
109
+ try:
110
+ chatbot.append((parse_text(input), ""))
111
+ except Exception as exc:
112
+ logger.error(exc)
113
+ logger.debug(f"{chatbot=}")
114
+ _ = """
115
+ if chatbot:
116
+ chatbot[-1] = (parse_text(input), str(exc))
117
+ yield chatbot, history, past_key_values
118
+ # """
119
+ yield chatbot, history, past_key_values
120
+
121
+ for response, history, past_key_values in model.stream_chat(
122
+ tokenizer,
123
+ input,
124
+ history,
125
+ past_key_values=past_key_values,
126
+ return_past_key_values=True,
127
+ max_length=max_length,
128
+ top_p=top_p,
129
+ temperature=temperature,
130
+ ):
131
+ chatbot[-1] = (parse_text(input), parse_text(response))
132
+
133
+ yield chatbot, history, past_key_values
134
+
135
+
136
+ def trans_api(input, max_length=4096, top_p=0.8, temperature=0.2):
137
+ if max_length < 10:
138
+ max_length = 4096
139
+ if top_p < 0.1 or top_p > 1:
140
+ top_p = 0.85
141
+ if temperature <= 0 or temperature > 1:
142
+ temperature = 0.01
143
+ try:
144
+ res, _ = model.chat(
145
+ tokenizer,
146
+ input,
147
+ history=[],
148
+ past_key_values=None,
149
+ max_length=max_length,
150
+ top_p=top_p,
151
+ temperature=temperature,
152
+ )
153
+ # logger.debug(f"{res=} \n{_=}")
154
+ except Exception as exc:
155
+ logger.error(f"{exc=}")
156
+ res = str(exc)
157
+
158
+ return res
159
+
160
+
161
+ def reset_user_input():
162
+ return gr.update(value="")
163
+
164
+
165
+ def reset_state():
166
+ return [], [], None
167
+
168
+
169
+ # Delete last turn
170
+ def delete_last_turn(chat, history):
171
+ if chat and history:
172
+ chat.pop(-1)
173
+ history.pop(-1)
174
+ return chat, history
175
+
176
+
177
+ # Regenerate response
178
+ def retry_last_answer(
179
+ user_input, chatbot, max_length, top_p, temperature, history, past_key_values
180
+ ):
181
+ if chatbot and history:
182
+ # Removing the previous conversation from chat
183
+ chatbot.pop(-1)
184
+ # Setting up a flag to capture a retry
185
+ RETRY_FLAG = True
186
+ # Getting last message from user
187
+ user_input = history[-1][0]
188
+ # Removing bot response from the history
189
+ history.pop(-1)
190
+
191
+ yield from predict(
192
+ RETRY_FLAG, # type: ignore
193
+ user_input,
194
+ chatbot,
195
+ max_length,
196
+ top_p,
197
+ temperature,
198
+ history,
199
+ past_key_values,
200
+ )
201
+
202
+
203
+ with gr.Blocks(title="ChatGLM2-6B-int4", theme=gr.themes.Soft(text_size="sm")) as demo:
204
+ # gr.HTML("""<h1 align="center">ChatGLM2-6B-int4</h1>""")
205
+ gr.HTML(
206
+ """<center><a href="https://huggingface.co/spaces/mikeee/chatglm2-6b-4bit?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>To avoid the queue and for faster inference Duplicate this Space and upgrade to GPU</center>"""
207
+ )
208
+
209
+ with gr.Accordion("🎈 Info", open=False):
210
+ _ = f"""
211
+ ## {model_name}
212
+
213
+ Try to refresh the browser and try again when occasionally an error occurs.
214
+
215
+ With a GPU, a query takes from a few seconds to a few tens of seconds, dependent on the number of words/characters
216
+ the question and responses contain. The quality of the responses varies quite a bit it seems. Even the same
217
+ question with the same parameters, asked at different times, can result in quite different responses.
218
+
219
+ * Low temperature: responses will be more deterministic and focused; High temperature: responses more creative.
220
+
221
+ * Suggested temperatures -- translation: up to 0.3; chatting: > 0.4
222
+
223
+ * Top P controls dynamic vocabulary selection based on context.
224
+
225
+ For a table of example values for different scenarios, refer to [this](https://community.openai.com/t/cheat-sheet-mastering-temperature-and-top-p-in-chatgpt-api-a-few-tips-and-tricks-on-controlling-the-creativity-deterministic-output-of-prompt-responses/172683)
226
+
227
+ If the instance is not on a GPU (T4), it will be very slow. You can try to run the colab notebook [chatglm2-6b-4bit colab notebook](https://colab.research.google.com/drive/1WkF7kOjVCcBBatDHjaGkuJHnPdMWNtbW?usp=sharing) for a spin.
228
+
229
+ The T4 GPU is sponsored by a community GPU grant from Huggingface. Thanks a lot!
230
+ """
231
+ gr.Markdown(dedent(_))
232
+ chatbot = gr.Chatbot()
233
+ with gr.Row():
234
+ with gr.Column(scale=4):
235
+ with gr.Column(scale=12):
236
+ user_input = gr.Textbox(
237
+ show_label=False,
238
+ placeholder="Input...",
239
+ ).style(container=False)
240
+ RETRY_FLAG = gr.Checkbox(value=False, visible=False)
241
+ with gr.Column(min_width=32, scale=1):
242
+ with gr.Row():
243
+ submitBtn = gr.Button("Submit", variant="primary")
244
+ deleteBtn = gr.Button("Delete last turn", variant="secondary")
245
+ retryBtn = gr.Button("Regenerate", variant="secondary")
246
+ with gr.Column(scale=1):
247
+ emptyBtn = gr.Button("Clear History")
248
+ max_length = gr.Slider(
249
+ 0,
250
+ 32768,
251
+ value=8192,
252
+ step=1.0,
253
+ label="Maximum length",
254
+ interactive=True,
255
+ )
256
+ top_p = gr.Slider(
257
+ 0, 1, value=0.85, step=0.01, label="Top P", interactive=True
258
+ )
259
+ temperature = gr.Slider(
260
+ 0.01, 1, value=0.95, step=0.01, label="Temperature", interactive=True
261
+ )
262
+
263
+ history = gr.State([])
264
+ past_key_values = gr.State(None)
265
+
266
+ user_input.submit(
267
+ predict,
268
+ [
269
+ RETRY_FLAG,
270
+ user_input,
271
+ chatbot,
272
+ max_length,
273
+ top_p,
274
+ temperature,
275
+ history,
276
+ past_key_values,
277
+ ],
278
+ [chatbot, history, past_key_values],
279
+ show_progress="full",
280
+ )
281
+ submitBtn.click(
282
+ predict,
283
+ [
284
+ RETRY_FLAG,
285
+ user_input,
286
+ chatbot,
287
+ max_length,
288
+ top_p,
289
+ temperature,
290
+ history,
291
+ past_key_values,
292
+ ],
293
+ [chatbot, history, past_key_values],
294
+ show_progress="full",
295
+ api_name="predict",
296
+ )
297
+ submitBtn.click(reset_user_input, [], [user_input])
298
+
299
+ emptyBtn.click(
300
+ reset_state, outputs=[chatbot, history, past_key_values], show_progress="full"
301
+ )
302
+
303
+ retryBtn.click(
304
+ retry_last_answer,
305
+ inputs=[
306
+ user_input,
307
+ chatbot,
308
+ max_length,
309
+ top_p,
310
+ temperature,
311
+ history,
312
+ past_key_values,
313
+ ],
314
+ # outputs = [chatbot, history, last_user_message, user_message]
315
+ outputs=[chatbot, history, past_key_values],
316
+ )
317
+ deleteBtn.click(delete_last_turn, [chatbot, history], [chatbot, history])
318
+
319
+ with gr.Accordion("Example inputs", open=True):
320
+ 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. """
321
+ examples = gr.Examples(
322
+ examples=[
323
+ ["Explain the plot of Cinderella in a sentence."],
324
+ [
325
+ "How long does it take to become proficient in French, and what are the best methods for retaining information?"
326
+ ],
327
+ ["What are some common mistakes to avoid when writing code?"],
328
+ ["Build a prompt to generate a beautiful portrait of a horse"],
329
+ ["Suggest four metaphors to describe the benefits of AI"],
330
+ ["Write a pop song about leaving home for the sandy beaches."],
331
+ ["Write a summary demonstrating my ability to tame lions"],
332
+ ["鲁迅和周树人什么关系"],
333
+ ["从前有一头牛,这头牛后面有什么?"],
334
+ ["正无穷大加一大于正无穷大吗?"],
335
+ ["正无穷大加正无穷大大于正无穷大吗?"],
336
+ ["-2的平方根等于什么"],
337
+ ["树上有5只鸟,猎人开枪打死了一只。树上还有几只鸟?"],
338
+ ["树上有11只鸟,猎人开枪打死了一只。树上还有几只鸟?提示:需考虑鸟可能受惊吓飞走。"],
339
+ ["鲁迅和周树人什么关系 用英文回答"],
340
+ ["以红楼梦的行文风格写一张委婉的请假条。不少于320字。"],
341
+ [f"{etext} 翻成中文,列出3个版本"],
342
+ [f"{etext} \n 翻成中文,保留原意,但使用文学性的语言。不要写解释。列出3个版本"],
343
+ ["js 判断一个数是不是质数"],
344
+ ["js 实现python 的 range(10)"],
345
+ ["js 实现python 的 [*(range(10)]"],
346
+ ["假定 1 + 2 = 4, 试求 7 + 8"],
347
+ ["Erkläre die Handlung von Cinderella in einem Satz."],
348
+ ["Erkläre die Handlung von Cinderella in einem Satz. Auf Deutsch"],
349
+ ],
350
+ inputs=[user_input],
351
+ examples_per_page=30,
352
+ )
353
+
354
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
355
+ input_text = gr.Text()
356
+ tr_btn = gr.Button("Go", variant="primary")
357
+ out_text = gr.Text()
358
+ tr_btn.click(
359
+ trans_api,
360
+ [input_text, max_length, top_p, temperature],
361
+ out_text,
362
+ # show_progress="full",
363
+ api_name="tr",
364
+ )
365
+ _ = """
366
+ input_text.submit(
367
+ trans_api,
368
+ [input_text, max_length, top_p, temperature],
369
+ out_text,
370
+ show_progress="full",
371
+ api_name="tr1",
372
+ )
373
+ # """
374
+
375
+ # demo.queue().launch(share=False, inbrowser=True)
376
+ # demo.queue().launch(share=True, inbrowser=True, debug=True)
377
+
378
+ demo.queue().launch(debug=True)
flake8.txt 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
gitattributes.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
gitignore.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ call-activate.bat
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