‘xiarui’ commited on
Commit
25d0227
·
1 Parent(s): 84a77a4
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. models/chat_gpt/__pycache__/chat_gpt.cpython-38.pyc +0 -0
  2. models/chat_gpt/__pycache__/config_private.cpython-38.pyc +0 -0
  3. models/chat_gpt/__pycache__/toolbox.cpython-38.pyc +0 -0
  4. models/chat_gpt/chat_gpt.py +159 -0
  5. models/chat_gpt/config.py +35 -0
  6. models/chat_gpt/config_private.py +35 -0
  7. models/chat_gpt/toolbox.py +44 -0
  8. models/chatglm/LICENSE +201 -0
  9. models/chatglm/MODEL_LICENSE +33 -0
  10. models/chatglm/PROJECT.md +28 -0
  11. models/chatglm/README.md +324 -0
  12. models/chatglm/README_en.md +275 -0
  13. models/chatglm/chatglm-6b-int4/.gitattributes +34 -0
  14. models/chatglm/chatglm-6b-int4/LICENSE +201 -0
  15. models/chatglm/chatglm-6b-int4/MODEL_LICENSE +33 -0
  16. models/chatglm/chatglm-6b-int4/README.md +81 -0
  17. models/chatglm/chatglm-6b-int4/config.json +30 -0
  18. models/chatglm/chatglm-6b-int4/configuration_chatglm.py +105 -0
  19. models/chatglm/chatglm-6b-int4/ice_text.model +3 -0
  20. models/chatglm/chatglm-6b-int4/modeling_chatglm.py +1472 -0
  21. models/chatglm/chatglm-6b-int4/pytorch_model.bin +3 -0
  22. models/chatglm/chatglm-6b-int4/quantization.py +515 -0
  23. models/chatglm/chatglm-6b-int4/quantization_kernels.c +34 -0
  24. models/chatglm/chatglm-6b-int4/quantization_kernels.so +0 -0
  25. models/chatglm/chatglm-6b-int4/quantization_kernels_parallel.c +50 -0
  26. models/chatglm/chatglm-6b-int4/quantization_kernels_parallel.so +0 -0
  27. models/chatglm/chatglm-6b-int4/tokenization_chatglm.py +430 -0
  28. models/chatglm/chatglm-6b-int4/tokenizer_config.json +20 -0
  29. models/chatglm/requirements.txt +8 -0
  30. models/chatglm/test.py +72 -0
  31. models/chatglm/utils.py +54 -0
  32. models/chinese_chat_llama/chinese-chat-llama-7b-int4/.gitattributes +34 -0
  33. models/chinese_chat_llama/chinese-chat-llama-7b-int4/README.md +1 -0
  34. models/chinese_chat_llama/chinese-chat-llama-7b-int4/chatllama-ggml-q4_0.bin +3 -0
  35. models/chinese_chat_llama/chinese-chat-llama-7b-int4/tokenizer.model +3 -0
  36. models/gpt4free/.github/FUNDING.yml +13 -0
  37. models/gpt4free/.gitignore +16 -0
  38. models/gpt4free/Docker/Dockerfile +12 -0
  39. models/gpt4free/LICENSE +674 -0
  40. models/gpt4free/README.md +148 -0
  41. models/gpt4free/gui/README.md +9 -0
  42. models/gpt4free/gui/streamlit_app.py +48 -0
  43. models/gpt4free/phind/README.md +34 -0
  44. models/gpt4free/phind/__init__.py +293 -0
  45. models/gpt4free/quora/README.md +68 -0
  46. models/gpt4free/quora/__init__.py +487 -0
  47. models/gpt4free/quora/api.py +578 -0
  48. models/gpt4free/quora/cookies.txt +30 -0
  49. models/gpt4free/quora/graphql/AddHumanMessageMutation.graphql +52 -0
  50. models/gpt4free/quora/graphql/AddMessageBreakMutation.graphql +17 -0
models/chat_gpt/__pycache__/chat_gpt.cpython-38.pyc ADDED
Binary file (4.57 kB). View file
 
models/chat_gpt/__pycache__/config_private.cpython-38.pyc ADDED
Binary file (532 Bytes). View file
 
models/chat_gpt/__pycache__/toolbox.cpython-38.pyc ADDED
Binary file (1.78 kB). View file
 
models/chat_gpt/chat_gpt.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import json
3
+ import logging
4
+ import traceback
5
+
6
+ import requests
7
+
8
+ # config_private.py放自己的秘密如API和代理网址
9
+ # 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件
10
+ from models.chat_gpt.toolbox import get_conf
11
+
12
+ proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY = \
13
+ get_conf('proxies', 'API_URL', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY')
14
+
15
+ timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings.' + \
16
+ '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。 \n'
17
+
18
+
19
+ class chat_gpt:
20
+ def __init__(self, name):
21
+ self.name = name
22
+
23
+ def get_full_error(self, chunk, stream_response):
24
+ """
25
+ 获取完整的从Openai返回的报错
26
+ """
27
+ while True:
28
+ try:
29
+ chunk += next(stream_response)
30
+ except:
31
+ break
32
+ return chunk
33
+
34
+ def predict(self, inputs, top_p=1, temperature=0.8, chatbot=[], history=[], system_prompt='',
35
+ stream=True):
36
+ """
37
+ 发送至chatGPT,流式获取输出。
38
+ 用于基础的对话功能。
39
+ inputs 是本次问询的输入
40
+ top_p, temperature是chatGPT的内部调优参数
41
+ history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)
42
+ chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容
43
+ """
44
+
45
+ if stream:
46
+ raw_input = inputs
47
+ logging.info(f'[raw_input] {raw_input}')
48
+ chatbot.append((inputs, ""))
49
+ yield chatbot, history, "等待响应"
50
+
51
+ headers, payload = self.generate_payload(inputs, top_p, temperature, history, system_prompt, stream)
52
+ history.append(inputs); history.append(" ")
53
+
54
+ retry = 0
55
+ while True:
56
+ try:
57
+ # make a POST request to the API endpoint, stream=True
58
+ response = requests.post(API_URL, headers=headers, proxies=proxies,
59
+ json=payload, stream=True, timeout=TIMEOUT_SECONDS);break
60
+ except:
61
+ retry += 1
62
+ retry_msg = f"Trying, 正在重试 ({retry}/{MAX_RETRY}) ……" if MAX_RETRY > 0 else ""
63
+ error_message_with_color = "\033[0;33;40m" + timeout_bot_msg + retry_msg + '\n' + "\033[0m"
64
+ chatbot[-1] = ((chatbot[-1][0], error_message_with_color))
65
+ yield chatbot, history, "请求超时" + retry_msg
66
+ if retry > MAX_RETRY: raise TimeoutError
67
+
68
+ gpt_replying_buffer = ""
69
+
70
+ is_head_of_the_stream = True
71
+ if stream:
72
+ stream_response = response.iter_lines()
73
+ while True:
74
+ chunk = next(stream_response)
75
+ # print(chunk.decode()[6:])
76
+ if is_head_of_the_stream:
77
+ # 数据流的第一帧不携带content
78
+ is_head_of_the_stream = False; continue
79
+
80
+ if chunk:
81
+ try:
82
+ if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
83
+ # 判定为数据流的结束,gpt_replying_buffer也写完了
84
+ logging.info(f'[response] {gpt_replying_buffer}')
85
+ break
86
+ # 处理数据流的主体
87
+ chunkjson = json.loads(chunk.decode()[6:])
88
+ status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"
89
+ # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出
90
+ gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]
91
+ history[-1] = gpt_replying_buffer
92
+ chatbot[-1] = (history[-2], history[-1])
93
+ yield chatbot, history, status_text
94
+
95
+ except Exception as e:
96
+ # traceback.print_exc()
97
+ yield chatbot, history, "Json解析不合常规"
98
+ chunk = self.get_full_error(chunk, stream_response)
99
+ error_msg = chunk.decode()
100
+ if "reduce the length" in error_msg:
101
+ chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")
102
+ history = []
103
+ elif "Incorrect API key" in error_msg:
104
+ chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")
105
+ else:
106
+ from toolbox import regular_txt_to_markdown
107
+ tb_str = regular_txt_to_markdown(traceback.format_exc())
108
+ chatbot[-1] = (chatbot[-1][0], f"[Local Message] Json Error \n\n {tb_str} \n\n {regular_txt_to_markdown(chunk.decode()[4:])}")
109
+ yield chatbot, history, "Json解析不合常规" + error_msg
110
+ return
111
+
112
+ def generate_payload(self, inputs, top_p, temperature, history, system_prompt, stream):
113
+ """
114
+ 整合所有信息,选择LLM模型,生成http请求,为发送请求做准备
115
+ """
116
+ headers = {
117
+ "Content-Type": "application/json",
118
+ "Authorization": f"Bearer {API_KEY}"
119
+ }
120
+
121
+ conversation_cnt = len(history) // 2
122
+
123
+ messages = [{"role": "system", "content": system_prompt}]
124
+ if conversation_cnt:
125
+ for index in range(0, 2*conversation_cnt, 2):
126
+ what_i_have_asked = {}
127
+ what_i_have_asked["role"] = "user"
128
+ what_i_have_asked["content"] = history[index]
129
+ what_gpt_answer = {}
130
+ what_gpt_answer["role"] = "assistant"
131
+ what_gpt_answer["content"] = history[index+1]
132
+ if what_i_have_asked["content"] != "":
133
+ if what_gpt_answer["content"] == "": continue
134
+ if what_gpt_answer["content"] == timeout_bot_msg: continue
135
+ messages.append(what_i_have_asked)
136
+ messages.append(what_gpt_answer)
137
+ else:
138
+ messages[-1]['content'] = what_gpt_answer['content']
139
+
140
+ what_i_ask_now = {}
141
+ what_i_ask_now["role"] = "user"
142
+ what_i_ask_now["content"] = inputs
143
+ messages.append(what_i_ask_now)
144
+
145
+ payload = {
146
+ "model": self.name,
147
+ "messages": messages,
148
+ "temperature": temperature, # 1.0,
149
+ "top_p": top_p, # 1.0,
150
+ "n": 1,
151
+ "stream": stream,
152
+ "presence_penalty": 0,
153
+ "frequency_penalty": 0,
154
+ }
155
+
156
+ #print(f" {LLM_MODEL} : {conversation_cnt} : {inputs}")
157
+ return headers, payload
158
+
159
+
models/chat_gpt/config.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # API_KEY = "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" 此key无效
2
+ API_KEY = "sk-此处填API密钥"
3
+ API_URL = "https://api.openai.com/v1/chat/completions"
4
+
5
+ # 改为True应用代理
6
+ USE_PROXY = False
7
+ if USE_PROXY:
8
+
9
+ # 填写格式是 [协议]:// [地址] :[端口] ,
10
+ # 例如 "socks5h://localhost:11284"
11
+ # [协议] 常见协议无非socks5h/http,例如 v2*** 和 s** 的默认本地协议是socks5h,cl**h 的默认本地协议是http
12
+ # [地址] 懂的都懂,不懂就填localhost或者127.0.0.1肯定错不了(localhost意思是代理软件安装在本机上)
13
+ # [端口] 在代理软件的设置里,不同的代理软件界面不一样,但端口号都应该在最显眼的位置上
14
+
15
+ # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
16
+ proxies = {"http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", }
17
+ print('网络代理状态:运行。')
18
+ else:
19
+ proxies = None
20
+ print('网络代理状态:未配置。无代理状态下很可能无法访问。')
21
+
22
+ # 发送请求到OpenAI后,等待多久判定为超时
23
+ TIMEOUT_SECONDS = 25
24
+
25
+ # 网页的端口, -1代表随机端口
26
+ WEB_PORT = -1
27
+
28
+ # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
29
+ MAX_RETRY = 2
30
+
31
+ # 设置并行使用的线程数
32
+ CONCURRENT_COUNT = 100
33
+
34
+ # 设置用户名和密码
35
+ AUTHENTICATION = [] # [("username", "password"), ("username2", "password2"), ...]
models/chat_gpt/config_private.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # API_KEY = "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" 此key无效
2
+ API_KEY = "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"
3
+ API_URL = "https://api.openai.com/v1/chat/completions"
4
+
5
+ # 改为True应用代理
6
+ USE_PROXY = True
7
+ if USE_PROXY:
8
+
9
+ # 填写格式是 [协议]:// [地址] :[端口] ,
10
+ # 例如 "socks5h://localhost:11284"
11
+ # [协议] 常见协议无非socks5h/http,例如 v2*** 和 s** 的默认本地协议是socks5h,cl**h 的默认本地协议是http
12
+ # [地址] 懂的都懂,不懂就填localhost或者127.0.0.1肯定错不了(localhost意思是代理软件安装在本机上)
13
+ # [端口] 在代理软件的设置里,不同的代理软件界面不一样,但端口号都应该在最显眼的位置上
14
+
15
+ # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
16
+ proxies = {"http": "socks5h://localhost:7890", "https": "socks5h://localhost:7890", }
17
+ # print('网络代理状态:运行。')
18
+ else:
19
+ proxies = None
20
+ print('No Network Proxy! May not work.')
21
+
22
+ # 发送请求到OpenAI后,等待多久判定为超时
23
+ TIMEOUT_SECONDS = 50
24
+
25
+ # 网页的端口, -1代表随机端口
26
+ WEB_PORT = -1
27
+
28
+ # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
29
+ MAX_RETRY = 2
30
+
31
+ # 设置并行使用的线程数
32
+ CONCURRENT_COUNT = 100
33
+
34
+ # 设置用户名和密码
35
+ AUTHENTICATION = [] # [("username", "password"), ("username2", "password2"), ...]
models/chat_gpt/toolbox.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ def get_conf(*args):
4
+ # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
5
+ res = []
6
+ for arg in args:
7
+ try: r = getattr(importlib.import_module('models.chat_gpt.config_private'), arg)
8
+ except: r = getattr(importlib.import_module('models.chat_gpt.config'), arg)
9
+ res.append(r)
10
+ # 在读取API_KEY时,检查一下是不是忘了改config
11
+ if arg == 'API_KEY' and len(r) != 51:
12
+ assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \
13
+ "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)"
14
+ return res
15
+
16
+
17
+ def write_results_to_file(history, file_name=None):
18
+ """
19
+ 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。
20
+ """
21
+ import os, time
22
+ if file_name is None:
23
+ # file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'
24
+ file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'
25
+ os.makedirs('./gpt_log/', exist_ok=True)
26
+ with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f:
27
+ f.write('# chat_gpt 分析报告\n')
28
+ for i, content in enumerate(history):
29
+ if i%2==0: f.write('## ')
30
+ f.write(content)
31
+ f.write('\n\n')
32
+ res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}')
33
+ print(res)
34
+ return res
35
+
36
+
37
+ def regular_txt_to_markdown(text):
38
+ """
39
+ 将普通文本转换为Markdown格式的文本。
40
+ """
41
+ text = text.replace('\n', '\n\n')
42
+ text = text.replace('\n\n\n', '\n\n')
43
+ text = text.replace('\n\n\n', '\n\n')
44
+ return text
models/chatglm/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Zhengxiao Du
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
models/chatglm/MODEL_LICENSE ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The ChatGLM-6B License
2
+
3
+ 1. Definitions
4
+
5
+ “Licensor” means the ChatGLM-6B Model Team that distributes its Software.
6
+
7
+ “Software” means the ChatGLM-6B model parameters made available under this license.
8
+
9
+ 2. License Grant
10
+
11
+ Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ 3. Restriction
16
+
17
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
18
+
19
+ You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
20
+
21
+ 4. Disclaimer
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ 5. Limitation of Liability
26
+
27
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
28
+
29
+ 6. Dispute Resolution
30
+
31
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
32
+
33
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
models/chatglm/PROJECT.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 友情链接
2
+
3
+ 对 ChatGLM 进行加速或者重新实现的开源项目:
4
+ * [SwissArmyTransformer](https://github.com/THUDM/SwissArmyTransformer): 一个Transformer统一编程框架,ChatGLM-6B已经在SAT中进行实现并可以进行P-tuning微调。
5
+ * [ChatGLM-MNN](https://github.com/wangzhaode/ChatGLM-MNN): 一个基于 MNN 的 ChatGLM-6B C++ 推理实现,支持根据显存大小自动分配计算任务给 GPU 和 CPU
6
+ * [JittorLLMs](https://github.com/Jittor/JittorLLMs):最低3G显存或者没有显卡都可运行 ChatGLM-6B FP16, 支持Linux、windows、Mac部署
7
+
8
+
9
+
10
+ 基于或使用了 ChatGLM-6B 的开源项目:
11
+ * [chatgpt_academic](https://github.com/binary-husky/chatgpt_academic): 支持ChatGLM-6B的学术写作与编程工具箱,具有模块化和多线程调用LLM的特点,可并行调用多种LLM。
12
+ * [闻达](https://github.com/l15y/wenda):大型语言模型调用平台,基于 ChatGLM-6B 实现了类 ChatPDF 功能
13
+ * [glm-bot](https://github.com/initialencounter/glm-bot):将ChatGLM接入Koishi可在各大聊天平台上调用ChatGLM
14
+ * [Chinese-LangChain](https://github.com/yanqiangmiffy/Chinese-LangChain):中文langchain项目,基于ChatGLM-6b+langchain实现本地化知识库检索与智能答案生成,增加web search功能、知识库选择功能和支持知识增量更新
15
+ * [bibliothecarius](https://github.com/coderabbit214/bibliothecarius):快速构建服务以集成您的本地数据和AI模型,支持ChatGLM等本地化模型接入。
16
+ * [langchain-ChatGLM](https://github.com/imClumsyPanda/langchain-ChatGLM):基于本地知识的 ChatGLM 应用,基于LangChain
17
+ * [ChatGLM-web](https://github.com/NCZkevin/chatglm-web):基于FastAPI和Vue3搭建的ChatGLM演示网站(支持chatglm流式输出、前端调整模型参数、上下文选择、保存图片、知识库问答等功能)
18
+ * [ChatGLM-6B-Engineering](https://github.com/LemonQu-GIT/ChatGLM-6B-Engineering):基于 ChatGLM-6B 后期调教,网络爬虫及 [Stable Diffusion](https://github.com/AUTOMATIC1111/stable-diffusion-webui) 实现的网络搜索及图片生成
19
+
20
+ 对 ChatGLM-6B 进行微调的开源项目:
21
+ * [InstructGLM](https://github.com/yanqiangmiffy/InstructGLM):基于ChatGLM-6B进行指令学习,汇总开源中英文指令数据,基于Lora进行指令数据微调,开放了Alpaca、Belle微调后的Lora权重,修复web_demo重复问题
22
+ * [ChatGLM-Finetuning](https://github.com/liucongg/ChatGLM-Finetuning):基于ChatGLM-6B模型,进行下游具体任务微调,涉及Freeze、Lora、P-tuning等,并进行实验效果对比。
23
+ * [ChatGLM-Tuning](https://github.com/mymusise/ChatGLM-Tuning): 基于 LoRA 对 ChatGLM-6B 进行微调。类似的项目还包括 [Humanable ChatGLM/GPT Fine-tuning | ChatGLM 微调](https://github.com/hscspring/hcgf)
24
+
25
+ 针对 ChatGLM-6B 的教程/文档:
26
+ * [Windows部署文档](https://github.com/ZhangErling/ChatGLM-6B/blob/main/deployment_windows.md)
27
+ * [ChatGLM-6B 的部署与微调教程 @ModelWhale平台](https://www.heywhale.com/mw/project/6436d82948f7da1fee2be59e)
28
+ * [搭建深度学习docker容器以运行 ChatGLM-6B - Luck_zy](https://www.luckzym.com/tags/ChatGLM-6B/)
models/chatglm/README.md ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatGLM-6B
2
+
3
+ <p align="center">
4
+ 🌐 <a href="https://chatglm.cn/blog" target="_blank">Blog</a> • 🤗 <a href="https://huggingface.co/THUDM/chatglm-6b" target="_blank">HF Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
5
+ </p>
6
+ <p align="center">
7
+ 👋 加入我们的 <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1th2q5u69-7tURzFuOPanmuHy9hsZnKA" target="_blank">Slack</a> 和 <a href="resources/WECHAT.md" target="_blank">WeChat</a>
8
+ </p>
9
+
10
+ ## 介绍
11
+
12
+ ChatGLM-6B 是一个开源的、支持中英双语的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。
13
+ ChatGLM-6B 使用了和 ChatGPT 相似的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答,更多信息请参考我们的[博客](https://chatglm.cn/blog)。
14
+
15
+ 为了方便下游开发者针对自己的应用场景定制模型,我们同时实现了基于 [P-Tuning v2](https://github.com/THUDM/P-tuning-v2) 的高效参数微调方法 [(使用指南)](ptuning/README.md) ,INT4 量化级别下最低只需 7GB 显存即可启动微调。
16
+
17
+ 不过,由于 ChatGLM-6B 的规模较小,目前已知其具有相当多的[**局限性**](#局限性),如事实性/数学逻辑错误,可能生成有害/有偏见内容,较弱的上下文能力,自我认知混乱,以及对英文指示生成与中文指示完全矛盾的内容。请大家在使用前了解这些问题,以免产生误解。更大的基于 1300 亿参数 [GLM-130B](https://github.com/THUDM/GLM-130B) 的 ChatGLM 正在内测开发中。
18
+
19
+ **想要提升 ChatGLM-6B 在你的实际场景中的表现?请参与 [ChatGLM-6B 提升计划](improve/README.md)**
20
+
21
+ *Read this in [English](README_en.md).*
22
+
23
+ ## 友情链接
24
+ 对 ChatGLM 进行加速的开源项目:
25
+ * [ChatGLM-MNN](https://github.com/wangzhaode/ChatGLM-MNN): 一个基于 MNN 的 ChatGLM-6B C++ 推理实现,支持根据显存大小自动分配计算任务给 GPU 和 CPU
26
+ * [JittorLLMs](https://github.com/Jittor/JittorLLMs):最低3G显存或者没有显卡都可运行 ChatGLM-6B FP16, 支持Linux、windows、Mac部署
27
+
28
+ 基于或使用了 ChatGLM-6B 的开源项目:
29
+ * [闻达](https://github.com/l15y/wenda):大型语言模型调用平台,基于 ChatGLM-6B 实现了类 ChatPDF 功能
30
+ * [chatgpt_academic](https://github.com/binary-husky/chatgpt_academic): 支持ChatGLM-6B的学术写作与编程工具箱,具有模块化和多线程调用LLM的特点,可并行调用多种LLM。
31
+ * [glm-bot](https://github.com/initialencounter/glm-bot):将ChatGLM接入Koishi可在各大聊天平台上调用ChatGLM
32
+
33
+ 更多开源项目参见 [PROJECT.md](PROJECT.md)
34
+
35
+ 如果你有其他好的项目/教程的话,欢迎参照上述格式添加到 README 中并提出 [Pull Request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork)。
36
+
37
+ ## 使用方式
38
+
39
+ ### 硬件需求
40
+
41
+ | **量化等级** | **最低 GPU 显存**(推理) | **最低 GPU 显存**(高效参数微调) |
42
+ | -------------- | ------------------------- | --------------------------------- |
43
+ | FP16(无量化) | 13 GB | 14 GB |
44
+ | INT8 | 8 GB | 9 GB |
45
+ | INT4 | 6 GB | 7 GB |
46
+ ### 环境安装
47
+
48
+ 使用 pip 安装依赖:`pip install -r requirements.txt`,其中 `transformers` 库版本推荐为 `4.27.1`,但理论上不低于 `4.23.1` 即可。
49
+
50
+ 此外,如果需要在 cpu 上运行量化后的模型,还需要安装 `gcc` 与 `openmp`。多数 Linux 发行版默认已安装。对于 Windows ,可在安装 [TDM-GCC](https://jmeubank.github.io/tdm-gcc/) 时勾选 `openmp`。 Windows 测试环境 `gcc` 版本为 `TDM-GCC 10.3.0`, Linux 为 `gcc 11.3.0`。
51
+
52
+ ### 代码调用
53
+
54
+ 可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
55
+
56
+ ```python
57
+ >>> from transformers import AutoTokenizer, AutoModel
58
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
59
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
60
+ >>> model = model.eval()
61
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
62
+ >>> print(response)
63
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
64
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
65
+ >>> print(response)
66
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
67
+
68
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
69
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
70
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
71
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
72
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
73
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
74
+
75
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
76
+ ```
77
+ ### 从本地加载模型
78
+ 以上代码会由 `transformers` 自动下载模型实现和参数。完整的模型实现可以在 [Hugging Face Hub](https://huggingface.co/THUDM/chatglm-6b)。如果你的网络环境较差,下载模型参数可能会花费较长时间甚至失败。此时可以先将模型下载到本地,然后从本地加载。
79
+
80
+ 从 Hugging Face Hub 下载模型需要先[安装Git LFS](https://docs.github.com/zh/repositories/working-with-files/managing-large-files/installing-git-large-file-storage),然后运行
81
+ ```Shell
82
+ git clone https://huggingface.co/THUDM/chatglm-6b
83
+ ```
84
+
85
+ 如果你从 Hugging Face Hub 上下载 checkpoint 的速度较慢,可以只下载模型实现
86
+ ```Shell
87
+ GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b
88
+ ```
89
+ 然后从[这里](https://cloud.tsinghua.edu.cn/d/fb9f16d6dc8f482596c2/)手动下载模型参数文件,并将下载的文件替换到本地的 `chatglm-6b` 目录下。
90
+
91
+ 将模型下载到本地之后,将以上代码中的 `THUDM/chatglm-6b` 替换为你本地的 `chatglm-6b` 文件夹的路径,即可从本地加载模型。
92
+
93
+ ## Demo & API
94
+
95
+ 我们提供了一个基于 [Gradio](https://gradio.app) 的网页版 Demo 和一个命令行 Demo。使用时首先需要下载本仓库:
96
+
97
+ ```shell
98
+ git clone https://github.com/THUDM/ChatGLM-6B
99
+ cd ChatGLM-6B
100
+ ```
101
+
102
+ #### 网页版 Demo
103
+
104
+ ![web-demo](resources/web-demo.gif)
105
+
106
+ 首先安装 Gradio:`pip install gradio`,然后运行仓库中的 [web_demo.py](web_demo.py):
107
+
108
+ ```shell
109
+ python web_demo.py
110
+ ```
111
+
112
+ 程序会运行一个 Web Server,并输出地址。在浏览器中打开输出的地址即可使用。最新版 Demo 实现了打字机效果,速度体验大大提升。注意,由于国内 Gradio 的网络访问较为缓慢,启用 `demo.queue().launch(share=True, inbrowser=True)` 时所有网络会经过 Gradio 服务器转发,导致打字机体验大幅下降,现在默认启动方式已经改为 `share=False`,如有需要公网访问的需求,可以重新修改为 `share=True` 启动。
113
+
114
+ 感谢 [@AdamBear](https://github.com/AdamBear) 实现了基于 Streamlit 的网页版 Demo,运行方式见[#117](https://github.com/THUDM/ChatGLM-6B/pull/117).
115
+
116
+ #### 命令行 Demo
117
+
118
+ ![cli-demo](resources/cli-demo.png)
119
+
120
+ 运行仓库中 [cli_demo.py](cli_demo.py):
121
+
122
+ ```shell
123
+ python cli_demo.py
124
+ ```
125
+
126
+ 程序会在命令行中进行交互式的对话,在命令行中输入指示并回车即可生成回复,输入 `clear` 可以清空对话历史,输入 `stop` 终止程序。
127
+
128
+ ### API部署
129
+ 首先需要安装额外的依赖 `pip install fastapi uvicorn`,然后运行仓库中的 [api.py](api.py):
130
+ ```shell
131
+ python api.py
132
+ ```
133
+ 默认部署在本地的 8000 端口,通过 POST 方法进行调用
134
+ ```shell
135
+ curl -X POST "http://127.0.0.1:8000" \
136
+ -H 'Content-Type: application/json' \
137
+ -d '{"prompt": "你好", "history": []}'
138
+ ```
139
+ 得到的返回值为
140
+ ```shell
141
+ {
142
+ "response":"你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。",
143
+ "history":[["你好","你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。"]],
144
+ "status":200,
145
+ "time":"2023-03-23 21:38:40"
146
+ }
147
+ ```
148
+
149
+ ## 低成本部署
150
+ ### 模型量化
151
+ 默认情况下,模型以 FP16 精度加载,运行上述代码需要大概 13GB 显存。如果你的 GPU 显存有限,可以尝试以量化方式加载模型,使用方法如下:
152
+
153
+ ```python
154
+ # 按需修改,目前只支持 4/8 bit 量化
155
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).quantize(8).half().cuda()
156
+ ```
157
+
158
+ 进行 2 至 3 轮对话后,8-bit 量化下 GPU 显存占用约为 10GB,4-bit 量化下仅需 6GB 占用。随着对话轮数的增多,对应消耗显存也随之增长,由于采用了相对位置编码,理论上 ChatGLM-6B 支持无限长的 context-length,但总长度超过 2048(训练长度)后性能会逐渐下降。
159
+
160
+ 模型量化会带来一定的性能损失,经过测试,ChatGLM-6B 在 4-bit 量化下仍然能够进行自然流畅的生成。使用 [GPT-Q](https://arxiv.org/abs/2210.17323) 等量化方案可以进一步压缩量化精度/提升相同量化精度下的模型性能,欢迎大家提出对应的 Pull Request。
161
+
162
+ 量化过程需要在内存中首先加载 FP16 格式的模型,消耗大概 13GB 的内存。如果你的内存不足的话,可以直接加载量化后的模型,INT4 量化后的模型仅需大概 5.2GB 的内存:
163
+ ```python
164
+ # INT8 量化的模型将"THUDM/chatglm-6b-int4"改为"THUDM/chatglm-6b-int8"
165
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda()
166
+ ```
167
+ 量化模型的参数文件也可以从[这里](https://cloud.tsinghua.edu.cn/d/674208019e314311ab5c/)手动下载。
168
+
169
+ ### CPU 部署
170
+ 如果你没有 GPU 硬件的话,也可以在 CPU 上进行推理,但是推理速度会更慢。使用方法如下(需要大概 32GB 内存)
171
+ ```python
172
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float()
173
+ ```
174
+
175
+ 如果你的内存不足,可以直接加载量化后的模型:
176
+ ```python
177
+ # INT8 量化的模型将"THUDM/chatglm-6b-int4"改为"THUDM/chatglm-6b-int8"
178
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4",trust_remote_code=True).float()
179
+ ```
180
+
181
+ 如果遇到了报错 `Could not find module 'nvcuda.dll'` 或者 `RuntimeError: Unknown platform: darwin` (MacOS) ,请[从本地加载模型](README.md#从本地加载模型)
182
+
183
+ ### Mac 上的 GPU 加速
184
+ 对于搭载了Apple Silicon的Mac(以及MacBook),可以使用 MPS 后端来在 GPU 上运行 ChatGLM-6B。需要参考 Apple 的 [官方说明](https://developer.apple.com/metal/pytorch) 安装 PyTorch-Nightly。
185
+
186
+ 目前在 MacOS 上只支持[从本地加载模型](README.md#从本地加载模型)。将代码中的模型加载改为从本地加载,并使用 mps 后端
187
+ ```python
188
+ model = AutoModel.from_pretrained("your local path", trust_remote_code=True).half().to('mps')
189
+ ```
190
+ 即可使用在 Mac 上使用 GPU 加速模型推理。
191
+
192
+ ### 多卡部署
193
+ 如果你有多张 GPU,但是每张 GPU 的显存大小都不足以容纳完整的模型,那么可以将模型切分在多张GPU上。首先安装 accelerate: `pip install accelerate`,然后通过如下方法加载模型:
194
+ ```python
195
+ from utils import load_model_on_gpus
196
+ model = load_model_on_gpus("THUDM/chatglm-6b", num_gpus=2)
197
+ ```
198
+ 即可将模型部署到两张 GPU 上进行推理。你可以将 `num_gpus` 改为你希望使用的 GPU 数。默认是均匀切分的,你也可以传入 `device_map` 参数来自己指定。
199
+
200
+ ## 高效参数微调
201
+ 基于 [P-tuning v2](https://github.com/THUDM/P-tuning-v2) 的高效参数微调。具体使用方法详见 [ptuning/README.md](ptuning/README.md)。
202
+
203
+ ## 更新信息
204
+ **[2023/04/16]** 增加 INT8 量化后的模型 [ChatGLM-6B-INT8](https://huggingface.co/THUDM/chatglm-6b-int8)。增加多卡部署(感谢 [@Cherrysaber](https://github.com/Cherrysaber))。
205
+
206
+ **[2023/04/06]** 优化web demo的界面(感谢 [@tuteng0915](https://github.com/tuteng0915))。移除embedding中的image token以减小显存占用(需要更新模型文件`pytorch_model-00001-of-00008.bin`和`pytorch_model-00008-of-00008.bin`,感谢 [@silverriver](https://github.com/silverriver) 提出的想法)。去掉了对 `icetk` 的依赖(需要更新模型文件`ice_text.model`)。
207
+
208
+ **[2023/03/31]** 增加基于 [P-Tuning-v2](https://github.com/THUDM/P-tuning-v2) 的高效参数微调实现,INT4 量化级别下最低只需 7GB 显存即可进行模型微调。详见[高效参数微调方法](ptuning/README.md)。
209
+
210
+ **[2023/03/23]** 增加 API 部署(感谢 [@LemonQu-GIT](https://github.com/LemonQu-GIT))。增加 Embedding 量化模型 [ChatGLM-6B-INT4-QE](https://huggingface.co/THUDM/chatglm-6b-int4-qe)。增加配备 Apple Silicon 芯片的 Mac 上 GPU 加速的支持。
211
+
212
+ **[2023/03/19]** 增加流式输出接口 `stream_chat`,已更新到网页版和命令行 Demo。修复输出中的中文标点。增加 INT4 量化后的模型 [ChatGLM-6B-INT4](https://huggingface.co/THUDM/chatglm-6b-int4)
213
+
214
+ ## ChatGLM-6B 示例
215
+
216
+ 以下是一些使用 `web_demo.py` 得到的示例截图。更多 ChatGLM-6B 的可能,等待你来探索发现!
217
+
218
+ <details><summary><b>自我认知</b></summary>
219
+
220
+ ![](examples/self-introduction.png)
221
+
222
+ </details>
223
+
224
+ <details><summary><b>提纲写作</b></summary>
225
+
226
+ ![](examples/blog-outline.png)
227
+
228
+ </details>
229
+
230
+ <details><summary><b>文案写作</b></summary>
231
+
232
+ ![](examples/ad-writing-2.png)
233
+
234
+ ![](examples/comments-writing.png)
235
+
236
+ </details>
237
+
238
+ <details><summary><b>邮件写作助手</b></summary>
239
+
240
+ ![](examples/email-writing-1.png)
241
+
242
+ ![](examples/email-writing-2.png)
243
+
244
+ </details>
245
+
246
+ <details><summary><b>信息抽取</b></summary>
247
+
248
+ ![](examples/information-extraction.png)
249
+
250
+ </details>
251
+
252
+ <details><summary><b>角色扮演</b></summary>
253
+
254
+ ![](examples/role-play.png)
255
+
256
+ </details>
257
+
258
+ <details><summary><b>评论比较</b></summary>
259
+
260
+ ![](examples/sport.png)
261
+
262
+ </details>
263
+
264
+ <details><summary><b>旅游向导</b></summary>
265
+
266
+ ![](examples/tour-guide.png)
267
+
268
+ </details>
269
+
270
+ ## 局限性
271
+
272
+ 由于 ChatGLM-6B 的小规模,其能力仍然有许多局限性。以下是我们目前发现的一些问题:
273
+
274
+ - 模型容量较小:6B 的小容量,决定了其相对较弱的模型记忆和语言能力。在面对许多事实性知识任务时,ChatGLM-6B 可能会生成不正确的信息;它也不擅长逻辑类问题(如数学、编程)的解答。
275
+ <details><summary><b>点击查看例子</b></summary>
276
+
277
+ ![](limitations/factual_error.png)
278
+
279
+ ![](limitations/math_error.png)
280
+
281
+ </details>
282
+
283
+ - 产生有害说明或有偏见的内容:ChatGLM-6B 只是一个初步与人类意图对齐的语言模型,可能会生成有害、有偏见的内容。(内容可能具有冒犯性,此处不展示)
284
+
285
+ - 英文能力不足:ChatGLM-6B 训练时使用的指示/回答大部分都是中文的,仅有极小一部分英文内容。因此,如果输入英文指示,回复的质量远不如中文,甚至与中文指示下的内容矛盾,并且出现中英夹杂的情况。
286
+
287
+ - 易被误导,对话能力较弱:ChatGLM-6B 对话能力还比较弱,而且 “自我认知” 存在问题,并很容易被误导并产生错误的言论。例如当前版本的模型在被误导的情况下,会在自我认知上发生偏差。
288
+ <details><summary><b>点击查看例子</b></summary>
289
+
290
+ ![](limitations/self-confusion_google.jpg)
291
+
292
+ ![](limitations/self-confusion_openai.jpg)
293
+
294
+ ![](limitations/self-confusion_tencent.jpg)
295
+
296
+ </details>
297
+
298
+ ## 协议
299
+
300
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
301
+
302
+ ## 引用
303
+
304
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文
305
+
306
+ ```
307
+ @inproceedings{
308
+ zeng2023glm-130b,
309
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
310
+ author={Aohan Zeng and Xiao Liu and Zhengxiao Du and Zihan Wang and Hanyu Lai and Ming Ding and Zhuoyi Yang and Yifan Xu and Wendi Zheng and Xiao Xia and Weng Lam Tam and Zixuan Ma and Yufei Xue and Jidong Zhai and Wenguang Chen and Zhiyuan Liu and Peng Zhang and Yuxiao Dong and Jie Tang},
311
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
312
+ year={2023},
313
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
314
+ }
315
+ ```
316
+ ```
317
+ @inproceedings{du2022glm,
318
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
319
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
320
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
321
+ pages={320--335},
322
+ year={2022}
323
+ }
324
+ ```
models/chatglm/README_en.md ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatGLM-6B
2
+
3
+
4
+ <p align="center">
5
+ 🌐 <a href="https://chatglm.cn/blog" target="_blank">Blog</a> • 🤗 <a href="https://huggingface.co/THUDM/chatglm-6b" target="_blank">HF Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
6
+ </p>
7
+ <p align="center">
8
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1th2q5u69-7tURzFuOPanmuHy9hsZnKA" target="_blank">Slack</a> and <a href="resources/WECHAT.md" target="_blank">WeChat</a>
9
+ </p>
10
+
11
+ ## Introduction
12
+
13
+ ChatGLM-6B is an open bilingual language model based on [General Language Model (GLM)](https://github.com/THUDM/GLM) framework, with 6.2 billion parameters. With the quantization technique, users can deploy locally on consumer-grade graphics cards (only 6GB of GPU memory is required at the INT4 quantization level).
14
+
15
+ ChatGLM-6B uses technology similar to ChatGPT, optimized for Chinese QA and dialogue. The model is trained for about 1T tokens of Chinese and English corpus, supplemented by supervised fine-tuning, feedback bootstrap, and reinforcement learning wit human feedback. With only about 6.2 billion parameters, the model is able to generate answers that are in line with human preference.
16
+
17
+ Try the [online demo](https://huggingface.co/spaces/ysharma/ChatGLM-6b_Gradio_Streaming) on Huggingface Spaces.
18
+
19
+ ## Update
20
+ **[2023/03/31]** Added a parameter-efficient tuning implementation based on [P-Tuning-v2](https://github.com/THUDM/P-tuning-v2). The minimum INT4 quantization level only needs 7GB GPU memory is enough for model tuning. See [Parameter-efficient tuning method](ptuning/README.md) for details.
21
+
22
+ **[2023/03/23]** Add API deployment, thanks to [@LemonQu-GIT](https://github.com/LemonQu-GIT). Add embedding-quantized model [ChatGLM-6B-INT4-QE](https://huggingface.co/THUDM/chatglm-6b-int4-qe). Add support for GPU inference on Mac with Apple Silicon.
23
+
24
+ **[2023/03/19]** Add streaming output function `stream_chat`, already applied in web and CLI demo. Fix Chinese punctuations in output. Add quantized model [ChatGLM-6B-INT4](https://huggingface.co/THUDM/chatglm-6b-int4).
25
+
26
+ ## Projects
27
+ The following are some open source projects developed based on this repository:
28
+ * [ChatGLM-MNN](https://github.com/wangzhaode/ChatGLM-MNN): An [MNN](https://github.com/alibaba/MNN)-based implementation of ChatGLM-6B C++ inference, which supports automatic allocation of computing tasks to GPU and CPU according to the size of GPU memory
29
+ * [ChatGLM-Tuning](https://github.com/mymusise/ChatGLM-Tuning): Fine-tuning ChatGLM-6B based on LoRA
30
+
31
+ If you have other good projects, please refer to the above format to add to README and propose [PR](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork).
32
+
33
+ ## Getting Started
34
+
35
+ ### Hardware Requirements
36
+
37
+ | **Quantization Level** | **GPU Memory** |
38
+ |------------------------|----------------|
39
+ | FP16(no quantization) | 13 GB |
40
+ | INT8 | 10 GB |
41
+ | INT4 | 6 GB |
42
+
43
+ ### Environment Setup
44
+
45
+ Install the requirements with pip: `pip install -r requirements.txt`. `transformers` library version is recommended to be `4.27.1`, but theoretically any version no lower than `4.23.1` is acceptable.
46
+
47
+ In addition, if you need to run the quantified model on the CPU, you also need to install `gcc` and `openmp`. Most Linux distributions are installed by default. For Windows, you can check `openmp` when installing [TDM-GCC](https://jmeubank.github.io/tdm-gcc/). On Windows testing environment, the `gcc` version is `TDM-GCC 10.3.0`, and on Linux is `gcc 11.3.0`.
48
+
49
+ ### Usage
50
+
51
+ Generate dialogue with the following code
52
+
53
+ ```python
54
+ >>> from transformers import AutoTokenizer, AutoModel
55
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
56
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
57
+ >>> model = model.eval()
58
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
59
+ >>> print(response)
60
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
61
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
62
+ >>> print(response)
63
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
64
+
65
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
66
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
67
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
68
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
69
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
70
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
71
+
72
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
73
+ ```
74
+
75
+ The full model implementation is on [HuggingFace Hub](https://huggingface.co/THUDM/chatglm-6b).
76
+
77
+ ### Demo
78
+
79
+ We provide a Web demo based on [Gradio](https://gradio.app) and a command line demo in the repo. First clone our repo with:
80
+
81
+ ```shell
82
+ git clone https://github.com/THUDM/ChatGLM-6B
83
+ cd ChatGLM-6B
84
+ ```
85
+
86
+ #### Web Demo
87
+
88
+ ![web-demo](resources/web-demo.png)
89
+
90
+ Install Gradio `pip install gradio`,and run [web_demo.py](web_demo.py):
91
+
92
+ ```shell
93
+ python web_demo.py
94
+ ```
95
+
96
+ The program runs a web server and outputs the URL. Open the URL in the browser to use the web demo.
97
+
98
+ #### CLI Demo
99
+
100
+ ![cli-demo](resources/cli-demo.png)
101
+
102
+ Run [cli_demo.py](cli_demo.py) in the repo:
103
+
104
+ ```shell
105
+ python cli_demo.py
106
+ ```
107
+
108
+ The command runs an interactive program in the shell. Type your instruction in the shell and hit enter to generate the response. Type `clear` to clear the dialogue history and `stop` to terminate the program.
109
+
110
+ ## API Deployment
111
+ First install the additional dependency `pip install fastapi uvicorn`. The run [api.py](api.py) in the repo.
112
+ ```shell
113
+ python api.py
114
+ ```
115
+ By default the api runs at the`8000`port of the local machine. You can call the API via
116
+ ```shell
117
+ curl -X POST "http://127.0.0.1:8000" \
118
+ -H 'Content-Type: application/json' \
119
+ -d '{"prompt": "你好", "history": []}'
120
+ ```
121
+ The returned value is
122
+ ```shell
123
+ {
124
+ "response":"你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。",
125
+ "history":[["你好","你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。"]],
126
+ "status":200,
127
+ "time":"2023-03-23 21:38:40"
128
+ }
129
+ ```
130
+
131
+ ## Deployment
132
+
133
+ ### Quantization
134
+
135
+ By default, the model parameters are loaded with FP16 precision, which require about 13GB of GPU memory. It your GPU memory is limited, you can try to load the model parameters with quantization:
136
+
137
+ ```python
138
+ # Change according to your hardware. Only support 4/8 bit quantization now.
139
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().quantize(4).cuda()
140
+ ```
141
+
142
+ After 2 to 3 rounds of dialogue, the GPU memory usage is about 10GB under 8-bit quantization, and only 6GB under 4-bit quantization. As the number of dialogue rounds increases, the corresponding GPU memory consumption also increases. Due to the use of relative position encoding, ChatGLM-6B theoretically supports an infinitely long context-length, but the performance will gradually decline after the total length exceeds 2048 (training length).
143
+
144
+ Model quantization brings a certain performance decline. After testing, ChatGLM-6B can still perform natural and smooth generation under 4-bit quantization. using [GPT-Q](https://arxiv.org/abs/2210.17323) etc. The quantization scheme can further compress the quantization accuracy/improve the model performance under the same quantization accuracy. You are welcome to submit corresponding Pull Requests.
145
+
146
+ **[2023/03/19]** The quantization costs about 13GB of CPU memory to load the FP16 model. If your CPU memory is limited, you can directly load the quantized model, which costs only 5.2GB CPU memory:
147
+ ```python
148
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda()
149
+ ```
150
+
151
+ ### CPU Deployment
152
+
153
+ If your computer is not equipped with GPU, you can also conduct inference on CPU, but the inference speed is slow (and taking about 32GB of memory):
154
+
155
+ ```python
156
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float()
157
+ ```
158
+
159
+ **[2023/03/19]** If your CPU memory is limited, you can directly load the quantized model:
160
+ ```python
161
+ model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).float()
162
+ ```
163
+
164
+ If your encounter the error `Could not find module 'nvcuda.dll'` or `RuntimeError: Unknown platform: darwin`(MacOS), please refer to this [Issue](https://github.com/THUDM/ChatGLM-6B/issues/6#issuecomment-1470060041).
165
+
166
+ ### GPU Inference on Mac
167
+ For Macs (and MacBooks) with Apple Silicon, it is possible to use the MPS backend to run ChatGLM-6B on the GPU. First, you need to refer to Apple's [official instructions](https://developer.apple.com/metal/pytorch) to install PyTorch-Nightly. Then clone the model repository locally (you need to [install Git LFS](https://docs.github.com/zh/repositories/working-with-files/managing-large-files/installing-git-large-file-storage))
168
+ ```shell
169
+ git lfs install
170
+ git clone https://huggingface.co/THUDM/chatglm-6b
171
+ ```
172
+ Change the code to load the model from your local path, and use the mps backend:
173
+ ```python
174
+ model = AutoModel.from_pretrained("your local path", trust_remote_code=True).half().to('mps')
175
+ ```
176
+ Then you can use GPU-accelerated model inference on Mac.
177
+
178
+ ### Multi-GPU Deployment
179
+ If you have multiple GPUs, but the memory size of each GPU is not sufficient to accommodate the entire model, you can split the model across multiple GPUs.
180
+
181
+ First, install accelerate: `pip install accelerate`, and then load the model using the following method:
182
+ ```python
183
+ from utils import load_model_on_gpus
184
+ model = load_model_on_gpus("THUDM/chatglm-6b", num_gpus=2)
185
+ ```
186
+
187
+ This will deploy the model onto two GPUs for inference. You can change `num_gpus` to the number of GPUs you want to use. By default, the model is split evenly, but you can also specify the `device_map` parameter to customize the splitting.
188
+
189
+ ## Parameter-efficient Tuning
190
+ Parameter-efficient tuning based on [P-tuning v2](https://github.com/THUDM/P-tuning-v2). See [ptuning/README.md](ptuning/README.md) for details on how to use it.
191
+
192
+ ## ChatGLM-6B Examples
193
+
194
+ The following are some Chinese examples with `web_demo.py`. Welcome to explore more possibility with ChatGLM-6B.
195
+
196
+ <details><summary><b>Self Cognition</b></summary>
197
+
198
+ ![](examples/self-introduction.png)
199
+
200
+ </details>
201
+
202
+ <details><summary><b>Outline</b></summary>
203
+
204
+ ![](examples/blog-outline.png)
205
+
206
+ </details>
207
+
208
+ <details><summary><b>Ad</b></summary>
209
+
210
+ ![](examples/ad-writing-2.png)
211
+
212
+ ![](examples/comments-writing.png)
213
+
214
+ </details>
215
+
216
+ <details><summary><b>Email</b></summary>
217
+
218
+ ![](examples/email-writing-1.png)
219
+
220
+ ![](examples/email-writing-2.png)
221
+
222
+ </details>
223
+
224
+ <details><summary><b>Information Extraction</b></summary>
225
+
226
+ ![](examples/information-extraction.png)
227
+
228
+ </details>
229
+
230
+ <details><summary><b>Role Play</b></summary>
231
+
232
+ ![](examples/role-play.png)
233
+
234
+ </details>
235
+
236
+ <details><summary><b>Comparison</b></summary>
237
+
238
+ ![](examples/sport.png)
239
+
240
+ </details>
241
+
242
+ <details><summary><b>Travel Guide</b></summary>
243
+
244
+ ![](examples/tour-guide.png)
245
+
246
+ </details>
247
+
248
+ ## License
249
+
250
+ This repository is licensed under the [Apache-2.0 License](LICENSE). The use of ChatGLM-6B model weights is subject to the [Model License](MODEL_LICENSE)。
251
+
252
+ ## Citation
253
+
254
+ If you find our work useful, please consider citing the following papers:
255
+
256
+ ```
257
+ @inproceedings{
258
+ zeng2023glm-130b,
259
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
260
+ author={Aohan Zeng and Xiao Liu and Zhengxiao Du and Zihan Wang and Hanyu Lai and Ming Ding and Zhuoyi Yang and Yifan Xu and Wendi Zheng and Xiao Xia and Weng Lam Tam and Zixuan Ma and Yufei Xue and Jidong Zhai and Wenguang Chen and Zhiyuan Liu and Peng Zhang and Yuxiao Dong and Jie Tang},
261
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
262
+ year={2023},
263
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
264
+ }
265
+ ```
266
+
267
+ ```
268
+ @inproceedings{du2022glm,
269
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
270
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
271
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
272
+ pages={320--335},
273
+ year={2022}
274
+ }
275
+ ```
models/chatglm/chatglm-6b-int4/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/chatglm/chatglm-6b-int4/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Zhengxiao Du
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
models/chatglm/chatglm-6b-int4/MODEL_LICENSE ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The GLM-130B License
2
+
3
+ 1. Definitions
4
+
5
+ “Licensor” means the GLM-130B Model Team that distributes its Software.
6
+
7
+ “Software” means the GLM-130B model parameters made available under this license.
8
+
9
+ 2. License Grant
10
+
11
+ Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ 3. Restriction
16
+
17
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
18
+
19
+ You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
20
+
21
+ 4. Disclaimer
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ 5. Limitation of Liability
26
+
27
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
28
+
29
+ 6. Dispute Resolution
30
+
31
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
32
+
33
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
models/chatglm/chatglm-6b-int4/README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM-6B-INT4
11
+ <p align="center">
12
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1th2q5u69-7tURzFuOPanmuHy9hsZnKA" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
13
+ </p>
14
+
15
+ ## 介绍
16
+ ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
17
+
18
+ ChatGLM-6B-INT4 是 ChatGLM-6B 量化后的模型权重。具体的,ChatGLM-6B-INT4 对 ChatGLM-6B 中的 28 个 GLM Block 进行了 INT4 量化,没有对 Embedding 和 LM Head 进行量化。量化后的模型理论上 6G 显存(使用 CPU 即内存)即可推理,具有在嵌入式设备(如树莓派)上运行的可能。
19
+
20
+ 在 CPU 上运行时,会根据硬件自动编译 CPU Kernel ,请确保已安装 GCC 和 OpenMP (Linux一般已安装,对于Windows则需手动安装),以获得最佳并行计算能力。
21
+
22
+ ## 软件依赖
23
+
24
+ ```shell
25
+ pip install protobuf transformers==4.27.1 cpm_kernels
26
+ ```
27
+
28
+ ## 代码调用
29
+
30
+ 可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
31
+
32
+ ```ipython
33
+ >>> from transformers import AutoTokenizer, AutoModel
34
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True)
35
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda()
36
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
37
+ >>> print(response)
38
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
39
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
40
+ >>> print(response)
41
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
42
+
43
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
44
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
45
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
46
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
47
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
48
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
49
+
50
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
51
+ ```
52
+
53
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。
54
+
55
+ ## 协议
56
+
57
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
58
+
59
+ ## 引用
60
+
61
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文:
62
+
63
+ ```
64
+ @inproceedings{
65
+ zeng2023glm-130b,
66
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
67
+ author={Aohan Zeng and Xiao Liu and Zhengxiao Du and Zihan Wang and Hanyu Lai and Ming Ding and Zhuoyi Yang and Yifan Xu and Wendi Zheng and Xiao Xia and Weng Lam Tam and Zixuan Ma and Yufei Xue and Jidong Zhai and Wenguang Chen and Zhiyuan Liu and Peng Zhang and Yuxiao Dong and Jie Tang},
68
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
69
+ year={2023},
70
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
71
+ }
72
+ ```
73
+ ```
74
+ @inproceedings{du2022glm,
75
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
76
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
77
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
78
+ pages={320--335},
79
+ year={2022}
80
+ }
81
+ ```
models/chatglm/chatglm-6b-int4/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm-6b-int4",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "bos_token_id": 130004,
12
+ "eos_token_id": 130005,
13
+ "gmask_token_id": 130001,
14
+ "hidden_size": 4096,
15
+ "inner_hidden_size": 16384,
16
+ "layernorm_epsilon": 1e-05,
17
+ "mask_token_id": 130000,
18
+ "max_sequence_length": 2048,
19
+ "model_type": "chatglm",
20
+ "num_attention_heads": 32,
21
+ "num_layers": 28,
22
+ "pad_token_id": 3,
23
+ "position_encoding_2d": true,
24
+ "quantization_bit": 4,
25
+ "quantization_embeddings": false,
26
+ "torch_dtype": "float16",
27
+ "transformers_version": "4.27.1",
28
+ "use_cache": true,
29
+ "vocab_size": 130528
30
+ }
models/chatglm/chatglm-6b-int4/configuration_chatglm.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ ChatGLM model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ class ChatGLMConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`~ChatGLMModel`].
12
+ It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
13
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
14
+ the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
15
+
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
17
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
18
+ for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 150528):
23
+ Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`~ChatGLMModel`] or
25
+ [`~TFChatGLMModel`].
26
+ hidden_size (`int`, *optional*, defaults to 4096):
27
+ Dimension of the encoder layers and the pooler layer.
28
+ num_hidden_layers (`int`, *optional*, defaults to 28):
29
+ Number of hidden layers in the Transformer encoder.
30
+ num_attention_heads (`int`, *optional*, defaults to 32):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ inner_hidden_size (`int`, *optional*, defaults to 16384):
33
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
34
+ max_sequence_length (`int`, *optional*, defaults to 512):
35
+ The maximum sequence length that this model might ever be used with.
36
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
37
+ layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
38
+ The epsilon used by the layer normalization layers.
39
+ use_cache (`bool`, *optional*, defaults to `True`):
40
+ Whether the model should return the last key/values attentions (not used by all models).
41
+ Example:
42
+
43
+ ```python
44
+ >>> from configuration_chatglm import ChatGLMConfig
45
+ >>> from modeling_chatglm import ChatGLMModel
46
+
47
+ >>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
48
+ >>> configuration = ChatGLMConfig()
49
+
50
+ >>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
51
+ >>> model = ChatGLMModel(configuration)
52
+
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```
56
+ """
57
+ model_type = "chatglm"
58
+
59
+ def __init__(
60
+ self,
61
+ vocab_size=150528,
62
+ hidden_size=4096,
63
+ num_layers=28,
64
+ num_attention_heads=32,
65
+ layernorm_epsilon=1e-5,
66
+ use_cache=False,
67
+ bos_token_id=150004,
68
+ eos_token_id=150005,
69
+ mask_token_id=150000,
70
+ gmask_token_id=150001,
71
+ pad_token_id=0,
72
+ max_sequence_length=2048,
73
+ inner_hidden_size=16384,
74
+ position_encoding_2d=True,
75
+ quantization_bit=0,
76
+ quantization_embeddings=False,
77
+ pre_seq_len=None,
78
+ prefix_projection=False,
79
+ **kwargs
80
+ ):
81
+ self.num_layers = num_layers
82
+ self.vocab_size = vocab_size
83
+ self.hidden_size = hidden_size
84
+ self.num_attention_heads = num_attention_heads
85
+ self.max_sequence_length = max_sequence_length
86
+ self.layernorm_epsilon = layernorm_epsilon
87
+ self.inner_hidden_size = inner_hidden_size
88
+ self.use_cache = use_cache
89
+ self.bos_token_id = bos_token_id
90
+ self.eos_token_id = eos_token_id
91
+ self.pad_token_id = pad_token_id
92
+ self.mask_token_id = mask_token_id
93
+ self.gmask_token_id = gmask_token_id
94
+ self.position_encoding_2d = position_encoding_2d
95
+ self.quantization_bit = quantization_bit
96
+ self.quantization_embeddings = quantization_embeddings
97
+ self.pre_seq_len = pre_seq_len
98
+ self.prefix_projection = prefix_projection
99
+
100
+ super().__init__(
101
+ pad_token_id=pad_token_id,
102
+ bos_token_id=bos_token_id,
103
+ eos_token_id=eos_token_id,
104
+ **kwargs
105
+ )
models/chatglm/chatglm-6b-int4/ice_text.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e974d9a69c242ce014c88c2b26089270f6198f3c0b700a887666cd3e816f17e
3
+ size 2706249
models/chatglm/chatglm-6b-int4/modeling_chatglm.py ADDED
@@ -0,0 +1,1472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+ import warnings
7
+ import re
8
+ import sys
9
+
10
+ import torch
11
+ import torch.utils.checkpoint
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+ from torch.nn import CrossEntropyLoss, LayerNorm
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+
18
+ from transformers.utils import (
19
+ add_code_sample_docstrings,
20
+ add_start_docstrings,
21
+ add_start_docstrings_to_model_forward,
22
+ )
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ )
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import logging
30
+ from transformers.generation.logits_process import LogitsProcessor
31
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
32
+
33
+ from .configuration_chatglm import ChatGLMConfig
34
+
35
+
36
+ # flags required to enable jit fusion kernels
37
+
38
+ if sys.platform != 'darwin':
39
+ torch._C._jit_set_profiling_mode(False)
40
+ torch._C._jit_set_profiling_executor(False)
41
+ torch._C._jit_override_can_fuse_on_cpu(True)
42
+ torch._C._jit_override_can_fuse_on_gpu(True)
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
47
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
48
+
49
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
50
+ "THUDM/chatglm-6b",
51
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
52
+ ]
53
+
54
+
55
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
56
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
57
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
58
+ scores.zero_()
59
+ scores[..., 5] = 5e4
60
+ return scores
61
+
62
+
63
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
64
+ """Load tf checkpoints in a pytorch model."""
65
+ try:
66
+ import re
67
+
68
+ import numpy as np
69
+ import tensorflow as tf
70
+ except ImportError:
71
+ logger.error(
72
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
73
+ "https://www.tensorflow.org/install/ for installation instructions."
74
+ )
75
+ raise
76
+ tf_path = os.path.abspath(tf_checkpoint_path)
77
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
78
+ # Load weights from TF model
79
+ init_vars = tf.train.list_variables(tf_path)
80
+ names = []
81
+ arrays = []
82
+ for name, shape in init_vars:
83
+ logger.info(f"Loading TF weight {name} with shape {shape}")
84
+ array = tf.train.load_variable(tf_path, name)
85
+ names.append(name)
86
+ arrays.append(array)
87
+
88
+ for name, array in zip(names, arrays):
89
+ name = name.split("/")
90
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
91
+ # which are not required for using pretrained model
92
+ if any(
93
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
94
+ for n in name
95
+ ):
96
+ logger.info(f"Skipping {'/'.join(name)}")
97
+ continue
98
+ pointer = model
99
+ for m_name in name:
100
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
101
+ scope_names = re.split(r"_(\d+)", m_name)
102
+ else:
103
+ scope_names = [m_name]
104
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
105
+ pointer = getattr(pointer, "weight")
106
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
107
+ pointer = getattr(pointer, "bias")
108
+ elif scope_names[0] == "output_weights":
109
+ pointer = getattr(pointer, "weight")
110
+ elif scope_names[0] == "squad":
111
+ pointer = getattr(pointer, "classifier")
112
+ else:
113
+ try:
114
+ pointer = getattr(pointer, scope_names[0])
115
+ except AttributeError:
116
+ logger.info(f"Skipping {'/'.join(name)}")
117
+ continue
118
+ if len(scope_names) >= 2:
119
+ num = int(scope_names[1])
120
+ pointer = pointer[num]
121
+ if m_name[-11:] == "_embeddings":
122
+ pointer = getattr(pointer, "weight")
123
+ elif m_name == "kernel":
124
+ array = np.transpose(array)
125
+ try:
126
+ assert (
127
+ pointer.shape == array.shape
128
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
129
+ except AssertionError as e:
130
+ e.args += (pointer.shape, array.shape)
131
+ raise
132
+ logger.info(f"Initialize PyTorch weight {name}")
133
+ pointer.data = torch.from_numpy(array)
134
+ return model
135
+
136
+
137
+ class PrefixEncoder(torch.nn.Module):
138
+ """
139
+ The torch.nn model to encode the prefix
140
+ Input shape: (batch-size, prefix-length)
141
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
142
+ """
143
+
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ self.prefix_projection = config.prefix_projection
147
+ if self.prefix_projection:
148
+ # Use a two-layer MLP to encode the prefix
149
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
150
+ self.trans = torch.nn.Sequential(
151
+ torch.nn.Linear(config.hidden_size, config.hidden_size),
152
+ torch.nn.Tanh(),
153
+ torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
154
+ )
155
+ else:
156
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
157
+
158
+ def forward(self, prefix: torch.Tensor):
159
+ if self.prefix_projection:
160
+ prefix_tokens = self.embedding(prefix)
161
+ past_key_values = self.trans(prefix_tokens)
162
+ else:
163
+ past_key_values = self.embedding(prefix)
164
+ return past_key_values
165
+
166
+
167
+ @torch.jit.script
168
+ def gelu_impl(x):
169
+ """OpenAI's gelu implementation."""
170
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
171
+ (1.0 + 0.044715 * x * x)))
172
+
173
+
174
+ def gelu(x):
175
+ return gelu_impl(x)
176
+
177
+
178
+ class RotaryEmbedding(torch.nn.Module):
179
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
180
+ super().__init__()
181
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
182
+ inv_freq = inv_freq.half()
183
+ self.learnable = learnable
184
+ if learnable:
185
+ self.inv_freq = torch.nn.Parameter(inv_freq)
186
+ self.max_seq_len_cached = None
187
+ else:
188
+ self.register_buffer('inv_freq', inv_freq)
189
+ self.max_seq_len_cached = None
190
+ self.cos_cached = None
191
+ self.sin_cached = None
192
+ self.precision = precision
193
+
194
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
195
+ error_msgs):
196
+ pass
197
+
198
+ def forward(self, x, seq_dim=1, seq_len=None):
199
+ if seq_len is None:
200
+ seq_len = x.shape[seq_dim]
201
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
202
+ self.max_seq_len_cached = None if self.learnable else seq_len
203
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
204
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
205
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
206
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
207
+ if self.precision == torch.bfloat16:
208
+ emb = emb.float()
209
+
210
+ # [sx, 1 (b * np), hn]
211
+ cos_cached = emb.cos()[:, None, :]
212
+ sin_cached = emb.sin()[:, None, :]
213
+ if self.precision == torch.bfloat16:
214
+ cos_cached = cos_cached.bfloat16()
215
+ sin_cached = sin_cached.bfloat16()
216
+ if self.learnable:
217
+ return cos_cached, sin_cached
218
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
219
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
220
+
221
+ def _apply(self, fn):
222
+ if self.cos_cached is not None:
223
+ self.cos_cached = fn(self.cos_cached)
224
+ if self.sin_cached is not None:
225
+ self.sin_cached = fn(self.sin_cached)
226
+ return super()._apply(fn)
227
+
228
+ def rotate_half(x):
229
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
230
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
231
+
232
+
233
+ @torch.jit.script
234
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
235
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
236
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
237
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
238
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
239
+ return q, k
240
+
241
+
242
+ def attention_fn(
243
+ self,
244
+ query_layer,
245
+ key_layer,
246
+ value_layer,
247
+ attention_mask,
248
+ hidden_size_per_partition,
249
+ layer_id,
250
+ layer_past=None,
251
+ scaling_attention_score=True,
252
+ use_cache=False,
253
+ ):
254
+ if layer_past is not None:
255
+ past_key, past_value = layer_past[0], layer_past[1]
256
+ key_layer = torch.cat((past_key, key_layer), dim=0)
257
+ value_layer = torch.cat((past_value, value_layer), dim=0)
258
+
259
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
260
+ seq_len, b, nh, hidden_size = key_layer.shape
261
+
262
+ if use_cache:
263
+ present = (key_layer, value_layer)
264
+ else:
265
+ present = None
266
+
267
+ query_key_layer_scaling_coeff = float(layer_id + 1)
268
+ if scaling_attention_score:
269
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
270
+
271
+ # ===================================
272
+ # Raw attention scores. [b, np, s, s]
273
+ # ===================================
274
+
275
+ # [b, np, sq, sk]
276
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
277
+
278
+ # [sq, b, np, hn] -> [sq, b * np, hn]
279
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
280
+ # [sk, b, np, hn] -> [sk, b * np, hn]
281
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
282
+
283
+ matmul_result = torch.zeros(
284
+ 1, 1, 1,
285
+ dtype=query_layer.dtype,
286
+ device=query_layer.device,
287
+ )
288
+
289
+ matmul_result = torch.baddbmm(
290
+ matmul_result,
291
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
292
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
293
+ beta=0.0,
294
+ alpha=1.0,
295
+ )
296
+
297
+ # change view to [b, np, sq, sk]
298
+ attention_scores = matmul_result.view(*output_size)
299
+
300
+ if self.scale_mask_softmax:
301
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
302
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
303
+ else:
304
+ if not (attention_mask == 0).all():
305
+ # if auto-regressive, skip
306
+ attention_scores.masked_fill_(attention_mask, -10000.0)
307
+ dtype = attention_scores.dtype
308
+ attention_scores = attention_scores.float()
309
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
310
+
311
+ attention_probs = F.softmax(attention_scores, dim=-1)
312
+
313
+ attention_probs = attention_probs.type(dtype)
314
+
315
+ # =========================
316
+ # Context layer. [sq, b, hp]
317
+ # =========================
318
+
319
+ # value_layer -> context layer.
320
+ # [sk, b, np, hn] --> [b, np, sq, hn]
321
+
322
+ # context layer shape: [b, np, sq, hn]
323
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
324
+
325
+ # change view [sk, b * np, hn]
326
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
327
+
328
+ # change view [b * np, sq, sk]
329
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
330
+
331
+ # matmul: [b * np, sq, hn]
332
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
333
+
334
+ # change view [b, np, sq, hn]
335
+ context_layer = context_layer.view(*output_size)
336
+
337
+ # [b, np, sq, hn] --> [sq, b, np, hn]
338
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
339
+
340
+ # [sq, b, np, hn] --> [sq, b, hp]
341
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
342
+ context_layer = context_layer.view(*new_context_layer_shape)
343
+
344
+ outputs = (context_layer, present, attention_probs)
345
+
346
+ return outputs
347
+
348
+
349
+ def default_init(cls, *args, **kwargs):
350
+ return cls(*args, **kwargs)
351
+
352
+
353
+ class SelfAttention(torch.nn.Module):
354
+ def __init__(self, hidden_size, num_attention_heads,
355
+ layer_id, hidden_size_per_attention_head=None, bias=True,
356
+ params_dtype=torch.float, position_encoding_2d=True, empty_init=True):
357
+ if empty_init:
358
+ init_method = skip_init
359
+ else:
360
+ init_method = default_init
361
+ super(SelfAttention, self).__init__()
362
+
363
+ self.layer_id = layer_id
364
+ self.hidden_size = hidden_size
365
+ self.hidden_size_per_partition = hidden_size
366
+ self.num_attention_heads = num_attention_heads
367
+ self.num_attention_heads_per_partition = num_attention_heads
368
+ self.position_encoding_2d = position_encoding_2d
369
+ self.rotary_emb = RotaryEmbedding(
370
+ self.hidden_size // (self.num_attention_heads * 2)
371
+ if position_encoding_2d
372
+ else self.hidden_size // self.num_attention_heads,
373
+ base=10000,
374
+ precision=torch.half,
375
+ learnable=False,
376
+ )
377
+
378
+ self.scale_mask_softmax = None
379
+
380
+ if hidden_size_per_attention_head is None:
381
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
382
+ else:
383
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
384
+
385
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
386
+
387
+ # Strided linear layer.
388
+ self.query_key_value = init_method(
389
+ torch.nn.Linear,
390
+ hidden_size,
391
+ 3 * self.inner_hidden_size,
392
+ bias=bias,
393
+ dtype=params_dtype,
394
+ )
395
+
396
+ self.dense = init_method(
397
+ torch.nn.Linear,
398
+ self.inner_hidden_size,
399
+ hidden_size,
400
+ bias=bias,
401
+ dtype=params_dtype,
402
+ )
403
+
404
+ @staticmethod
405
+ def attention_mask_func(attention_scores, attention_mask):
406
+ attention_scores.masked_fill_(attention_mask, -10000.0)
407
+ return attention_scores
408
+
409
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
410
+ contiguous_split_chunks=False):
411
+ """Split a tensor along its last dimension.
412
+ Arguments:
413
+ tensor: input tensor.
414
+ num_partitions: number of partitions to split the tensor
415
+ contiguous_split_chunks: If True, make each chunk contiguous
416
+ in memory.
417
+ """
418
+ # Get the size and dimension.
419
+ last_dim = tensor.dim() - 1
420
+ last_dim_size = tensor.size()[last_dim] // num_partitions
421
+ # Split.
422
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
423
+ # Note: torch.split does not create contiguous tensors by default.
424
+ if contiguous_split_chunks:
425
+ return tuple(chunk.contiguous() for chunk in tensor_list)
426
+
427
+ return tensor_list
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ position_ids,
433
+ attention_mask: torch.Tensor,
434
+ layer_id,
435
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
436
+ use_cache: bool = False,
437
+ output_attentions: bool = False,
438
+ ):
439
+ """
440
+ hidden_states: [seq_len, batch, hidden_size]
441
+ attention_mask: [(1, 1), seq_len, seq_len]
442
+ """
443
+
444
+ # [seq_len, batch, 3 * hidden_size]
445
+ mixed_raw_layer = self.query_key_value(hidden_states)
446
+
447
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
448
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
449
+ self.num_attention_heads_per_partition,
450
+ 3 * self.hidden_size_per_attention_head,
451
+ )
452
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
453
+
454
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
455
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
456
+
457
+ if self.position_encoding_2d:
458
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
459
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
460
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
461
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
462
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
463
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
464
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
465
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
466
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
467
+ else:
468
+ position_ids = position_ids.transpose(0, 1)
469
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
470
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
471
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
472
+
473
+ # [seq_len, batch, hidden_size]
474
+ context_layer, present, attention_probs = attention_fn(
475
+ self=self,
476
+ query_layer=query_layer,
477
+ key_layer=key_layer,
478
+ value_layer=value_layer,
479
+ attention_mask=attention_mask,
480
+ hidden_size_per_partition=self.hidden_size_per_partition,
481
+ layer_id=layer_id,
482
+ layer_past=layer_past,
483
+ use_cache=use_cache
484
+ )
485
+
486
+ output = self.dense(context_layer)
487
+
488
+ outputs = (output, present)
489
+
490
+ if output_attentions:
491
+ outputs += (attention_probs,)
492
+
493
+ return outputs # output, present, attention_probs
494
+
495
+
496
+ class GEGLU(torch.nn.Module):
497
+ def __init__(self):
498
+ super().__init__()
499
+ self.activation_fn = F.gelu
500
+
501
+ def forward(self, x):
502
+ # dim=-1 breaks in jit for pt<1.10
503
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
504
+ return x1 * self.activation_fn(x2)
505
+
506
+
507
+ class GLU(torch.nn.Module):
508
+ def __init__(self, hidden_size, inner_hidden_size=None,
509
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float, empty_init=True):
510
+ super(GLU, self).__init__()
511
+ if empty_init:
512
+ init_method = skip_init
513
+ else:
514
+ init_method = default_init
515
+ self.layer_id = layer_id
516
+ self.activation_func = activation_func
517
+
518
+ # Project to 4h.
519
+ self.hidden_size = hidden_size
520
+ if inner_hidden_size is None:
521
+ inner_hidden_size = 4 * hidden_size
522
+ self.inner_hidden_size = inner_hidden_size
523
+ self.dense_h_to_4h = init_method(
524
+ torch.nn.Linear,
525
+ self.hidden_size,
526
+ self.inner_hidden_size,
527
+ bias=bias,
528
+ dtype=params_dtype,
529
+ )
530
+ # Project back to h.
531
+ self.dense_4h_to_h = init_method(
532
+ torch.nn.Linear,
533
+ self.inner_hidden_size,
534
+ self.hidden_size,
535
+ bias=bias,
536
+ dtype=params_dtype,
537
+ )
538
+
539
+ def forward(self, hidden_states):
540
+ """
541
+ hidden_states: [seq_len, batch, hidden_size]
542
+ """
543
+
544
+ # [seq_len, batch, inner_hidden_size]
545
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
546
+
547
+ intermediate_parallel = self.activation_func(intermediate_parallel)
548
+
549
+ output = self.dense_4h_to_h(intermediate_parallel)
550
+
551
+ return output
552
+
553
+
554
+ class GLMBlock(torch.nn.Module):
555
+ def __init__(
556
+ self,
557
+ hidden_size,
558
+ num_attention_heads,
559
+ layernorm_epsilon,
560
+ layer_id,
561
+ inner_hidden_size=None,
562
+ hidden_size_per_attention_head=None,
563
+ layernorm=LayerNorm,
564
+ use_bias=True,
565
+ params_dtype=torch.float,
566
+ num_layers=28,
567
+ position_encoding_2d=True,
568
+ empty_init=True
569
+ ):
570
+ super(GLMBlock, self).__init__()
571
+ # Set output layer initialization if not provided.
572
+
573
+ self.layer_id = layer_id
574
+
575
+ # Layernorm on the input data.
576
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
577
+
578
+ self.position_encoding_2d = position_encoding_2d
579
+
580
+ # Self attention.
581
+ self.attention = SelfAttention(
582
+ hidden_size,
583
+ num_attention_heads,
584
+ layer_id,
585
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
586
+ bias=use_bias,
587
+ params_dtype=params_dtype,
588
+ position_encoding_2d=self.position_encoding_2d,
589
+ empty_init=empty_init
590
+ )
591
+
592
+ # Layernorm on the input data.
593
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
594
+
595
+ self.num_layers = num_layers
596
+
597
+ # GLU
598
+ self.mlp = GLU(
599
+ hidden_size,
600
+ inner_hidden_size=inner_hidden_size,
601
+ bias=use_bias,
602
+ layer_id=layer_id,
603
+ params_dtype=params_dtype,
604
+ empty_init=empty_init
605
+ )
606
+
607
+ def forward(
608
+ self,
609
+ hidden_states: torch.Tensor,
610
+ position_ids,
611
+ attention_mask: torch.Tensor,
612
+ layer_id,
613
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
614
+ use_cache: bool = False,
615
+ output_attentions: bool = False,
616
+ ):
617
+ """
618
+ hidden_states: [seq_len, batch, hidden_size]
619
+ attention_mask: [(1, 1), seq_len, seq_len]
620
+ """
621
+
622
+ # Layer norm at the begining of the transformer layer.
623
+ # [seq_len, batch, hidden_size]
624
+ attention_input = self.input_layernorm(hidden_states)
625
+
626
+ # Self attention.
627
+ attention_outputs = self.attention(
628
+ attention_input,
629
+ position_ids,
630
+ attention_mask=attention_mask,
631
+ layer_id=layer_id,
632
+ layer_past=layer_past,
633
+ use_cache=use_cache,
634
+ output_attentions=output_attentions
635
+ )
636
+
637
+ attention_output = attention_outputs[0]
638
+
639
+ outputs = attention_outputs[1:]
640
+
641
+ # Residual connection.
642
+ alpha = (2 * self.num_layers) ** 0.5
643
+ hidden_states = attention_input * alpha + attention_output
644
+
645
+ mlp_input = self.post_attention_layernorm(hidden_states)
646
+
647
+ # MLP.
648
+ mlp_output = self.mlp(mlp_input)
649
+
650
+ # Second residual connection.
651
+ output = mlp_input * alpha + mlp_output
652
+
653
+ if use_cache:
654
+ outputs = (output,) + outputs
655
+ else:
656
+ outputs = (output,) + outputs[1:]
657
+
658
+ return outputs # hidden_states, present, attentions
659
+
660
+
661
+ class ChatGLMPreTrainedModel(PreTrainedModel):
662
+ """
663
+ An abstract class to handle weights initialization and
664
+ a simple interface for downloading and loading pretrained models.
665
+ """
666
+
667
+ is_parallelizable = False
668
+ supports_gradient_checkpointing = True
669
+ config_class = ChatGLMConfig
670
+ base_model_prefix = "transformer"
671
+ _no_split_modules = ["GLMBlock"]
672
+
673
+ def __init__(self, *inputs, **kwargs):
674
+ super().__init__(*inputs, **kwargs)
675
+
676
+ def _init_weights(self, module: nn.Module):
677
+ """Initialize the weights."""
678
+ return
679
+
680
+ def get_masks(self, input_ids, device):
681
+ batch_size, seq_length = input_ids.shape
682
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
683
+ attention_mask = torch.ones((batch_size, seq_length, seq_length), device=device)
684
+ attention_mask.tril_()
685
+ for i, context_length in enumerate(context_lengths):
686
+ attention_mask[i, :, :context_length] = 1
687
+ attention_mask.unsqueeze_(1)
688
+ attention_mask = (attention_mask < 0.5).bool()
689
+
690
+ return attention_mask
691
+
692
+ def get_position_ids(self, input_ids, mask_positions, device, use_gmasks=None):
693
+ batch_size, seq_length = input_ids.shape
694
+ if use_gmasks is None:
695
+ use_gmasks = [False] * batch_size
696
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
697
+ if self.position_encoding_2d:
698
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
699
+ for i, context_length in enumerate(context_lengths):
700
+ position_ids[i, context_length:] = mask_positions[i]
701
+ block_position_ids = [torch.cat((
702
+ torch.zeros(context_length, dtype=torch.long, device=device),
703
+ torch.arange(seq_length - context_length, dtype=torch.long, device=device) + 1
704
+ )) for context_length in context_lengths]
705
+ block_position_ids = torch.stack(block_position_ids, dim=0)
706
+ position_ids = torch.stack((position_ids, block_position_ids), dim=1)
707
+ else:
708
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
709
+ for i, context_length in enumerate(context_lengths):
710
+ if not use_gmasks[i]:
711
+ position_ids[context_length:] = mask_positions[i]
712
+
713
+ return position_ids
714
+
715
+ def _set_gradient_checkpointing(self, module, value=False):
716
+ if isinstance(module, ChatGLMModel):
717
+ module.gradient_checkpointing = value
718
+
719
+
720
+ CHATGLM_6B_START_DOCSTRING = r"""
721
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
722
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
723
+ usage and behavior.
724
+
725
+ Parameters:
726
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
727
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
728
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
729
+ """
730
+
731
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
732
+ Args:
733
+ input_ids (`torch.LongTensor` of shape `({0})`):
734
+ Indices of input sequence tokens in the vocabulary.
735
+
736
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
737
+ See [`PreTrainedTokenizer.encode`] and
738
+ [`PreTrainedTokenizer.__call__`] for details.
739
+
740
+ [What are input IDs?](../glossary#input-ids)
741
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
742
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
743
+
744
+ - 1 for tokens that are **not masked**,
745
+ - 0 for tokens that are **masked**.
746
+
747
+ [What are attention masks?](../glossary#attention-mask)
748
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
749
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
750
+
751
+ - 0 corresponds to a *sentence A* token,
752
+ - 1 corresponds to a *sentence B* token.
753
+
754
+ [What are token type IDs?](../glossary#token-type-ids)
755
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
756
+ Indices of positions of each input sequence tokens in the position embeddings.
757
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
758
+
759
+ [What are position IDs?](../glossary#position-ids)
760
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
761
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
762
+
763
+ - 1 indicates the head is **not masked**,
764
+ - 0 indicates the head is **masked**.
765
+
766
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
767
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
768
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
769
+ than the model's internal embedding lookup matrix.
770
+ output_attentions (`bool`, *optional*):
771
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
772
+ tensors for more detail.
773
+ output_hidden_states (`bool`, *optional*):
774
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
775
+ more detail.
776
+ return_dict (`bool`, *optional*):
777
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
778
+ """
779
+
780
+
781
+ @add_start_docstrings(
782
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
783
+ CHATGLM_6B_START_DOCSTRING,
784
+ )
785
+ class ChatGLMModel(ChatGLMPreTrainedModel):
786
+ """
787
+
788
+ The model can behave as an encoder (with only self-attention) as well
789
+ as a decoder, in which case a layer of cross-attention is added between
790
+ the self-attention layers, following the architecture described in [Attention is
791
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
792
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
793
+
794
+ To behave as an decoder the model needs to be initialized with the
795
+ `is_decoder` argument of the configuration set to `True`.
796
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
797
+ argument and `add_cross_attention` set to `True`; an
798
+ `encoder_hidden_states` is then expected as an input to the forward pass.
799
+ """
800
+
801
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
802
+ super().__init__(config)
803
+ if empty_init:
804
+ init_method = skip_init
805
+ else:
806
+ init_method = default_init
807
+ # recording parameters
808
+ self.max_sequence_length = config.max_sequence_length
809
+ self.hidden_size = config.hidden_size
810
+ self.params_dtype = torch.half
811
+ self.num_attention_heads = config.num_attention_heads
812
+ self.vocab_size = config.vocab_size
813
+ self.num_layers = config.num_layers
814
+ self.layernorm_epsilon = config.layernorm_epsilon
815
+ self.inner_hidden_size = config.inner_hidden_size
816
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
817
+ self.position_encoding_2d = config.position_encoding_2d
818
+ self.pre_seq_len = config.pre_seq_len
819
+ self.prefix_projection = config.prefix_projection
820
+
821
+ self.word_embeddings = init_method(
822
+ torch.nn.Embedding,
823
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
824
+ dtype=self.params_dtype
825
+ )
826
+ self.gradient_checkpointing = False
827
+
828
+ def get_layer(layer_id):
829
+ return GLMBlock(
830
+ self.hidden_size,
831
+ self.num_attention_heads,
832
+ self.layernorm_epsilon,
833
+ layer_id,
834
+ inner_hidden_size=self.inner_hidden_size,
835
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
836
+ layernorm=LayerNorm,
837
+ use_bias=True,
838
+ params_dtype=self.params_dtype,
839
+ position_encoding_2d=self.position_encoding_2d,
840
+ empty_init=empty_init
841
+ )
842
+
843
+ self.layers = torch.nn.ModuleList(
844
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
845
+ )
846
+
847
+ # Final layer norm before output.
848
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
849
+
850
+ if self.pre_seq_len is not None:
851
+ for param in self.parameters():
852
+ param.requires_grad = False
853
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
854
+ self.prefix_encoder = PrefixEncoder(config)
855
+ self.dropout = torch.nn.Dropout(0.1)
856
+
857
+ # total_params = sum(p.numel() for p in self.parameters())
858
+ # trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
859
+ # print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
860
+
861
+ def get_input_embeddings(self):
862
+ return self.word_embeddings
863
+
864
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
865
+ self.word_embeddings = new_embeddings
866
+
867
+ def get_prompt(self, batch_size, device, dtype=torch.half):
868
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
869
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
870
+ past_key_values = past_key_values.view(
871
+ batch_size,
872
+ self.pre_seq_len,
873
+ self.num_layers * 2,
874
+ self.num_attention_heads,
875
+ self.hidden_size // self.num_attention_heads
876
+ )
877
+ # seq_len, b, nh, hidden_size
878
+ past_key_values = self.dropout(past_key_values)
879
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
880
+ # past_key_values = [(v[0], v[1]) for v in past_key_values]
881
+ return past_key_values
882
+
883
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
884
+ @add_code_sample_docstrings(
885
+ checkpoint=_CHECKPOINT_FOR_DOC,
886
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
887
+ config_class=_CONFIG_FOR_DOC,
888
+ )
889
+ def forward(
890
+ self,
891
+ input_ids: Optional[torch.LongTensor] = None,
892
+ position_ids: Optional[torch.LongTensor] = None,
893
+ attention_mask: Optional[torch.Tensor] = None,
894
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
895
+ inputs_embeds: Optional[torch.LongTensor] = None,
896
+ use_cache: Optional[bool] = None,
897
+ output_attentions: Optional[bool] = None,
898
+ output_hidden_states: Optional[bool] = None,
899
+ return_dict: Optional[bool] = None,
900
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
901
+
902
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
903
+ output_hidden_states = (
904
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
905
+ )
906
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
907
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
908
+
909
+ if self.gradient_checkpointing and self.training:
910
+ if use_cache:
911
+ logger.warning_once(
912
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
913
+ )
914
+ use_cache = False
915
+
916
+ if input_ids is not None and inputs_embeds is not None:
917
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
918
+ elif input_ids is not None:
919
+ batch_size, seq_length = input_ids.shape[:2]
920
+ elif inputs_embeds is not None:
921
+ batch_size, seq_length, _ = inputs_embeds.shape[:2]
922
+ else:
923
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
924
+
925
+ if inputs_embeds is None:
926
+ inputs_embeds = self.word_embeddings(input_ids)
927
+
928
+ if past_key_values is None:
929
+ if self.pre_seq_len is not None:
930
+ past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device,
931
+ dtype=inputs_embeds.dtype)
932
+ else:
933
+ past_key_values = tuple([None] * len(self.layers))
934
+
935
+ if attention_mask is None:
936
+ attention_mask = self.get_masks(
937
+ input_ids,
938
+ device=input_ids.device
939
+ )
940
+
941
+
942
+ if position_ids is None:
943
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
944
+ seqs = input_ids.tolist()
945
+
946
+ mask_positions, use_gmasks = [], []
947
+ for seq in seqs:
948
+ mask_token = gMASK if gMASK in seq else MASK
949
+ use_gmask = mask_token == gMASK
950
+ mask_positions.append(seq.index(mask_token))
951
+ use_gmasks.append(use_gmask)
952
+
953
+ position_ids = self.get_position_ids(
954
+ input_ids,
955
+ mask_positions=mask_positions,
956
+ device=input_ids.device,
957
+ use_gmasks=use_gmasks
958
+ )
959
+
960
+ if self.pre_seq_len is not None and attention_mask is not None:
961
+ prefix_attention_mask = torch.ones(batch_size, 1, input_ids.size(-1), self.pre_seq_len).to(
962
+ attention_mask.device)
963
+ prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
964
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)
965
+
966
+ # [seq_len, batch, hidden_size]
967
+ hidden_states = inputs_embeds.transpose(0, 1)
968
+
969
+ presents = () if use_cache else None
970
+ all_self_attentions = () if output_attentions else None
971
+ all_hidden_states = () if output_hidden_states else None
972
+
973
+ if attention_mask is None:
974
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
975
+
976
+ else:
977
+ attention_mask = attention_mask.to(input_ids.device)
978
+
979
+ for i, layer in enumerate(self.layers):
980
+
981
+ if output_hidden_states:
982
+ all_hidden_states = all_hidden_states + (hidden_states,)
983
+ layer_past = past_key_values[i]
984
+
985
+ if self.gradient_checkpointing and self.training:
986
+ layer_ret = torch.utils.checkpoint.checkpoint(
987
+ layer,
988
+ hidden_states,
989
+ position_ids,
990
+ attention_mask,
991
+ torch.tensor(i),
992
+ layer_past,
993
+ use_cache,
994
+ output_attentions
995
+ )
996
+ else:
997
+ layer_ret = layer(
998
+ hidden_states,
999
+ position_ids=position_ids,
1000
+ attention_mask=attention_mask,
1001
+ layer_id=torch.tensor(i),
1002
+ layer_past=layer_past,
1003
+ use_cache=use_cache,
1004
+ output_attentions=output_attentions
1005
+ )
1006
+
1007
+ hidden_states = layer_ret[0]
1008
+
1009
+ if use_cache:
1010
+ presents = presents + (layer_ret[1],)
1011
+
1012
+ if output_attentions:
1013
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
1014
+
1015
+ # Final layer norm.
1016
+ hidden_states = self.final_layernorm(hidden_states)
1017
+
1018
+ if output_hidden_states:
1019
+ all_hidden_states = all_hidden_states + (hidden_states,)
1020
+
1021
+ if not return_dict:
1022
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1023
+
1024
+ return BaseModelOutputWithPast(
1025
+ last_hidden_state=hidden_states,
1026
+ past_key_values=presents,
1027
+ hidden_states=all_hidden_states,
1028
+ attentions=all_self_attentions,
1029
+ )
1030
+
1031
+
1032
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1033
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
1034
+ super().__init__(config)
1035
+ if empty_init:
1036
+ init_method = skip_init
1037
+ else:
1038
+ init_method = default_init
1039
+
1040
+ # self.hidden_size = config.hidden_size
1041
+ # self.params_dtype = torch.half
1042
+ # self.vocab_size = config.vocab_size
1043
+ self.max_sequence_length = config.max_sequence_length
1044
+
1045
+ self.position_encoding_2d = config.position_encoding_2d
1046
+
1047
+ self.transformer = ChatGLMModel(config, empty_init=empty_init)
1048
+
1049
+ self.lm_head = init_method(
1050
+ nn.Linear,
1051
+ config.hidden_size,
1052
+ config.vocab_size,
1053
+ bias=False,
1054
+ dtype=torch.half
1055
+ )
1056
+
1057
+ self.config = config
1058
+
1059
+ self.quantized = False
1060
+
1061
+ if self.config.quantization_bit:
1062
+ self.quantize(self.config.quantization_bit, self.config.quantization_embeddings, use_quantization_cache=True, empty_init=True)
1063
+
1064
+ def get_output_embeddings(self):
1065
+ return self.lm_head
1066
+
1067
+ def set_output_embeddings(self, new_embeddings):
1068
+ self.lm_head = new_embeddings
1069
+
1070
+ def _update_model_kwargs_for_generation(
1071
+ self,
1072
+ outputs: ModelOutput,
1073
+ model_kwargs: Dict[str, Any],
1074
+ is_encoder_decoder: bool = False,
1075
+ standardize_cache_format: bool = False,
1076
+ ) -> Dict[str, Any]:
1077
+ # update past_key_values
1078
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1079
+ outputs, standardize_cache_format=standardize_cache_format
1080
+ )
1081
+
1082
+ # update attention mask
1083
+ if "attention_mask" in model_kwargs:
1084
+ attention_mask = model_kwargs["attention_mask"]
1085
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1086
+ attention_mask = torch.cat(
1087
+ [attention_mask, attention_mask.new_ones((*attention_mask.shape[:3], 1))], dim=3)
1088
+ new_attention_mask = attention_mask[:, :, -1:].clone()
1089
+ new_attention_mask[..., -1] = False
1090
+ model_kwargs["attention_mask"] = torch.cat(
1091
+ [attention_mask, new_attention_mask], dim=2
1092
+ )
1093
+
1094
+ # update position ids
1095
+ if "position_ids" in model_kwargs:
1096
+ position_ids = model_kwargs["position_ids"]
1097
+ new_position_id = position_ids[..., -1:].clone()
1098
+ new_position_id[:, 1, :] += 1
1099
+ model_kwargs["position_ids"] = torch.cat(
1100
+ [position_ids, new_position_id], dim=-1
1101
+ )
1102
+
1103
+ return model_kwargs
1104
+
1105
+ def prepare_inputs_for_generation(
1106
+ self,
1107
+ input_ids: torch.LongTensor,
1108
+ past: Optional[torch.Tensor] = None,
1109
+ past_key_values: Optional[torch.Tensor] = None,
1110
+ attention_mask: Optional[torch.Tensor] = None,
1111
+ position_ids: Optional[torch.Tensor] = None,
1112
+ **kwargs
1113
+ ) -> dict:
1114
+ batch_size, seq_length = input_ids.shape
1115
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
1116
+ seqs = input_ids.tolist()
1117
+ mask_positions, use_gmasks = [], []
1118
+ for seq in seqs:
1119
+ mask_token = gMASK if gMASK in seq else MASK
1120
+ use_gmask = mask_token == gMASK
1121
+ mask_positions.append(seq.index(mask_token))
1122
+ use_gmasks.append(use_gmask)
1123
+
1124
+ # only last token for input_ids if past is not None
1125
+ if past is not None or past_key_values is not None:
1126
+ last_token = input_ids[:, -1].unsqueeze(-1)
1127
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1128
+ attention_mask = attention_mask[:, :, -1:]
1129
+ else:
1130
+ attention_mask = None
1131
+ if position_ids is not None:
1132
+ position_ids = position_ids[..., -1:]
1133
+ else:
1134
+ context_lengths = [seq.index(self.config.bos_token_id) for seq in seqs]
1135
+ if self.position_encoding_2d:
1136
+ position_ids = torch.tensor(
1137
+ [[mask_position, seq_length - context_length] for mask_position, context_length in
1138
+ zip(mask_positions, context_lengths)], dtype=torch.long, device=input_ids.device).unsqueeze(-1)
1139
+ else:
1140
+ position_ids = torch.tensor([mask_position for mask_position in mask_positions], dtype=torch.long,
1141
+ device=input_ids.device).unsqueeze(-1)
1142
+
1143
+ if past is None:
1144
+ past = past_key_values
1145
+ return {
1146
+ "input_ids": last_token,
1147
+ "past_key_values": past,
1148
+ "position_ids": position_ids,
1149
+ "attention_mask": attention_mask
1150
+ }
1151
+ else:
1152
+ if attention_mask is not None and attention_mask.dtype != torch.bool:
1153
+ logger.warning_once(f"The dtype of attention mask ({attention_mask.dtype}) is not bool")
1154
+ attention_mask = None
1155
+ if attention_mask is None:
1156
+ attention_mask = self.get_masks(
1157
+ input_ids,
1158
+ device=input_ids.device
1159
+ )
1160
+ if position_ids is None:
1161
+ position_ids = self.get_position_ids(
1162
+ input_ids,
1163
+ device=input_ids.device,
1164
+ mask_positions=mask_positions,
1165
+ use_gmasks=use_gmasks
1166
+ )
1167
+
1168
+ return {
1169
+ "input_ids": input_ids,
1170
+ "past_key_values": past,
1171
+ "position_ids": position_ids,
1172
+ "attention_mask": attention_mask
1173
+ }
1174
+
1175
+ def forward(
1176
+ self,
1177
+ input_ids: Optional[torch.Tensor] = None,
1178
+ position_ids: Optional[torch.Tensor] = None,
1179
+ attention_mask: Optional[torch.Tensor] = None,
1180
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1181
+ inputs_embeds: Optional[torch.Tensor] = None,
1182
+ labels: Optional[torch.Tensor] = None,
1183
+ use_cache: Optional[bool] = None,
1184
+ output_attentions: Optional[bool] = None,
1185
+ output_hidden_states: Optional[bool] = None,
1186
+ return_dict: Optional[bool] = None,
1187
+ ):
1188
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1189
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1190
+
1191
+ transformer_outputs = self.transformer(
1192
+ input_ids=input_ids,
1193
+ position_ids=position_ids,
1194
+ attention_mask=attention_mask,
1195
+ past_key_values=past_key_values,
1196
+ inputs_embeds=inputs_embeds,
1197
+ use_cache=use_cache,
1198
+ output_attentions=output_attentions,
1199
+ output_hidden_states=output_hidden_states,
1200
+ return_dict=return_dict,
1201
+ )
1202
+
1203
+ hidden_states = transformer_outputs[0]
1204
+
1205
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1206
+
1207
+ loss = None
1208
+ if labels is not None:
1209
+ lm_logits = lm_logits.to(torch.float32)
1210
+
1211
+ # Shift so that tokens < n predict n
1212
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1213
+ shift_labels = labels[..., 1:].contiguous()
1214
+ # Flatten the tokens
1215
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1216
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1217
+
1218
+ lm_logits = lm_logits.to(hidden_states.dtype)
1219
+ loss = loss.to(hidden_states.dtype)
1220
+
1221
+ if not return_dict:
1222
+ output = (lm_logits,) + transformer_outputs[1:]
1223
+ return ((loss,) + output) if loss is not None else output
1224
+
1225
+ return CausalLMOutputWithPast(
1226
+ loss=loss,
1227
+ logits=lm_logits,
1228
+ past_key_values=transformer_outputs.past_key_values,
1229
+ hidden_states=transformer_outputs.hidden_states,
1230
+ attentions=transformer_outputs.attentions,
1231
+ )
1232
+
1233
+ @staticmethod
1234
+ def _reorder_cache(
1235
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1236
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1237
+ """
1238
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1239
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1240
+ beam_idx at every generation step.
1241
+
1242
+ Output shares the same memory storage as `past`.
1243
+ """
1244
+ return tuple(
1245
+ (
1246
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1247
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1248
+ )
1249
+ for layer_past in past
1250
+ )
1251
+
1252
+ def process_response(self, response):
1253
+ response = response.strip()
1254
+ response = response.replace("[[训练时间]]", "2023年")
1255
+ punkts = [
1256
+ [",", ","],
1257
+ ["!", "!"],
1258
+ [":", ":"],
1259
+ [";", ";"],
1260
+ ["\?", "?"],
1261
+ ]
1262
+ for item in punkts:
1263
+ response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
1264
+ response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
1265
+ return response
1266
+
1267
+ @torch.no_grad()
1268
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1269
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1270
+ if history is None:
1271
+ history = []
1272
+ if logits_processor is None:
1273
+ logits_processor = LogitsProcessorList()
1274
+ logits_processor.append(InvalidScoreLogitsProcessor())
1275
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1276
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1277
+ if not history:
1278
+ prompt = query
1279
+ else:
1280
+ prompt = ""
1281
+ for i, (old_query, response) in enumerate(history):
1282
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1283
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1284
+ inputs = tokenizer([prompt], return_tensors="pt")
1285
+ inputs = inputs.to(self.device)
1286
+ outputs = self.generate(**inputs, **gen_kwargs)
1287
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1288
+ response = tokenizer.decode(outputs)
1289
+ response = self.process_response(response)
1290
+ history = history + [(query, response)]
1291
+ return response, history
1292
+
1293
+ @torch.no_grad()
1294
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
1295
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1296
+ if history is None:
1297
+ history = []
1298
+ if logits_processor is None:
1299
+ logits_processor = LogitsProcessorList()
1300
+ logits_processor.append(InvalidScoreLogitsProcessor())
1301
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1302
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1303
+ if not history:
1304
+ prompt = query
1305
+ else:
1306
+ prompt = ""
1307
+ for i, (old_query, response) in enumerate(history):
1308
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1309
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1310
+ inputs = tokenizer([prompt], return_tensors="pt")
1311
+ inputs = inputs.to(self.device)
1312
+ for outputs in self.stream_generate(**inputs, **gen_kwargs):
1313
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1314
+ response = tokenizer.decode(outputs)
1315
+ response = self.process_response(response)
1316
+ new_history = history + [(query, response)]
1317
+ yield response, new_history
1318
+
1319
+ @torch.no_grad()
1320
+ def stream_generate(
1321
+ self,
1322
+ input_ids,
1323
+ generation_config: Optional[GenerationConfig] = None,
1324
+ logits_processor: Optional[LogitsProcessorList] = None,
1325
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1326
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1327
+ **kwargs,
1328
+ ):
1329
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1330
+
1331
+ if generation_config is None:
1332
+ generation_config = self.generation_config
1333
+ generation_config = copy.deepcopy(generation_config)
1334
+ model_kwargs = generation_config.update(**kwargs)
1335
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1336
+
1337
+ if isinstance(eos_token_id, int):
1338
+ eos_token_id = [eos_token_id]
1339
+
1340
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1341
+ if has_default_max_length and generation_config.max_new_tokens is None:
1342
+ warnings.warn(
1343
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1344
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1345
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1346
+ UserWarning,
1347
+ )
1348
+ elif generation_config.max_new_tokens is not None:
1349
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1350
+ if not has_default_max_length:
1351
+ logger.warn(
1352
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1353
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1354
+ "Please refer to the documentation for more information. "
1355
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1356
+ UserWarning,
1357
+ )
1358
+
1359
+ if input_ids_seq_length >= generation_config.max_length:
1360
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1361
+ logger.warning(
1362
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1363
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1364
+ " increasing `max_new_tokens`."
1365
+ )
1366
+
1367
+ # 2. Set generation parameters if not already defined
1368
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1369
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1370
+
1371
+ logits_processor = self._get_logits_processor(
1372
+ generation_config=generation_config,
1373
+ input_ids_seq_length=input_ids_seq_length,
1374
+ encoder_input_ids=input_ids,
1375
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1376
+ logits_processor=logits_processor,
1377
+ )
1378
+
1379
+ stopping_criteria = self._get_stopping_criteria(
1380
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1381
+ )
1382
+ logits_warper = self._get_logits_warper(generation_config)
1383
+
1384
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1385
+ scores = None
1386
+ while True:
1387
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1388
+ # forward pass to get next token
1389
+ outputs = self(
1390
+ **model_inputs,
1391
+ return_dict=True,
1392
+ output_attentions=False,
1393
+ output_hidden_states=False,
1394
+ )
1395
+
1396
+ next_token_logits = outputs.logits[:, -1, :]
1397
+
1398
+ # pre-process distribution
1399
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1400
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1401
+
1402
+ # sample
1403
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1404
+ if generation_config.do_sample:
1405
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1406
+ else:
1407
+ next_tokens = torch.argmax(probs, dim=-1)
1408
+
1409
+ # update generated ids, model inputs, and length for next step
1410
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1411
+ model_kwargs = self._update_model_kwargs_for_generation(
1412
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1413
+ )
1414
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1415
+
1416
+ # stop when each sentence is finished, or if we exceed the maximum length
1417
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1418
+ break
1419
+ yield input_ids
1420
+
1421
+ def quantize(self, bits: int, quantize_embeddings=False, use_quantization_cache=False, empty_init=False, **kwargs):
1422
+ if bits == 0:
1423
+ return
1424
+
1425
+ from .quantization import quantize, QuantizedEmbedding, QuantizedLinear, load_cpu_kernel
1426
+
1427
+ if self.quantized:
1428
+ if self.device == torch.device("cpu"):
1429
+ logger.info("Already quantized, reloading cpu kernel.")
1430
+ load_cpu_kernel(**kwargs)
1431
+ else:
1432
+ logger.info("Already quantized.")
1433
+ return self
1434
+
1435
+ self.quantized = True
1436
+
1437
+ self.config.quantization_bit = bits
1438
+ self.config.quantization_embeddings = quantize_embeddings
1439
+
1440
+ self.transformer = quantize(self.transformer, bits, use_quantization_cache=use_quantization_cache, empty_init=empty_init, **kwargs)
1441
+
1442
+ if self.device == torch.device("cpu"):
1443
+ dtype = torch.float32
1444
+ else:
1445
+ dtype = torch.half
1446
+
1447
+ if quantize_embeddings:
1448
+ logger.info("Applying quantization to embeddings")
1449
+ self.transformer.word_embeddings = QuantizedEmbedding(
1450
+ weight_bit_width=bits,
1451
+ weight_tensor=self.transformer.word_embeddings.weight.to(self.device),
1452
+ num_embeddings=self.transformer.word_embeddings.num_embeddings,
1453
+ embedding_dim=self.transformer.word_embeddings.embedding_dim,
1454
+ dtype=dtype,
1455
+ empty_init=empty_init,
1456
+ device=self.transformer.word_embeddings.weight.device,
1457
+ )
1458
+ self.lm_head = QuantizedLinear(
1459
+ weight_bit_width=bits,
1460
+ weight_tensor=self.lm_head.weight.to(self.device),
1461
+ bias_tensor=None,
1462
+ in_features=self.lm_head.in_features,
1463
+ out_features=self.lm_head.out_features,
1464
+ bias=False,
1465
+ quantized_weight=self.transformer.word_embeddings.weight,
1466
+ quantized_weight_scale=self.transformer.word_embeddings.weight_scale,
1467
+ dtype=dtype,
1468
+ empty_init=empty_init,
1469
+ device=self.lm_head.weight.device,
1470
+ )
1471
+
1472
+ return self
models/chatglm/chatglm-6b-int4/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35828b49cf23cbae4c27788d4b04fc68c79a276300e09f14d72a49b0b738b4a9
3
+ size 3893083075
models/chatglm/chatglm-6b-int4/quantization.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear, Embedding
2
+ from torch.nn.parameter import Parameter
3
+ import torch.nn.functional as F
4
+
5
+ import os
6
+ import bz2
7
+ import torch
8
+ import base64
9
+ import ctypes
10
+ from transformers.utils import logging
11
+
12
+ from typing import List
13
+ from functools import partial
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+ try:
18
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
19
+
20
+ class Kernel:
21
+ def __init__(self, code: bytes, function_names: List[str]):
22
+ self.code = code
23
+ self._function_names = function_names
24
+ self._cmodule = LazyKernelCModule(self.code)
25
+
26
+ for name in self._function_names:
27
+ setattr(self, name, KernelFunction(self._cmodule, name))
28
+
29
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
30
+
31
+ kernels = Kernel(
32
+ bz2.decompress(base64.b64decode(quantization_code)),
33
+ [
34
+ "int4WeightCompression",
35
+ "int4WeightExtractionFloat",
36
+ "int4WeightExtractionHalf",
37
+ "int8WeightExtractionFloat",
38
+ "int8WeightExtractionHalf",
39
+ ],
40
+ )
41
+ except Exception as exception:
42
+ kernels = None
43
+ logger.warning("Failed to load cpm_kernels:", exception)
44
+
45
+
46
+ class W8A16Linear(torch.autograd.Function):
47
+ @staticmethod
48
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
49
+ ctx.inp_shape = inp.size()
50
+ ctx.weight_bit_width = weight_bit_width
51
+ out_features = quant_w.size(0)
52
+ inp = inp.contiguous().view(-1, inp.size(-1))
53
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
54
+ ctx.weight_shape = weight.size()
55
+ output = inp.mm(weight.t())
56
+ ctx.save_for_backward(inp, quant_w, scale_w)
57
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
58
+
59
+ @staticmethod
60
+ def backward(ctx, grad_output: torch.Tensor):
61
+ inp, quant_w, scale_w = ctx.saved_tensors
62
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
63
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
64
+ grad_input = grad_output.mm(weight)
65
+ grad_weight = grad_output.t().mm(inp)
66
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
67
+
68
+
69
+ class W8A16LinearCPU(torch.autograd.Function):
70
+ @staticmethod
71
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width, quantization_cache=None):
72
+ ctx.inp_shape = inp.size()
73
+ ctx.weight_bit_width = weight_bit_width
74
+ out_features = quant_w.size(0)
75
+ inp = inp.contiguous().view(-1, inp.size(-1))
76
+ weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache)
77
+ ctx.weight_shape = weight.size()
78
+ output = inp.mm(weight.t())
79
+ ctx.save_for_backward(inp, quant_w, scale_w)
80
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
81
+
82
+ @staticmethod
83
+ def backward(ctx, grad_output: torch.Tensor):
84
+ inp, quant_w, scale_w = ctx.saved_tensors
85
+ weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width)
86
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
87
+ grad_input = grad_output.mm(weight)
88
+ grad_weight = grad_output.t().mm(inp)
89
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
90
+
91
+
92
+ default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c")
93
+ default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg"
94
+ default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels_parallel.c")
95
+ default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWUzax5EAALXbgERwSX1mTwAAr/ff3kACNyXUbZYwBpoaNGIyAaADQwRSaVP9QoMg0A2oAPU0AEUkU9GaaKMaQB6gA09T1ARRKnpk0niaJkaaNDJ6g0DTIKVKfZ/g6v1Kem5LJLa0WmkukkuCIHUqWbtJGJMsCSQFiPEIYHgBIZDzR8R6REbYxIqD2Cu7lMkFoPu6LmHeOAy0GF83Tc40jgmTs4HnCe60QfJa2bDBZ0Y1lhgbiZjW8SNsAKCk42UOEdjWN3KoiCIYeQUCCKWIyHewhtSoInLKSG22l4jKM2ZDCVKtBm3OTYBl3jsVqMImtj7PQw7xKxLXQzwgJaPPgW1fRhrvPJICl4YFDYfNbkbBh5JDgrazFml50xEQQwQUjxNwE0IDSofLzSg7UNVKn+Rr1KErzBHUxBqdHRlXzqYsIa5K9Y0UuE2ugw3g5KYofm7AaGNTzJSMhcchhxdaU4JZ0F1UNgQ8XcGDguypqYza8yFaEoGgNRcLej+g2t0feGKFE5OY2PFluQ3q4HgycxlfvzHqo0KcM0JI8OKXtzayJFgsqC1NdUQVu8rChnA6FO3MFyGOoC9KO8ITPpYM5pRqTlczFkLES/4u5IpwoSCZtY8i"
96
+
97
+ cpu_kernels = None
98
+
99
+
100
+ class CPUKernel:
101
+ def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None, parallel_num=None):
102
+ self.load =False
103
+ self.int8WeightExtractionFloat = None
104
+ self.int4WeightExtractionFloat = None
105
+ self.int4WeightCompression = None
106
+ self.SetNumThreads = lambda x: x
107
+
108
+ try:
109
+ if not os.path.exists(default_cpu_kernel_code_path):
110
+ with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file:
111
+ code = default_cpu_kernel_code
112
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
113
+ file.write(cpu_quantization_code)
114
+
115
+ if not os.path.exists(default_cpu_parallel_kernel_code_path):
116
+ with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file:
117
+ code = default_cpu_parallel_kernel_code
118
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
119
+ file.write(cpu_quantization_code)
120
+
121
+ except Exception as ex:
122
+ print("Error when generating default cpu kernel code(can be ignored when using custom kernels).")
123
+
124
+ if compile_parallel_kernel is None:
125
+ compile_parallel_kernel = bool(int(os.cpu_count()) >= 4)
126
+
127
+ if compile_parallel_kernel and source_code == default_cpu_kernel_code_path:
128
+ source_code = default_cpu_parallel_kernel_code_path
129
+
130
+ kernels = None
131
+
132
+ if (not kernel_file) or (not os.path.exists(kernel_file)):
133
+ print("No compiled kernel found.")
134
+ try:
135
+ if os.path.exists(source_code):
136
+ print("Compiling kernels :", source_code)
137
+ kernel_file = source_code[:-2] + ".so"
138
+
139
+ if compile_parallel_kernel:
140
+ compile_command = "gcc -O3 -fPIC -pthread -fopenmp -std=c99 {} -shared -o {}".format(source_code, kernel_file)
141
+ print("Compiling", compile_command)
142
+ exit_state = os.system(compile_command)
143
+ if not exit_state:
144
+ try:
145
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
146
+ print("Load kernel :", kernel_file)
147
+ except:
148
+ kernels = None
149
+ print("Load parallel cpu kernel failed, using default cpu kernel code:")
150
+ import traceback
151
+ exception = traceback.format_exc()
152
+ print(exception)
153
+ else:
154
+ print("Compile default cpu kernel failed, using default cpu kernel code.")
155
+
156
+ if kernels is None: # adjust config, use default cpu kernel
157
+ compile_parallel_kernel = False
158
+ source_code = default_cpu_kernel_code_path
159
+ kernel_file = source_code[:-2] + ".so"
160
+
161
+ if kernels is None:
162
+ compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
163
+ print("Compiling", compile_command)
164
+ exit_state = os.system(compile_command)
165
+ if not exit_state:
166
+ try:
167
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
168
+ print("Load kernel :", kernel_file)
169
+ except:
170
+ kernels = None
171
+ print("Load default cpu kernel failed:")
172
+ import traceback
173
+ exception = traceback.format_exc()
174
+ print(exception)
175
+ else:
176
+ print("Compile default cpu kernel failed.")
177
+ else:
178
+ print("Kernel source code not found.")
179
+ return
180
+ except:
181
+ print("Failed to build cpu kernel:")
182
+ import traceback
183
+ exception = traceback.format_exc()
184
+ print(exception)
185
+ return
186
+ else:
187
+ try:
188
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
189
+ print("Load kernel :", kernel_file)
190
+ except:
191
+ kernels = None
192
+ print("Load custom cpu kernel failed:")
193
+ import traceback
194
+ exception = traceback.format_exc()
195
+ print(exception)
196
+
197
+ if kernels is not None:
198
+ self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float
199
+ self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float
200
+ self.int4WeightCompression = kernels.compress_int4_weight
201
+ if compile_parallel_kernel:
202
+ try:
203
+ self.SetNumThreads = kernels.set_num_threads
204
+ except:
205
+ print("No set_num_threads() found in kernel.")
206
+ self.load = True
207
+ else:
208
+ print("Failed to load kernel.")
209
+ return
210
+
211
+ if compile_parallel_kernel:
212
+ if parallel_num is None:
213
+ parallel_num = max(os.cpu_count() // 2, 1)
214
+ print("Setting CPU quantization kernel threads to", parallel_num)
215
+ if parallel_num < 4:
216
+ print("Parallel kernel is not recommended when parallel num < 4.")
217
+ self.SetNumThreads(parallel_num)
218
+
219
+ self.parallel_num = parallel_num
220
+
221
+
222
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
223
+ """compress weight on cpu or cuda to int4"""
224
+ if weight.device == torch.device("cpu"):
225
+ assert isinstance(cpu_kernels, CPUKernel)
226
+ n, m = weight.size(0), weight.size(1)
227
+ assert m % 2 == 0
228
+ m = m // 2
229
+ out = torch.empty(n, m, dtype=torch.int8, device="cpu")
230
+ cpu_kernels.int4WeightCompression(
231
+ ctypes.c_void_p(weight.data_ptr()),
232
+ ctypes.c_void_p(out.data_ptr()),
233
+ ctypes.c_int32(n),
234
+ ctypes.c_int32(m)
235
+ )
236
+ return out
237
+ else:
238
+ with torch.cuda.device(weight.device):
239
+ n, m = weight.size(0), weight.size(1)
240
+ assert m % 2 == 0
241
+ m = m // 2
242
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
243
+ stream = torch.cuda.current_stream()
244
+
245
+ gridDim = (n, 1, 1)
246
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
247
+
248
+ kernels.int4WeightCompression(
249
+ gridDim,
250
+ blockDim,
251
+ 0,
252
+ stream,
253
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
254
+ )
255
+ return out
256
+
257
+
258
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
259
+ if source_bit_width == 8:
260
+ func = kernels.int8WeightExtractionHalf
261
+ elif source_bit_width == 4:
262
+ func = kernels.int4WeightExtractionHalf
263
+ else:
264
+ assert False, "Unsupported bit-width"
265
+
266
+ with torch.cuda.device(weight.device):
267
+ n, m = weight.size(0), weight.size(1)
268
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
269
+ stream = torch.cuda.current_stream()
270
+
271
+ gridDim = (n, 1, 1)
272
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
273
+
274
+ func(
275
+ gridDim,
276
+ blockDim,
277
+ 0,
278
+ stream,
279
+ [
280
+ ctypes.c_void_p(weight.data_ptr()),
281
+ ctypes.c_void_p(scale_list.data_ptr()),
282
+ ctypes.c_void_p(out.data_ptr()),
283
+ ctypes.c_int32(n),
284
+ ctypes.c_int32(m),
285
+ ],
286
+ )
287
+ return out
288
+
289
+
290
+ def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int, quantization_cache=None):
291
+ """extract weight on cpu to float32"""
292
+ if source_bit_width == 8:
293
+ func = cpu_kernels.int8WeightExtractionFloat
294
+ elif source_bit_width == 4:
295
+ func = cpu_kernels.int4WeightExtractionFloat
296
+ else:
297
+ assert False, "Unsupported bit-width"
298
+
299
+ n, m = weight.size(0), weight.size(1)
300
+
301
+ if quantization_cache is not None:
302
+ out = quantization_cache
303
+ func(
304
+ ctypes.c_void_p(weight.data_ptr()),
305
+ ctypes.c_void_p(scale_list.data_ptr()),
306
+ ctypes.c_void_p(out.data_ptr()),
307
+ ctypes.c_int32(n),
308
+ ctypes.c_int32(m)
309
+ )
310
+ return out.tensor
311
+ else:
312
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu")
313
+ func(
314
+ ctypes.c_void_p(weight.data_ptr()),
315
+ ctypes.c_void_p(scale_list.data_ptr()),
316
+ ctypes.c_void_p(out.data_ptr()),
317
+ ctypes.c_int32(n),
318
+ ctypes.c_int32(m)
319
+ )
320
+ return out
321
+
322
+
323
+ class CacheTensor():
324
+ def __init__(self, *args, **kwargs):
325
+ self.tensor = torch.empty(*args, **kwargs)
326
+
327
+ def to(self, *args, **kwargs):
328
+ self.tensor = self.tensor.to(*args, **kwargs)
329
+
330
+ def data_ptr(self):
331
+ return self.tensor.data_ptr()
332
+
333
+
334
+ class QuantizedLinear(Linear):
335
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None, quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs):
336
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
337
+ self.weight_bit_width = weight_bit_width
338
+ self.quantization_cache = quantization_cache
339
+
340
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
341
+ del self.weight
342
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
343
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
344
+ else:
345
+ shape = self.weight.shape
346
+ del self.weight
347
+
348
+ if weight_tensor is None or empty_init:
349
+ self.weight = torch.empty(
350
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
351
+ )
352
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
353
+ else:
354
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(kwargs["dtype"])
355
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
356
+ if weight_bit_width == 4:
357
+ self.weight = compress_int4_weight(self.weight)
358
+
359
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
360
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
361
+
362
+ if bias_tensor is not None:
363
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
364
+ else:
365
+ self.bias = None
366
+
367
+ def reset_parameters(self):
368
+ """To accelerate initialization"""
369
+ pass
370
+
371
+ def forward(self, input):
372
+ if self.weight.device == torch.device("cpu"):
373
+ output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width, self.quantization_cache)
374
+ else:
375
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
376
+ if self.bias is not None:
377
+ output = output + self.bias
378
+ return output
379
+
380
+ def _apply(self, fn):
381
+ self_obj = super()._apply(fn)
382
+ if self.quantization_cache is not None:
383
+ self.quantization_cache.to(self_obj.weight.device)
384
+ self.quantization_cache.to(self_obj.weight_scale.dtype)
385
+ return self_obj
386
+
387
+
388
+ class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init
389
+ def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None, empty_init=False, *args, **kwargs):
390
+ super(QuantizedEmbedding, self).__init__(*args, **kwargs)
391
+ self.weight_bit_width = weight_bit_width
392
+
393
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
394
+ del self.weight
395
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
396
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
397
+ else:
398
+ shape = self.weight.shape
399
+ del self.weight
400
+
401
+ if weight_tensor is None or empty_init:
402
+ self.weight = torch.empty(
403
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
404
+ )
405
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
406
+ else:
407
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
408
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
409
+ if weight_bit_width == 4:
410
+ self.weight = compress_int4_weight(self.weight)
411
+
412
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
413
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
414
+
415
+ def forward(self, input):
416
+ if self.weight.device == torch.device("cpu"):
417
+ original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
418
+ else:
419
+ original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
420
+ output = F.embedding(
421
+ input, original_weight, self.padding_idx, self.max_norm,
422
+ self.norm_type, self.scale_grad_by_freq, self.sparse
423
+ )
424
+ return output
425
+
426
+
427
+ def load_cpu_kernel(**kwargs):
428
+ global cpu_kernels
429
+ cpu_kernels = CPUKernel(**kwargs)
430
+ assert cpu_kernels.load
431
+
432
+
433
+ def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs):
434
+ """Replace fp16 linear with quantized linear"""
435
+
436
+ query_key_value_quantization_cache = None
437
+ dense_quantization_cache = None
438
+ dense_h_to_4h_quantization_cache = None
439
+ dense_4h_to_h_quantization_cache = None
440
+
441
+ try:
442
+ load_cpu_kernel(**kwargs)
443
+ except:
444
+ if kernels is None: # CUDA kernels failed
445
+ print("Cannot load cpu or cuda kernel, quantization failed:")
446
+ assert kernels is not None
447
+ print("Cannot load cpu kernel, don't use quantized model on cpu.")
448
+
449
+ current_device = model.device
450
+
451
+ if model.device == torch.device("cpu"):
452
+ dtype=torch.float32
453
+ else:
454
+ dtype = torch.half
455
+
456
+ QuantizedLinearWithPara = partial(
457
+ QuantizedLinear,
458
+ weight_bit_width=weight_bit_width,
459
+ bias=True,
460
+ dtype=dtype,
461
+ empty_init=empty_init
462
+ )
463
+
464
+ if use_quantization_cache:
465
+ print("Using quantization cache")
466
+ layer = model.layers[0]
467
+ weight = layer.attention.query_key_value.weight
468
+ n, m = weight.size(0), weight.size(1)
469
+ query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
470
+ weight = layer.attention.dense.weight
471
+ n, m = weight.size(0), weight.size(1)
472
+ dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
473
+ weight = layer.mlp.dense_h_to_4h.weight
474
+ n, m = weight.size(0), weight.size(1)
475
+ dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
476
+ weight = layer.mlp.dense_4h_to_h.weight
477
+ n, m = weight.size(0), weight.size(1)
478
+ dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
479
+
480
+ print("Applying quantization to glm layers")
481
+
482
+ for layer in model.layers:
483
+ layer.attention.query_key_value = QuantizedLinearWithPara(
484
+ weight_tensor=layer.attention.query_key_value.weight.to(current_device),
485
+ bias_tensor=layer.attention.query_key_value.bias,
486
+ in_features=layer.attention.query_key_value.in_features,
487
+ out_features=layer.attention.query_key_value.out_features,
488
+ device=layer.attention.query_key_value.weight.device,
489
+ quantization_cache=query_key_value_quantization_cache
490
+ )
491
+ layer.attention.dense = QuantizedLinearWithPara(
492
+ weight_tensor=layer.attention.dense.weight.to(current_device),
493
+ bias_tensor=layer.attention.dense.bias,
494
+ in_features=layer.attention.dense.in_features,
495
+ out_features=layer.attention.dense.out_features,
496
+ device=layer.attention.dense.weight.device,
497
+ quantization_cache=dense_quantization_cache
498
+ )
499
+ layer.mlp.dense_h_to_4h = QuantizedLinearWithPara(
500
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device),
501
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
502
+ in_features=layer.mlp.dense_h_to_4h.in_features,
503
+ out_features=layer.mlp.dense_h_to_4h.out_features,
504
+ device=layer.mlp.dense_h_to_4h.weight.device,
505
+ quantization_cache=dense_h_to_4h_quantization_cache
506
+ )
507
+ layer.mlp.dense_4h_to_h = QuantizedLinearWithPara(
508
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device),
509
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
510
+ in_features=layer.mlp.dense_4h_to_h.in_features,
511
+ out_features=layer.mlp.dense_4h_to_h.out_features,
512
+ device=layer.mlp.dense_4h_to_h.weight.device,
513
+ quantization_cache=dense_4h_to_h_quantization_cache
514
+ )
515
+ return model
models/chatglm/chatglm-6b-int4/quantization_kernels.c ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ void compress_int4_weight(void *weight, void *out, int n, int m)
2
+ {
3
+ for(int i=0;i<n*m;i++)
4
+ {
5
+ (*(unsigned char*)(out)) = ((*(unsigned char*)(weight)) << 4);
6
+ weight += sizeof(char);
7
+ (*(unsigned char*)(out)) |= ((*(unsigned char*)(weight)) & 15);
8
+ weight += sizeof(char);
9
+ out += sizeof(char);
10
+ }
11
+ }
12
+
13
+ void extract_int8_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
14
+ {
15
+ for(int i=0;i<n;i++)
16
+ for(int j=0;j<m;j++)
17
+ (*(float*)(out + sizeof(float) * (i * m + j))) = (*(float*)(scale_list + sizeof(float) * i)) * (*(char*)(weight + sizeof(char) * (i * m + j)));
18
+ }
19
+
20
+ void extract_int4_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
21
+ {
22
+ for(int i=0;i<n;i++)
23
+ {
24
+ for(int j=0;j<m;j++)
25
+ {
26
+ (*(float*)(out)) = (*(float*)(scale_list)) * ((*(char*)(weight)) >> 4);
27
+ out += sizeof(float);
28
+ (*(float*)(out)) = (*(float*)(scale_list)) * (((char)((*(unsigned char*)(weight)) << 4))>> 4);
29
+ out += sizeof(float);
30
+ weight += sizeof(char);
31
+ }
32
+ scale_list += sizeof(float);
33
+ }
34
+ }
models/chatglm/chatglm-6b-int4/quantization_kernels.so ADDED
Binary file (99.9 kB). View file
 
models/chatglm/chatglm-6b-int4/quantization_kernels_parallel.c ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <omp.h>
2
+
3
+ void set_num_threads(int n_threads)
4
+ {
5
+ omp_set_num_threads(n_threads);
6
+ }
7
+
8
+ int get_num_threads()
9
+ {
10
+ return omp_get_num_threads();
11
+ }
12
+
13
+
14
+ void compress_int4_weight(void *weight, void *out, int n, int m)
15
+ {
16
+ #pragma omp parallel for
17
+ for(int i=0;i<n;i++)
18
+ {
19
+ for(int j=0;j<m;j++)
20
+ {
21
+ (*(unsigned char*)(out + sizeof(unsigned char) * (i * m + j))) = ((*(unsigned char*)(weight + sizeof(unsigned char) * (i * (m << 1) + (j << 1)))) << 4);
22
+ (*(unsigned char*)(out + sizeof(unsigned char) * (i * m + j))) |= (((*(unsigned char*)(weight + sizeof(unsigned char) * (i * (m << 1) + ((j << 1) | 1)))) & 15));
23
+ }
24
+ }
25
+ }
26
+
27
+
28
+ void extract_int8_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
29
+ {
30
+ #pragma omp parallel for
31
+ for(int i=0;i<n;i++)
32
+ {
33
+ for(int j=0;j<m;j++)
34
+ (*(float*)(out + sizeof(float) * (i * m + j))) = (*(float*)(scale_list + sizeof(float) * i)) * (*(char*)(weight + sizeof(char) * (i * m + j)));
35
+ }
36
+ }
37
+
38
+
39
+ void extract_int4_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
40
+ {
41
+ #pragma omp parallel for
42
+ for(int i=0;i<n;i++)
43
+ {
44
+ for(int j=0;j<m;j++)
45
+ {
46
+ (*(float*)(out + sizeof(float) * (i * (m << 1) + (j << 1)))) = (*(float*)(scale_list + sizeof(float) * i)) * ((*(char*)(weight + sizeof(char) * (i * m + j))) >> 4);
47
+ (*(float*)(out + sizeof(float) * (i * (m << 1) + ((j << 1) | 1)))) = (*(float*)(scale_list + sizeof(float) * i)) * (((char)((*(unsigned char*)(weight + sizeof(char) * (i * m + j))) << 4))>> 4);
48
+ }
49
+ }
50
+ }
models/chatglm/chatglm-6b-int4/quantization_kernels_parallel.so ADDED
Binary file (103 kB). View file
 
models/chatglm/chatglm-6b-int4/tokenization_chatglm.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ from typing import List, Optional, Union
3
+ import os
4
+
5
+ from transformers.tokenization_utils import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+ from typing import Dict
9
+ import sentencepiece as spm
10
+ import numpy as np
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
15
+ "THUDM/chatglm-6b": 2048,
16
+ }
17
+
18
+
19
+ class TextTokenizer:
20
+ def __init__(self, model_path):
21
+ self.sp = spm.SentencePieceProcessor()
22
+ self.sp.Load(model_path)
23
+ self.num_tokens = self.sp.vocab_size()
24
+
25
+ def encode(self, text):
26
+ return self.sp.EncodeAsIds(text)
27
+
28
+ def decode(self, ids: List[int]):
29
+ return self.sp.DecodeIds(ids)
30
+
31
+ def tokenize(self, text):
32
+ return self.sp.EncodeAsPieces(text)
33
+
34
+ def convert_tokens_to_ids(self, tokens):
35
+ return [self.sp.PieceToId(token) for token in tokens]
36
+
37
+ def convert_token_to_id(self, token):
38
+ return self.sp.PieceToId(token)
39
+
40
+ def convert_id_to_token(self, idx):
41
+ return self.sp.IdToPiece(idx)
42
+
43
+ def __len__(self):
44
+ return self.num_tokens
45
+
46
+
47
+ class SPTokenizer:
48
+ def __init__(
49
+ self,
50
+ vocab_file,
51
+ num_image_tokens=20000,
52
+ max_blank_length=80,
53
+ byte_fallback=True,
54
+ ):
55
+ assert vocab_file is not None
56
+ self.vocab_file = vocab_file
57
+ self.num_image_tokens = num_image_tokens
58
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
59
+ self.max_blank_length = max_blank_length
60
+ self.byte_fallback = byte_fallback
61
+ self.text_tokenizer = TextTokenizer(vocab_file)
62
+
63
+ def _get_text_tokenizer(self):
64
+ return self.text_tokenizer
65
+
66
+ @staticmethod
67
+ def get_blank_token(length: int):
68
+ assert length >= 2
69
+ return f"<|blank_{length}|>"
70
+
71
+ @staticmethod
72
+ def get_tab_token():
73
+ return f"<|tab|>"
74
+
75
+ @property
76
+ def num_text_tokens(self):
77
+ return self.text_tokenizer.num_tokens
78
+
79
+ @property
80
+ def num_tokens(self):
81
+ return self.num_image_tokens + self.num_text_tokens
82
+
83
+ @staticmethod
84
+ def _encode_whitespaces(text: str, max_len: int = 80):
85
+ text = text.replace("\t", SPTokenizer.get_tab_token())
86
+ for i in range(max_len, 1, -1):
87
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
88
+ return text
89
+
90
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
91
+ if linebreak:
92
+ text = text.replace("\n", "<n>")
93
+ if whitespaces:
94
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
95
+ return text
96
+
97
+ def encode(
98
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
99
+ ) -> List[int]:
100
+ """
101
+ @param text: Text to encode.
102
+ @param linebreak: Whether to encode newline (\n) in text.
103
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
104
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
105
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
106
+ """
107
+ text = self._preprocess(text, linebreak, whitespaces)
108
+ if not add_dummy_prefix:
109
+ text = "<n>" + text
110
+ tmp = self._get_text_tokenizer().encode(text)
111
+ tokens = [x + self.num_image_tokens for x in tmp]
112
+ return tokens if add_dummy_prefix else tokens[2:]
113
+
114
+ def decode(self, text_ids: List[int]) -> str:
115
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
116
+ ids = [_id for _id in ids if _id >= 0]
117
+ text = self._get_text_tokenizer().decode(ids)
118
+ text = text.replace("<n>", "\n")
119
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
120
+ for i in range(2, self.max_blank_length + 1):
121
+ text = text.replace(self.get_blank_token(i), " " * i)
122
+ return text
123
+
124
+ def tokenize(
125
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
126
+ ) -> List[str]:
127
+ """
128
+ @param text: Text to encode.
129
+ @param linebreak: Whether to encode newline (\n) in text.
130
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
131
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
132
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
133
+ """
134
+ text = self._preprocess(text, linebreak, whitespaces)
135
+ if not add_dummy_prefix:
136
+ text = "<n>" + text
137
+ tokens = self._get_text_tokenizer().tokenize(text)
138
+ return tokens if add_dummy_prefix else tokens[2:]
139
+
140
+ def __getitem__(self, x: Union[int, str]):
141
+ if isinstance(x, int):
142
+ if x < self.num_image_tokens:
143
+ return "<image_{}>".format(x)
144
+ else:
145
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
146
+ elif isinstance(x, str):
147
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
148
+ return int(x[7:-1])
149
+ else:
150
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
151
+ else:
152
+ raise ValueError("The key should be str or int.")
153
+
154
+
155
+ class ChatGLMTokenizer(PreTrainedTokenizer):
156
+ """
157
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
158
+
159
+ Args:
160
+ vocab_file (`str`):
161
+ Path to the vocabulary file.
162
+ """
163
+
164
+ vocab_files_names = {"vocab_file": "ice_text.model"}
165
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
166
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
167
+
168
+ def __init__(
169
+ self,
170
+ vocab_file,
171
+ do_lower_case=False,
172
+ remove_space=False,
173
+ bos_token='<sop>',
174
+ eos_token='<eop>',
175
+ end_token='</s>',
176
+ mask_token='[MASK]',
177
+ gmask_token='[gMASK]',
178
+ padding_side="left",
179
+ pad_token="<pad>",
180
+ unk_token="<unk>",
181
+ num_image_tokens=20000,
182
+ **kwargs
183
+ ) -> None:
184
+ super().__init__(
185
+ do_lower_case=do_lower_case,
186
+ remove_space=remove_space,
187
+ padding_side=padding_side,
188
+ bos_token=bos_token,
189
+ eos_token=eos_token,
190
+ end_token=end_token,
191
+ mask_token=mask_token,
192
+ gmask_token=gmask_token,
193
+ pad_token=pad_token,
194
+ unk_token=unk_token,
195
+ num_image_tokens=num_image_tokens,
196
+ **kwargs
197
+ )
198
+
199
+ self.do_lower_case = do_lower_case
200
+ self.remove_space = remove_space
201
+ self.vocab_file = vocab_file
202
+
203
+ self.bos_token = bos_token
204
+ self.eos_token = eos_token
205
+ self.end_token = end_token
206
+ self.mask_token = mask_token
207
+ self.gmask_token = gmask_token
208
+
209
+ self.sp_tokenizer = SPTokenizer(vocab_file, num_image_tokens=num_image_tokens)
210
+
211
+ """ Initialisation """
212
+
213
+ @property
214
+ def gmask_token_id(self) -> Optional[int]:
215
+ if self.gmask_token is None:
216
+ return None
217
+ return self.convert_tokens_to_ids(self.gmask_token)
218
+
219
+ @property
220
+ def end_token_id(self) -> Optional[int]:
221
+ """
222
+ `Optional[int]`: Id of the end of context token in the vocabulary. Returns `None` if the token has not been
223
+ set.
224
+ """
225
+ if self.end_token is None:
226
+ return None
227
+ return self.convert_tokens_to_ids(self.end_token)
228
+
229
+ @property
230
+ def vocab_size(self):
231
+ """ Returns vocab size """
232
+ return self.sp_tokenizer.num_tokens
233
+
234
+ def get_vocab(self):
235
+ """ Returns vocab as a dict """
236
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
237
+ vocab.update(self.added_tokens_encoder)
238
+ return vocab
239
+
240
+ def preprocess_text(self, inputs):
241
+ if self.remove_space:
242
+ outputs = " ".join(inputs.strip().split())
243
+ else:
244
+ outputs = inputs
245
+
246
+ if self.do_lower_case:
247
+ outputs = outputs.lower()
248
+
249
+ return outputs
250
+
251
+ def _tokenize(self, text, **kwargs):
252
+ """ Returns a tokenized string. """
253
+ text = self.preprocess_text(text)
254
+
255
+ seq = self.sp_tokenizer.tokenize(text)
256
+
257
+ return seq
258
+
259
+ def _decode(
260
+ self,
261
+ token_ids: Union[int, List[int]],
262
+ skip_special_tokens: bool = False,
263
+ clean_up_tokenization_spaces: bool = True,
264
+ **kwargs
265
+ ) -> str:
266
+ if isinstance(token_ids, int):
267
+ token_ids = [token_ids]
268
+ if len(token_ids) == 0:
269
+ return ""
270
+ if self.pad_token_id in token_ids: # remove pad
271
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
272
+ return self.sp_tokenizer.decode(token_ids)
273
+
274
+ def _convert_token_to_id(self, token):
275
+ """ Converts a token (str) in an id using the vocab. """
276
+ return self.sp_tokenizer[token]
277
+
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.sp_tokenizer[index]
281
+
282
+ def save_vocabulary(self, save_directory, filename_prefix=None):
283
+ """
284
+ Save the vocabulary and special tokens file to a directory.
285
+
286
+ Args:
287
+ save_directory (`str`):
288
+ The directory in which to save the vocabulary.
289
+ filename_prefix (`str`, *optional*):
290
+ An optional prefix to add to the named of the saved files.
291
+
292
+ Returns:
293
+ `Tuple(str)`: Paths to the files saved.
294
+ """
295
+ if os.path.isdir(save_directory):
296
+ vocab_file = os.path.join(
297
+ save_directory, self.vocab_files_names["vocab_file"]
298
+ )
299
+ else:
300
+ vocab_file = save_directory
301
+
302
+ with open(self.vocab_file, 'rb') as fin:
303
+ proto_str = fin.read()
304
+
305
+ with open(vocab_file, "wb") as writer:
306
+ writer.write(proto_str)
307
+
308
+ return (vocab_file,)
309
+
310
+ def build_inputs_with_special_tokens(
311
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
312
+ ) -> List[int]:
313
+ """
314
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
315
+ adding special tokens. A BERT sequence has the following format:
316
+
317
+ - single sequence: `[CLS] X [SEP]`
318
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
319
+
320
+ Args:
321
+ token_ids_0 (`List[int]`):
322
+ List of IDs to which the special tokens will be added.
323
+ token_ids_1 (`List[int]`, *optional*):
324
+ Optional second list of IDs for sequence pairs.
325
+
326
+ Returns:
327
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
328
+ """
329
+ gmask_id = self.sp_tokenizer[self.gmask_token]
330
+ eos_id = self.sp_tokenizer[self.eos_token]
331
+ token_ids_0 = token_ids_0 + [gmask_id, self.sp_tokenizer[self.bos_token]]
332
+ if token_ids_1 is not None:
333
+ token_ids_0 = token_ids_0 + token_ids_1 + [eos_id]
334
+ return token_ids_0
335
+
336
+ def _pad(
337
+ self,
338
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
339
+ max_length: Optional[int] = None,
340
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
341
+ pad_to_multiple_of: Optional[int] = None,
342
+ return_attention_mask: Optional[bool] = None,
343
+ ) -> dict:
344
+ """
345
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
346
+
347
+ Args:
348
+ encoded_inputs:
349
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
350
+ max_length: maximum length of the returned list and optionally padding length (see below).
351
+ Will truncate by taking into account the special tokens.
352
+ padding_strategy: PaddingStrategy to use for padding.
353
+
354
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
355
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
356
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
357
+ The tokenizer padding sides are defined in self.padding_side:
358
+
359
+ - 'left': pads on the left of the sequences
360
+ - 'right': pads on the right of the sequences
361
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
362
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
363
+ `>= 7.5` (Volta).
364
+ return_attention_mask:
365
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
366
+ """
367
+ # Load from model defaults
368
+ bos_token_id = self.sp_tokenizer[self.bos_token]
369
+ mask_token_id = self.sp_tokenizer[self.mask_token]
370
+ gmask_token_id = self.sp_tokenizer[self.gmask_token]
371
+ assert self.padding_side == "left"
372
+
373
+ required_input = encoded_inputs[self.model_input_names[0]]
374
+ seq_length = len(required_input)
375
+
376
+ if padding_strategy == PaddingStrategy.LONGEST:
377
+ max_length = len(required_input)
378
+
379
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
380
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
381
+
382
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
383
+
384
+ # Initialize attention mask if not present.
385
+ if max_length is not None:
386
+ if "attention_mask" not in encoded_inputs:
387
+ if bos_token_id in required_input:
388
+ context_length = required_input.index(bos_token_id)
389
+ else:
390
+ context_length = seq_length
391
+ attention_mask = np.ones((1, seq_length, seq_length))
392
+ attention_mask = np.tril(attention_mask)
393
+ attention_mask[:, :, :context_length] = 1
394
+ attention_mask = np.bool_(attention_mask < 0.5)
395
+ encoded_inputs["attention_mask"] = attention_mask
396
+
397
+ if "position_ids" not in encoded_inputs:
398
+ if bos_token_id in required_input:
399
+ context_length = required_input.index(bos_token_id)
400
+ else:
401
+ context_length = seq_length
402
+ position_ids = np.arange(seq_length, dtype=np.int64)
403
+ mask_token = mask_token_id if mask_token_id in required_input else gmask_token_id
404
+ if mask_token in required_input:
405
+ mask_position = required_input.index(mask_token)
406
+ position_ids[context_length:] = mask_position
407
+ block_position_ids = np.concatenate(
408
+ [np.zeros(context_length, dtype=np.int64),
409
+ np.arange(1, seq_length - context_length + 1, dtype=np.int64)])
410
+ encoded_inputs["position_ids"] = np.stack([position_ids, block_position_ids], axis=0)
411
+
412
+ if needs_to_be_padded:
413
+ difference = max_length - len(required_input)
414
+
415
+ if "attention_mask" in encoded_inputs:
416
+ encoded_inputs["attention_mask"] = np.pad(encoded_inputs["attention_mask"],
417
+ pad_width=[(0, 0), (difference, 0), (difference, 0)],
418
+ mode='constant', constant_values=True)
419
+ if "token_type_ids" in encoded_inputs:
420
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
421
+ "token_type_ids"
422
+ ]
423
+ if "special_tokens_mask" in encoded_inputs:
424
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
425
+ if "position_ids" in encoded_inputs:
426
+ encoded_inputs["position_ids"] = np.pad(encoded_inputs["position_ids"],
427
+ pad_width=[(0, 0), (difference, 0)])
428
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
429
+
430
+ return encoded_inputs
models/chatglm/chatglm-6b-int4/tokenizer_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-6b-int4",
3
+ "bos_token": "<sop>",
4
+ "eos_token": "<eop>",
5
+ "end_token": "</s>",
6
+ "gmask_token": "[gMASK]",
7
+ "mask_token": "[MASK]",
8
+ "pad_token": "<pad>",
9
+ "unk_token": "<unk>",
10
+ "remove_space": false,
11
+ "do_lower_case": false,
12
+ "tokenizer_class": "ChatGLMTokenizer",
13
+ "num_image_tokens": 0,
14
+ "auto_map": {
15
+ "AutoTokenizer": [
16
+ "tokenization_chatglm.ChatGLMTokenizer",
17
+ null
18
+ ]
19
+ }
20
+ }
models/chatglm/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ protobuf
2
+ transformers==4.27.1
3
+ cpm_kernels
4
+ torch>=1.10
5
+ gradio
6
+ mdtex2html
7
+ sentencepiece
8
+ accelerate
models/chatglm/test.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import signal
4
+ import time
5
+ from transformers import AutoTokenizer, AutoModel
6
+ from multi_input import MultiInputInCmd
7
+
8
+ if __name__ == "__main__":
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained("E:\ProjectEX\LLM\ChatGLM-6B\chatglm-6b-int4", trust_remote_code=True)
11
+ model = AutoModel.from_pretrained("E:\ProjectEX\LLM\ChatGLM-6B\chatglm-6b-int4", trust_remote_code=True).float()
12
+ model = model.quantize(bits=4,
13
+ kernel_file="E:\ProjectEX\LLM\ChatGLM-6B\chatglm-6b-int4\quantization_kernels_parallel.so")
14
+ model = model.eval()
15
+
16
+ os_name = platform.system()
17
+ clear_command = 'cls' if os_name == 'Windows' else 'clear'
18
+ stop_stream = False
19
+
20
+
21
+ def build_prompt(history):
22
+ prompt = "欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序"
23
+ for query, response in history:
24
+ prompt += f"\n\n用户:{query}"
25
+ prompt += f"\n\nChatGLM-6B:{response}"
26
+ return prompt
27
+
28
+
29
+ def signal_handler(signal, frame):
30
+ global stop_stream
31
+ stop_stream = True
32
+
33
+
34
+ def main():
35
+ history = []
36
+ global stop_stream
37
+ print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序")
38
+ while True:
39
+
40
+ # query = input("\n用户:")
41
+
42
+ input_fun = MultiInputInCmd("\n用户:")
43
+ all_input_lines = input_fun.run()
44
+ # handle as normal message
45
+ query = ''
46
+ for index in range(len(all_input_lines)):
47
+ if index == len(all_input_lines) - 1:
48
+ query = query + all_input_lines[index]
49
+ else:
50
+ query = query + all_input_lines[index] + '\n'
51
+
52
+ if query.strip() == "stop":
53
+ break
54
+ if query.strip() == "clear":
55
+ history = []
56
+ os.system(clear_command)
57
+ print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序")
58
+ continue
59
+ last_index = 0
60
+ start = time.time()
61
+ for response, history in model.stream_chat(tokenizer, query, history=history):
62
+ if stop_stream:
63
+ stop_stream = False
64
+ break
65
+ else:
66
+ print(response[last_index:], end='', flush=True)
67
+ last_index = len(response)
68
+ signal.signal(signal.SIGINT, signal_handler)
69
+ print((time.time() - start) / last_index)
70
+ print('')
71
+
72
+ main()
models/chatglm/utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict, Tuple, Union, Optional
3
+
4
+ from torch.nn import Module
5
+ from transformers import AutoModel
6
+
7
+
8
+ def auto_configure_device_map(num_gpus: int) -> Dict[str, int]:
9
+ # transformer.word_embeddings 占用1层
10
+ # transformer.final_layernorm 和 lm_head 占用1层
11
+ # transformer.layers 占用 28 层
12
+ # 总共30层分配到num_gpus张卡上
13
+ num_trans_layers = 28
14
+ per_gpu_layers = 30 / num_gpus
15
+
16
+ # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError
17
+ # windows下 model.device 会被设置成 transformer.word_embeddings.device
18
+ # linux下 model.device 会被设置成 lm_head.device
19
+ # 在调用chat或者stream_chat时,input_ids会被放到model.device上
20
+ # 如果transformer.word_embeddings.device和model.device不同,则会导致RuntimeError
21
+ # 因此这里将transformer.word_embeddings,transformer.final_layernorm,lm_head都放到第一张卡上
22
+ device_map = {'transformer.word_embeddings': 0,
23
+ 'transformer.final_layernorm': 0, 'lm_head': 0}
24
+
25
+ used = 2
26
+ gpu_target = 0
27
+ for i in range(num_trans_layers):
28
+ if used >= per_gpu_layers:
29
+ gpu_target += 1
30
+ used = 0
31
+ assert gpu_target < num_gpus
32
+ device_map[f'transformer.layers.{i}'] = gpu_target
33
+ used += 1
34
+
35
+ return device_map
36
+
37
+
38
+ def load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2,
39
+ device_map: Optional[Dict[str, int]] = None, **kwargs) -> Module:
40
+ if num_gpus < 2 and device_map is None:
41
+ model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half().cuda()
42
+ else:
43
+ from accelerate import dispatch_model
44
+
45
+ model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half()
46
+
47
+ if device_map is None:
48
+ device_map = auto_configure_device_map(num_gpus)
49
+
50
+ model = dispatch_model(model, device_map=device_map)
51
+
52
+ return model
53
+
54
+
models/chinese_chat_llama/chinese-chat-llama-7b-int4/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/chinese_chat_llama/chinese-chat-llama-7b-int4/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ How to use: https://github.com/ydli-ai/Chinese-ChatLLaMA
models/chinese_chat_llama/chinese-chat-llama-7b-int4/chatllama-ggml-q4_0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83ad6e9c2746760f9f1aa9be81754328d44bb9db4667b5aec76429d9705fca5f
3
+ size 4212859520
models/chinese_chat_llama/chinese-chat-llama-7b-int4/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
models/gpt4free/.github/FUNDING.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [onlp]
4
+ patreon: xtekky
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: xtekky
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: tekky
10
+ issuehunt: xtekky
11
+ otechie: # Replace with a single Otechie username
12
+ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13
+ custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
models/gpt4free/.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
9
+
10
+ .idea/
11
+
12
+ */__pycache__/
13
+
14
+ *.log
15
+
16
+ cookie.json
models/gpt4free/Docker/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ RUN apt-get update && apt-get install -y git
4
+
5
+ RUN git clone https://github.com/xtekky/gpt4free.git
6
+ WORKDIR /gpt4free
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+ RUN cp gui/streamlit_app.py .
9
+
10
+ EXPOSE 8501
11
+
12
+ CMD ["streamlit", "run", "streamlit_app.py"]
models/gpt4free/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
models/gpt4free/README.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GPT4free - use ChatGPT, for free!!
2
+
3
+ <img width="1383" alt="image" src="https://user-images.githubusercontent.com/98614666/233799515-1a7cb6a3-b17f-42c4-956d-8d2a0664466f.png">
4
+
5
+ Have you ever come across some amazing projects that you couldn't use **just because you didn't have an OpenAI API key?**
6
+
7
+ **We've got you covered!** This repository offers **reverse-engineered** third-party APIs for `GPT-4/3.5`, sourced from various websites. You can simply **download** this repository, and use the available modules, which are designed to be used **just like OpenAI's official package**. **Unleash ChatGPT's potential for your projects, now!** You are welcome ; ).
8
+
9
+ By the way, thank you so much for `7k` stars and all the support!!
10
+
11
+ ## Announcement
12
+ Dear Gpt4free Community,
13
+
14
+ I want to thank you for your interest in and support of this project, which I only intended to be for entertainment and educational purposes; I had no idea it would end up being so popular.
15
+
16
+ I'm aware of the concerns about the project's legality and its impact on smaller sites hosting APIs. I take these concerns seriously and plan to address them.
17
+
18
+ Here's what I'm doing to fix these issues:
19
+
20
+ 1. Removing APIs from smaller sites: To reduce the impact on smaller sites, I have removed their APIs from the repository. Please shoot me a dm if you are an owner of a site and want it removed.
21
+
22
+ 2. Commitment to ethical use: I want to emphasize my commitment to promoting ethical use of language models. I don't support any illegal or unethical behavior, and I expect users to follow the same principles.
23
+
24
+ Thank you for your support and understanding. I appreciate your continued interest in gpt4free and am committed to addressing your concerns.
25
+
26
+ Sincerely,
27
+ xtekky
28
+
29
+ ## Legal Notice <a name="legal-notice"></a>
30
+
31
+ This repository uses third-party APIs and AI models and is *not* associated with or endorsed by the API providers or the original developers of the models. This project is intended **for educational purposes only**.
32
+
33
+ Please note the following:
34
+
35
+ 1. **Disclaimer**: The APIs, services, and trademarks mentioned in this repository belong to their respective owners. This project is *not* claiming any right over them.
36
+
37
+ 2. **Responsibility**: The author of this repository is *not* responsible for any consequences arising from the use or misuse of this repository or the content provided by the third-party APIs and any damage or losses caused by users' actions.
38
+
39
+ 3. **Educational Purposes Only**: This repository and its content are provided strictly for educational purposes. By using the information and code provided, users acknowledge that they are using the APIs and models at their own risk and agree to comply with any applicable laws and regulations.
40
+
41
+
42
+ ## Table of Contents
43
+ | Section | Description | Link | Status |
44
+ | ------- | ----------- | ---- | ------ |
45
+ | **To do list** | List of tasks to be done | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#todo) | - |
46
+ | **Current Sites** | Current websites or platforms that can be used as APIs | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#current-sites) | - |
47
+ | **Best Sites for gpt4** | Recommended websites or platforms for gpt4 | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#best-sites) | - |
48
+ | **Streamlit GPT4Free GUI** | Web-based graphical user interface for interacting with gpt4free | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#streamlit-gpt4free-gui) | - |
49
+ | **Docker** | Instructions on how to run gpt4free in a Docker container | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#docker-instructions) | - |
50
+ | **ChatGPT clone** | A ChatGPT clone with new features and scalability | [![Link to Website](https://img.shields.io/badge/Link-Visit%20Site-blue)](https://chat.chatbot.sex/chat) | - |
51
+ | **How to install** | Instructions on how to install gpt4free | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#install) | - |
52
+ | **Legal Notice** | Legal notice or disclaimer | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#legal-notice) | - |
53
+ | **Copyright** | Copyright information | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#copyright) | - |
54
+ | **Usage Examples** | | | |
55
+ | `quora (poe)` | Example usage for quora | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./quora/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) |
56
+ | `phind` | Example usage for phind | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./phind/README.md) | ![Inactive](https://img.shields.io/badge/Active-brightgreen) |
57
+ | `you` | Example usage for you | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./you/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen)
58
+ | **Try it Out** | | | |
59
+ | Google Colab Jupyter Notebook | Example usage for gpt4free | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DanielShemesh/gpt4free-colab/blob/main/gpt4free.ipynb) | - |
60
+ | replit Example (feel free to fork this repl) | Example usage for gpt4free | [![](https://img.shields.io/badge/Open%20in-Replit-1A1E27?logo=replit)](https://replit.com/@gpt4free/gpt4free-webui) | - |
61
+
62
+
63
+ ## Todo <a name="todo"></a>
64
+
65
+ - [ ] Add a GUI for the repo
66
+ - [ ] Make a general package named `openai_rev`, instead of different folders
67
+ - [ ] Live api status to know which are down and which can be used
68
+ - [ ] Integrate more API's in `./unfinished` as well as other ones in the lists
69
+ - [ ] Make an API to use as proxy for other projects
70
+ - [ ] Make a pypi package
71
+
72
+ ## Current Sites <a name="current-sites"></a>
73
+
74
+ | Website | Model(s) |
75
+ | ---------------------------------------------------- | ------------------------------- |
76
+ | [poe.com](https://poe.com) | GPT-4/3.5 |
77
+ | [writesonic.com](https://writesonic.com) | GPT-3.5 / Internet |
78
+ | [t3nsor.com](https://t3nsor.com) | GPT-3.5 |
79
+ | [you.com](https://you.com) | GPT-3.5 / Internet / good search|
80
+ | [phind.com](https://phind.com) | GPT-4 / Internet / good search |
81
+ | [sqlchat.ai](https://sqlchat.ai) | GPT-3.5 |
82
+ | [chat.openai.com/chat](https://chat.openai.com/chat) | GPT-3.5 |
83
+ | [bard.google.com](https://bard.google.com) | custom / search |
84
+ | [bing.com/chat](https://bing.com/chat) | GPT-4/3.5 |
85
+ | [chat.forefront.ai/](https://chat.forefront.ai/) | GPT-4/3.5 |
86
+
87
+ ## Best sites <a name="best-sites"></a>
88
+
89
+ #### gpt-4
90
+ - [`/phind`](./phind/README.md)
91
+ - pro: only stable gpt-4 with streaming ( no limit )
92
+ - contra: weird backend prompting
93
+ - why not `ora` anymore ? gpt-4 requires login + limited
94
+
95
+ #### gpt-3.5
96
+ - looking for a stable api at the moment
97
+
98
+ ## Install <a name="install"></a>
99
+ download or clone this GitHub repo
100
+ install requirements with:
101
+ ```sh
102
+ pip3 install -r requirements.txt
103
+ ```
104
+
105
+ ## To start gpt4free GUI <a name="streamlit-gpt4free-gui"></a>
106
+ move `streamlit_app.py` from `./gui` to the base folder
107
+ then run:
108
+ `streamlit run streamlit_app.py` or `python3 -m streamlit run streamlit_app.py`
109
+
110
+ ## Docker <a name="docker-instructions"></a>
111
+ Build
112
+ ```
113
+ docker build -t gpt4free:latest -f Docker/Dockerfile .
114
+ ```
115
+ Run
116
+ ```
117
+ docker run -p 8501:8501 gpt4free:latest
118
+ ```
119
+
120
+ ## ChatGPT clone
121
+ > currently implementing new features and trying to scale it, please be patient it may be unstable
122
+ > https://chat.chatbot.sex/chat
123
+ > This site was developed by me and includes **gpt-4/3.5**, **internet access** and **gpt-jailbreak's** like DAN
124
+ > run locally here: https://github.com/xtekky/chatgpt-clone
125
+
126
+ ## Copyright:
127
+ This program is licensed under the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.txt)
128
+
129
+ Most code, with the exception of `quora/api.py` (by [ading2210](https://github.com/ading2210)), has been written by me, [xtekky](https://github.com/xtekky).
130
+
131
+ ### Copyright Notice: <a name="copyright"></a>
132
+ ```
133
+ xtekky/openai-gpt4: multiple reverse engineered language-model api's to decentralise the ai industry.
134
+ Copyright (C) 2023 xtekky
135
+
136
+ This program is free software: you can redistribute it and/or modify
137
+ it under the terms of the GNU General Public License as published by
138
+ the Free Software Foundation, either version 3 of the License, or
139
+ (at your option) any later version.
140
+
141
+ This program is distributed in the hope that it will be useful,
142
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
143
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
144
+ GNU General Public License for more details.
145
+
146
+ You should have received a copy of the GNU General Public License
147
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
148
+ ```
models/gpt4free/gui/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # gpt4free gui
2
+
3
+ preview:
4
+
5
+ <img width="1125" alt="image" src="https://user-images.githubusercontent.com/98614666/234232398-09e9d3c5-08e6-4b8a-b4f2-0666e9790c7d.png">
6
+
7
+ run:
8
+
9
+ <img width="724" alt="image" src="https://user-images.githubusercontent.com/98614666/234232449-0d5cd092-a29d-4759-8197-e00ba712cb1a.png">
models/gpt4free/gui/streamlit_app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import phind
3
+
4
+ phind.cf_clearance = ''
5
+ phind.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
6
+
7
+ def phind_get_answer(question:str)->str:
8
+ # set cf_clearance cookie
9
+ try:
10
+
11
+ result = phind.Completion.create(
12
+ model = 'gpt-4',
13
+ prompt = question,
14
+ results = phind.Search.create(question, actualSearch = True),
15
+ creative = False,
16
+ detailed = False,
17
+ codeContext = '')
18
+ return result.completion.choices[0].text
19
+
20
+ except Exception as e:
21
+ return 'An error occured, please make sure you are using a cf_clearance token and correct useragent | %s' % e
22
+
23
+ st.set_page_config(
24
+ page_title="gpt4freeGUI",
25
+ initial_sidebar_state="expanded",
26
+ page_icon="🧠",
27
+ menu_items={
28
+ 'Get Help': 'https://github.com/xtekky/gpt4free/blob/main/README.md',
29
+ 'Report a bug': "https://github.com/xtekky/gpt4free/issues",
30
+ 'About': "### gptfree GUI"
31
+ }
32
+ )
33
+
34
+ st.header('GPT4free GUI')
35
+
36
+ question_text_area = st.text_area('🤖 Ask Any Question :', placeholder='Explain quantum computing in 50 words')
37
+ if st.button('🧠 Think'):
38
+ answer = phind_get_answer(question_text_area)
39
+ st.caption("Answer :")
40
+ st.markdown(answer)
41
+
42
+
43
+ hide_streamlit_style = """
44
+ <style>
45
+ footer {visibility: hidden;}
46
+ </style>
47
+ """
48
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
models/gpt4free/phind/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Example: `phind` (use like openai pypi package) <a name="example-phind"></a>
2
+
3
+ ```python
4
+ import phind
5
+
6
+ # set cf_clearance cookie (needed again)
7
+ phind.cf_clearance = 'xx.xx-1682166681-0-160'
8
+ phind.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' # same as the one from browser you got cf_clearance from
9
+
10
+ prompt = 'who won the quatar world cup'
11
+
12
+ # help needed: not getting newlines from the stream, please submit a PR if you know how to fix this
13
+ # stream completion
14
+ for result in phind.StreamingCompletion.create(
15
+ model = 'gpt-4',
16
+ prompt = prompt,
17
+ results = phind.Search.create(prompt, actualSearch = True), # create search (set actualSearch to False to disable internet)
18
+ creative = False,
19
+ detailed = False,
20
+ codeContext = ''): # up to 3000 chars of code
21
+
22
+ print(result.completion.choices[0].text, end='', flush=True)
23
+
24
+ # normal completion
25
+ result = phind.Completion.create(
26
+ model = 'gpt-4',
27
+ prompt = prompt,
28
+ results = phind.Search.create(prompt, actualSearch = True), # create search (set actualSearch to False to disable internet)
29
+ creative = False,
30
+ detailed = False,
31
+ codeContext = '') # up to 3000 chars of code
32
+
33
+ print(result.completion.choices[0].text)
34
+ ```
models/gpt4free/phind/__init__.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib.parse import quote
2
+ from time import time
3
+ from datetime import datetime
4
+ from queue import Queue, Empty
5
+ from threading import Thread
6
+ from re import findall
7
+
8
+ from curl_cffi.requests import post
9
+
10
+ proxies = {"http": "socks5h://localhost:7890", "https": "socks5h://localhost:7890", }
11
+ cf_clearance = ''
12
+ user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
13
+
14
+ class PhindResponse:
15
+
16
+ class Completion:
17
+
18
+ class Choices:
19
+ def __init__(self, choice: dict) -> None:
20
+ self.text = choice['text']
21
+ self.content = self.text.encode()
22
+ self.index = choice['index']
23
+ self.logprobs = choice['logprobs']
24
+ self.finish_reason = choice['finish_reason']
25
+
26
+ def __repr__(self) -> str:
27
+ return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
28
+
29
+ def __init__(self, choices: dict) -> None:
30
+ self.choices = [self.Choices(choice) for choice in choices]
31
+
32
+ class Usage:
33
+ def __init__(self, usage_dict: dict) -> None:
34
+ self.prompt_tokens = usage_dict['prompt_tokens']
35
+ self.completion_tokens = usage_dict['completion_tokens']
36
+ self.total_tokens = usage_dict['total_tokens']
37
+
38
+ def __repr__(self):
39
+ return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
40
+
41
+ def __init__(self, response_dict: dict) -> None:
42
+
43
+ self.response_dict = response_dict
44
+ self.id = response_dict['id']
45
+ self.object = response_dict['object']
46
+ self.created = response_dict['created']
47
+ self.model = response_dict['model']
48
+ self.completion = self.Completion(response_dict['choices'])
49
+ self.usage = self.Usage(response_dict['usage'])
50
+
51
+ def json(self) -> dict:
52
+ return self.response_dict
53
+
54
+
55
+ class Search:
56
+ def create(prompt: str, actualSearch: bool = True, language: str = 'en') -> dict: # None = no search
57
+ if user_agent == '':
58
+ raise ValueError('user_agent must be set, refer to documentation')
59
+ if cf_clearance == '' :
60
+ raise ValueError('cf_clearance must be set, refer to documentation')
61
+
62
+ if not actualSearch:
63
+ return {
64
+ '_type': 'SearchResponse',
65
+ 'queryContext': {
66
+ 'originalQuery': prompt
67
+ },
68
+ 'webPages': {
69
+ 'webSearchUrl': f'https://www.bing.com/search?q={quote(prompt)}',
70
+ 'totalEstimatedMatches': 0,
71
+ 'value': []
72
+ },
73
+ 'rankingResponse': {
74
+ 'mainline': {
75
+ 'items': []
76
+ }
77
+ }
78
+ }
79
+
80
+ headers = {
81
+ 'authority': 'www.phind.com',
82
+ 'accept': '*/*',
83
+ 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
84
+ 'cookie': f'cf_clearance={cf_clearance}',
85
+ 'origin': 'https://www.phind.com',
86
+ 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
87
+ 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
88
+ 'sec-ch-ua-mobile': '?0',
89
+ 'sec-ch-ua-platform': '"macOS"',
90
+ 'sec-fetch-dest': 'empty',
91
+ 'sec-fetch-mode': 'cors',
92
+ 'sec-fetch-site': 'same-origin',
93
+ 'user-agent': user_agent
94
+ }
95
+
96
+
97
+ return post('https://www.phind.com/api/bing/search', proxies=proxies, headers = headers, json = {
98
+ 'q': prompt,
99
+ 'userRankList': {},
100
+ 'browserLanguage': language}).json()['rawBingResults']
101
+
102
+
103
+ class Completion:
104
+ def create(
105
+ model = 'gpt-4',
106
+ prompt: str = '',
107
+ results: dict = None,
108
+ creative: bool = False,
109
+ detailed: bool = False,
110
+ codeContext: str = '',
111
+ language: str = 'en') -> PhindResponse:
112
+
113
+ if user_agent == '' :
114
+ raise ValueError('user_agent must be set, refer to documentation')
115
+
116
+ if cf_clearance == '' :
117
+ raise ValueError('cf_clearance must be set, refer to documentation')
118
+
119
+ if results is None:
120
+ results = Search.create(prompt, actualSearch = True)
121
+
122
+ if len(codeContext) > 2999:
123
+ raise ValueError('codeContext must be less than 3000 characters')
124
+
125
+ models = {
126
+ 'gpt-4' : 'expert',
127
+ 'gpt-3.5-turbo' : 'intermediate',
128
+ 'gpt-3.5': 'intermediate',
129
+ }
130
+
131
+ json_data = {
132
+ 'question' : prompt,
133
+ 'bingResults' : results, #response.json()['rawBingResults'],
134
+ 'codeContext' : codeContext,
135
+ 'options': {
136
+ 'skill' : models[model],
137
+ 'date' : datetime.now().strftime("%d/%m/%Y"),
138
+ 'language': language,
139
+ 'detailed': detailed,
140
+ 'creative': creative
141
+ }
142
+ }
143
+
144
+ headers = {
145
+ 'authority': 'www.phind.com',
146
+ 'accept': '*/*',
147
+ 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
148
+ 'content-type': 'application/json',
149
+ 'cookie': f'cf_clearance={cf_clearance}',
150
+ 'origin': 'https://www.phind.com',
151
+ 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
152
+ 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
153
+ 'sec-ch-ua-mobile': '?0',
154
+ 'sec-ch-ua-platform': '"macOS"',
155
+ 'sec-fetch-dest': 'empty',
156
+ 'sec-fetch-mode': 'cors',
157
+ 'sec-fetch-site': 'same-origin',
158
+ 'user-agent': user_agent
159
+ }
160
+
161
+ completion = ''
162
+ response = post('https://www.phind.com/api/infer/answer', proxies=proxies, headers = headers, json = json_data, timeout=99999, impersonate='chrome110')
163
+ for line in response.text.split('\r\n\r\n'):
164
+ completion += (line.replace('data: ', ''))
165
+
166
+ return PhindResponse({
167
+ 'id' : f'cmpl-1337-{int(time())}',
168
+ 'object' : 'text_completion',
169
+ 'created': int(time()),
170
+ 'model' : models[model],
171
+ 'choices': [{
172
+ 'text' : completion,
173
+ 'index' : 0,
174
+ 'logprobs' : None,
175
+ 'finish_reason' : 'stop'
176
+ }],
177
+ 'usage': {
178
+ 'prompt_tokens' : len(prompt),
179
+ 'completion_tokens' : len(completion),
180
+ 'total_tokens' : len(prompt) + len(completion)
181
+ }
182
+ })
183
+
184
+
185
+ class StreamingCompletion:
186
+ message_queue = Queue()
187
+ stream_completed = False
188
+
189
+ def request(model, prompt, results, creative, detailed, codeContext, language) -> None:
190
+
191
+ models = {
192
+ 'gpt-4' : 'expert',
193
+ 'gpt-3.5-turbo' : 'intermediate',
194
+ 'gpt-3.5': 'intermediate',
195
+ }
196
+
197
+ json_data = {
198
+ 'question' : prompt,
199
+ 'bingResults' : results,
200
+ 'codeContext' : codeContext,
201
+ 'options': {
202
+ 'skill' : models[model],
203
+ 'date' : datetime.now().strftime("%d/%m/%Y"),
204
+ 'language': language,
205
+ 'detailed': detailed,
206
+ 'creative': creative
207
+ }
208
+ }
209
+
210
+ headers = {
211
+ 'authority': 'www.phind.com',
212
+ 'accept': '*/*',
213
+ 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
214
+ 'content-type': 'application/json',
215
+ 'cookie': f'cf_clearance={cf_clearance}',
216
+ 'origin': 'https://www.phind.com',
217
+ 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
218
+ 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
219
+ 'sec-ch-ua-mobile': '?0',
220
+ 'sec-ch-ua-platform': '"macOS"',
221
+ 'sec-fetch-dest': 'empty',
222
+ 'sec-fetch-mode': 'cors',
223
+ 'sec-fetch-site': 'same-origin',
224
+ 'user-agent': user_agent
225
+ }
226
+
227
+ response = post('https://www.phind.com/api/infer/answer',
228
+ headers = headers, proxies=proxies, json = json_data, timeout=99999, impersonate='chrome110', content_callback=StreamingCompletion.handle_stream_response)
229
+
230
+
231
+ StreamingCompletion.stream_completed = True
232
+
233
+ @staticmethod
234
+ def create(
235
+ model : str = 'gpt-4',
236
+ prompt : str = '',
237
+ results : dict = None,
238
+ creative : bool = False,
239
+ detailed : bool = False,
240
+ codeContext : str = '',
241
+ language : str = 'en'):
242
+
243
+ if user_agent == '':
244
+ raise ValueError('user_agent must be set, refer to documentation')
245
+ if cf_clearance == '' :
246
+ raise ValueError('cf_clearance must be set, refer to documentation')
247
+
248
+ if results is None:
249
+ results = Search.create(prompt, actualSearch = True)
250
+
251
+ if len(codeContext) > 2999:
252
+ raise ValueError('codeContext must be less than 3000 characters')
253
+
254
+ Thread(target = StreamingCompletion.request, args = [
255
+ model, prompt, results, creative, detailed, codeContext, language]).start()
256
+
257
+ while StreamingCompletion.stream_completed != True or not StreamingCompletion.message_queue.empty():
258
+ try:
259
+ chunk = StreamingCompletion.message_queue.get(timeout=0)
260
+
261
+ if chunk == b'data: \r\ndata: \r\ndata: \r\n\r\n':
262
+ chunk = b'data: \n\n\r\n\r\n'
263
+
264
+ chunk = chunk.decode()
265
+
266
+ chunk = chunk.replace('data: \r\n\r\ndata: ', 'data: \n')
267
+ chunk = chunk.replace('\r\ndata: \r\ndata: \r\n\r\n', '\n\n\r\n\r\n')
268
+ chunk = chunk.replace('data: ', '').replace('\r\n\r\n', '')
269
+
270
+ yield PhindResponse({
271
+ 'id' : f'cmpl-1337-{int(time())}',
272
+ 'object' : 'text_completion',
273
+ 'created': int(time()),
274
+ 'model' : model,
275
+ 'choices': [{
276
+ 'text' : chunk,
277
+ 'index' : 0,
278
+ 'logprobs' : None,
279
+ 'finish_reason' : 'stop'
280
+ }],
281
+ 'usage': {
282
+ 'prompt_tokens' : len(prompt),
283
+ 'completion_tokens' : len(chunk),
284
+ 'total_tokens' : len(prompt) + len(chunk)
285
+ }
286
+ })
287
+
288
+ except Empty:
289
+ pass
290
+
291
+ @staticmethod
292
+ def handle_stream_response(response):
293
+ StreamingCompletion.message_queue.put(response)
models/gpt4free/quora/README.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #### warning !!!
2
+ poe.com added security and can detect if you are making automated requests. You may get your account banned if you are using this api.
3
+ The normal non-driver api is also currently not very stable
4
+
5
+
6
+ ### Example: `quora (poe)` (use like openai pypi package) - GPT-4 <a name="example-poe"></a>
7
+
8
+ ```python
9
+ # quora model names: (use left key as argument)
10
+ models = {
11
+ 'sage' : 'capybara',
12
+ 'gpt-4' : 'beaver',
13
+ 'claude-v1.2' : 'a2_2',
14
+ 'claude-instant-v1.0' : 'a2',
15
+ 'gpt-3.5-turbo' : 'chinchilla'
16
+ }
17
+ ```
18
+
19
+ #### !! new: bot creation
20
+
21
+ ```python
22
+ # import quora (poe) package
23
+ import quora
24
+
25
+ # create account
26
+ # make sure to set enable_bot_creation to True
27
+ token = quora.Account.create(logging = True, enable_bot_creation=True)
28
+
29
+ model = quora.Model.create(
30
+ token = token,
31
+ model = 'gpt-3.5-turbo', # or claude-instant-v1.0
32
+ system_prompt = 'you are ChatGPT a large language model ...'
33
+ )
34
+
35
+ print(model.name) # gptx....
36
+
37
+ # streaming response
38
+ for response in quora.StreamingCompletion.create(
39
+ custom_model = model.name,
40
+ prompt ='hello world',
41
+ token = token):
42
+
43
+ print(response.completion.choices[0].text)
44
+ ```
45
+
46
+ #### Normal Response:
47
+ ```python
48
+
49
+ response = quora.Completion.create(model = 'gpt-4',
50
+ prompt = 'hello world',
51
+ token = token)
52
+
53
+ print(response.completion.choices[0].text)
54
+ ```
55
+
56
+ #### Update Use This For Poe
57
+ ```python
58
+ from quora import Poe
59
+
60
+ # available models: ['Sage', 'GPT-4', 'Claude+', 'Claude-instant', 'ChatGPT', 'Dragonfly', 'NeevaAI']
61
+
62
+ poe = Poe(model='ChatGPT')
63
+ poe.chat('who won the football world cup most?')
64
+
65
+ # new bot creation
66
+ poe.create_bot('new_bot_name', prompt='You are new test bot', base_model='gpt-3.5-turbo')
67
+
68
+ ```
models/gpt4free/quora/__init__.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime
3
+ from hashlib import md5
4
+ from json import dumps
5
+ from pathlib import Path
6
+ from random import choice, choices, randint
7
+ from re import search, findall
8
+ from string import ascii_letters, digits
9
+ from typing import Optional
10
+ from urllib.parse import unquote
11
+
12
+ import selenium.webdriver.support.expected_conditions as EC
13
+ from pypasser import reCaptchaV3
14
+ from requests import Session
15
+ from selenium import webdriver
16
+ from selenium.webdriver.common.by import By
17
+ from selenium.webdriver.support.wait import WebDriverWait
18
+ from tls_client import Session as TLS
19
+
20
+ from quora.api import Client as PoeClient
21
+ from quora.mail import Emailnator
22
+
23
+ # from twocaptcha import TwoCaptcha
24
+ # solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358')
25
+
26
+ MODELS = {
27
+ "Sage": "capybara",
28
+ "GPT-4": "beaver",
29
+ "Claude+": "a2_2",
30
+ "Claude-instant": "a2",
31
+ "ChatGPT": "chinchilla",
32
+ "Dragonfly": "nutria",
33
+ "NeevaAI": "hutia",
34
+ }
35
+
36
+
37
+ def extract_formkey(html):
38
+ script_regex = r"<script>if\(.+\)throw new Error;(.+)</script>"
39
+ script_text = search(script_regex, html).group(1)
40
+ key_regex = r'var .="([0-9a-f]+)",'
41
+ key_text = search(key_regex, script_text).group(1)
42
+ cipher_regex = r".\[(\d+)\]=.\[(\d+)\]"
43
+ cipher_pairs = findall(cipher_regex, script_text)
44
+
45
+ formkey_list = [""] * len(cipher_pairs)
46
+ for pair in cipher_pairs:
47
+ formkey_index, key_index = map(int, pair)
48
+ formkey_list[formkey_index] = key_text[key_index]
49
+ formkey = "".join(formkey_list)
50
+
51
+ return formkey
52
+
53
+
54
+ class PoeResponse:
55
+ class Completion:
56
+ class Choices:
57
+ def __init__(self, choice: dict) -> None:
58
+ self.text = choice["text"]
59
+ self.content = self.text.encode()
60
+ self.index = choice["index"]
61
+ self.logprobs = choice["logprobs"]
62
+ self.finish_reason = choice["finish_reason"]
63
+
64
+ def __repr__(self) -> str:
65
+ return f"""<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>"""
66
+
67
+ def __init__(self, choices: dict) -> None:
68
+ self.choices = [self.Choices(choice) for choice in choices]
69
+
70
+ class Usage:
71
+ def __init__(self, usage_dict: dict) -> None:
72
+ self.prompt_tokens = usage_dict["prompt_tokens"]
73
+ self.completion_tokens = usage_dict["completion_tokens"]
74
+ self.total_tokens = usage_dict["total_tokens"]
75
+
76
+ def __repr__(self):
77
+ return f"""<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>"""
78
+
79
+ def __init__(self, response_dict: dict) -> None:
80
+ self.response_dict = response_dict
81
+ self.id = response_dict["id"]
82
+ self.object = response_dict["object"]
83
+ self.created = response_dict["created"]
84
+ self.model = response_dict["model"]
85
+ self.completion = self.Completion(response_dict["choices"])
86
+ self.usage = self.Usage(response_dict["usage"])
87
+
88
+ def json(self) -> dict:
89
+ return self.response_dict
90
+
91
+
92
+ class ModelResponse:
93
+ def __init__(self, json_response: dict) -> None:
94
+ self.id = json_response["data"]["poeBotCreate"]["bot"]["id"]
95
+ self.name = json_response["data"]["poeBotCreate"]["bot"]["displayName"]
96
+ self.limit = json_response["data"]["poeBotCreate"]["bot"]["messageLimit"][
97
+ "dailyLimit"
98
+ ]
99
+ self.deleted = json_response["data"]["poeBotCreate"]["bot"]["deletionState"]
100
+
101
+
102
+ class Model:
103
+ def create(
104
+ token: str,
105
+ model: str = "gpt-3.5-turbo", # claude-instant
106
+ system_prompt: str = "You are ChatGPT a large language model developed by Openai. Answer as consisely as possible",
107
+ description: str = "gpt-3.5 language model from openai, skidded by poe.com",
108
+ handle: str = None,
109
+ ) -> ModelResponse:
110
+ models = {
111
+ "gpt-3.5-turbo": "chinchilla",
112
+ "claude-instant-v1.0": "a2",
113
+ "gpt-4": "beaver",
114
+ }
115
+
116
+ if not handle:
117
+ handle = f"gptx{randint(1111111, 9999999)}"
118
+
119
+ client = Session()
120
+ client.cookies["p-b"] = token
121
+
122
+ formkey = extract_formkey(client.get("https://poe.com").text)
123
+ settings = client.get("https://poe.com/api/settings").json()
124
+
125
+ client.headers = {
126
+ "host": "poe.com",
127
+ "origin": "https://poe.com",
128
+ "referer": "https://poe.com/",
129
+ "poe-formkey": formkey,
130
+ "poe-tchannel": settings["tchannelData"]["channel"],
131
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
132
+ "connection": "keep-alive",
133
+ "sec-ch-ua": '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
134
+ "sec-ch-ua-mobile": "?0",
135
+ "sec-ch-ua-platform": '"macOS"',
136
+ "content-type": "application/json",
137
+ "sec-fetch-site": "same-origin",
138
+ "sec-fetch-mode": "cors",
139
+ "sec-fetch-dest": "empty",
140
+ "accept": "*/*",
141
+ "accept-encoding": "gzip, deflate, br",
142
+ "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
143
+ }
144
+
145
+ payload = dumps(
146
+ separators=(",", ":"),
147
+ obj={
148
+ "queryName": "CreateBotMain_poeBotCreate_Mutation",
149
+ "variables": {
150
+ "model": models[model],
151
+ "handle": handle,
152
+ "prompt": system_prompt,
153
+ "isPromptPublic": True,
154
+ "introduction": "",
155
+ "description": description,
156
+ "profilePictureUrl": "https://qph.fs.quoracdn.net/main-qimg-24e0b480dcd946e1cc6728802c5128b6",
157
+ "apiUrl": None,
158
+ "apiKey": "".join(choices(ascii_letters + digits, k=32)),
159
+ "isApiBot": False,
160
+ "hasLinkification": False,
161
+ "hasMarkdownRendering": False,
162
+ "hasSuggestedReplies": False,
163
+ "isPrivateBot": False,
164
+ },
165
+ "query": "mutation CreateBotMain_poeBotCreate_Mutation(\n $model: String!\n $handle: String!\n $prompt: String!\n $isPromptPublic: Boolean!\n $introduction: String!\n $description: String!\n $profilePictureUrl: String\n $apiUrl: String\n $apiKey: String\n $isApiBot: Boolean\n $hasLinkification: Boolean\n $hasMarkdownRendering: Boolean\n $hasSuggestedReplies: Boolean\n $isPrivateBot: Boolean\n) {\n poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {\n status\n bot {\n id\n ...BotHeader_bot\n }\n }\n}\n\nfragment BotHeader_bot on Bot {\n displayName\n messageLimit {\n dailyLimit\n }\n ...BotImage_bot\n ...BotLink_bot\n ...IdAnnotation_node\n ...botHelpers_useViewerCanAccessPrivateBot\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotImage_bot on Bot {\n displayName\n ...botHelpers_useDeletion_bot\n ...BotImage_useProfileImage_bot\n}\n\nfragment BotImage_useProfileImage_bot on Bot {\n image {\n __typename\n ... on LocalBotImage {\n localName\n }\n ... on UrlBotImage {\n url\n }\n }\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotLink_bot on Bot {\n displayName\n}\n\nfragment IdAnnotation_node on Node {\n __isNode: __typename\n id\n}\n\nfragment botHelpers_useDeletion_bot on Bot {\n deletionState\n}\n\nfragment botHelpers_useViewerCanAccessPrivateBot on Bot {\n isPrivateBot\n viewerIsCreator\n}\n",
166
+ },
167
+ )
168
+
169
+ base_string = payload + client.headers["poe-formkey"] + "WpuLMiXEKKE98j56k"
170
+ client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
171
+
172
+ response = client.post("https://poe.com/api/gql_POST", data=payload)
173
+
174
+ if "success" not in response.text:
175
+ raise Exception(
176
+ """
177
+ Bot creation Failed
178
+ !! Important !!
179
+ Bot creation was not enabled on this account
180
+ please use: quora.Account.create with enable_bot_creation set to True
181
+ """
182
+ )
183
+
184
+ return ModelResponse(response.json())
185
+
186
+
187
+ class Account:
188
+ def create(
189
+ proxy: Optional[str] = None,
190
+ logging: bool = False,
191
+ enable_bot_creation: bool = False,
192
+ ):
193
+ client = TLS(client_identifier="chrome110")
194
+ client.proxies = (
195
+ {"http": f"http://{proxy}", "https": f"http://{proxy}"} if proxy else None
196
+ )
197
+
198
+ mail_client = Emailnator()
199
+ mail_address = mail_client.get_mail()
200
+
201
+ if logging:
202
+ print("email", mail_address)
203
+
204
+ client.headers = {
205
+ "authority": "poe.com",
206
+ "accept": "*/*",
207
+ "accept-language": "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
208
+ "content-type": "application/json",
209
+ "origin": "https://poe.com",
210
+ "poe-tag-id": "null",
211
+ "referer": "https://poe.com/login",
212
+ "sec-ch-ua": '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
213
+ "sec-ch-ua-mobile": "?0",
214
+ "sec-ch-ua-platform": '"macOS"',
215
+ "sec-fetch-dest": "empty",
216
+ "sec-fetch-mode": "cors",
217
+ "sec-fetch-site": "same-origin",
218
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
219
+ "poe-formkey": extract_formkey(client.get("https://poe.com/login").text),
220
+ "poe-tchannel": client.get("https://poe.com/api/settings").json()[
221
+ "tchannelData"
222
+ ]["channel"],
223
+ }
224
+
225
+ token = reCaptchaV3(
226
+ "https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=4PnKmGB9wRHh1i04o7YUICeI&size=invisible&cb=bi6ivxoskyal"
227
+ )
228
+ # token = solver.recaptcha(sitekey='6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG',
229
+ # url = 'https://poe.com/login?redirect_url=%2F',
230
+ # version = 'v3',
231
+ # enterprise = 1,
232
+ # invisible = 1,
233
+ # action = 'login',)['code']
234
+
235
+ payload = dumps(
236
+ separators=(",", ":"),
237
+ obj={
238
+ "queryName": "MainSignupLoginSection_sendVerificationCodeMutation_Mutation",
239
+ "variables": {
240
+ "emailAddress": mail_address,
241
+ "phoneNumber": None,
242
+ "recaptchaToken": token,
243
+ },
244
+ "query": "mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n",
245
+ },
246
+ )
247
+
248
+ base_string = payload + client.headers["poe-formkey"] + "WpuLMiXEKKE98j56k"
249
+ client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
250
+
251
+ print(dumps(client.headers, indent=4))
252
+
253
+ response = client.post("https://poe.com/api/gql_POST", data=payload)
254
+
255
+ if "automated_request_detected" in response.text:
256
+ print("please try using a proxy / wait for fix")
257
+
258
+ if "Bad Request" in response.text:
259
+ if logging:
260
+ print("bad request, retrying...", response.json())
261
+ quit()
262
+
263
+ if logging:
264
+ print("send_code", response.json())
265
+
266
+ mail_content = mail_client.get_message()
267
+ mail_token = findall(r';">(\d{6,7})</div>', mail_content)[0]
268
+
269
+ if logging:
270
+ print("code", mail_token)
271
+
272
+ payload = dumps(
273
+ separators=(",", ":"),
274
+ obj={
275
+ "queryName": "SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation",
276
+ "variables": {
277
+ "verificationCode": str(mail_token),
278
+ "emailAddress": mail_address,
279
+ "phoneNumber": None,
280
+ },
281
+ "query": "mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n",
282
+ },
283
+ )
284
+
285
+ base_string = payload + client.headers["poe-formkey"] + "WpuLMiXEKKE98j56k"
286
+ client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
287
+
288
+ response = client.post("https://poe.com/api/gql_POST", data=payload)
289
+ if logging:
290
+ print("verify_code", response.json())
291
+
292
+ def get(self):
293
+ cookies = (
294
+ open(Path(__file__).resolve().parent / "cookies.txt", "r")
295
+ .read()
296
+ .splitlines()
297
+ )
298
+ return choice(cookies)
299
+
300
+
301
+ class StreamingCompletion:
302
+ def create(
303
+ model: str = "gpt-4",
304
+ custom_model: bool = None,
305
+ prompt: str = "hello world",
306
+ token: str = "",
307
+ ):
308
+ _model = MODELS[model] if not custom_model else custom_model
309
+
310
+ client = PoeClient(token)
311
+
312
+ for chunk in client.send_message(_model, prompt):
313
+ yield PoeResponse(
314
+ {
315
+ "id": chunk["messageId"],
316
+ "object": "text_completion",
317
+ "created": chunk["creationTime"],
318
+ "model": _model,
319
+ "choices": [
320
+ {
321
+ "text": chunk["text_new"],
322
+ "index": 0,
323
+ "logprobs": None,
324
+ "finish_reason": "stop",
325
+ }
326
+ ],
327
+ "usage": {
328
+ "prompt_tokens": len(prompt),
329
+ "completion_tokens": len(chunk["text_new"]),
330
+ "total_tokens": len(prompt) + len(chunk["text_new"]),
331
+ },
332
+ }
333
+ )
334
+
335
+
336
+ class Completion:
337
+ def create(
338
+ model: str = "gpt-4",
339
+ custom_model: str = None,
340
+ prompt: str = "hello world",
341
+ token: str = "",
342
+ ):
343
+ models = {
344
+ "sage": "capybara",
345
+ "gpt-4": "beaver",
346
+ "claude-v1.2": "a2_2",
347
+ "claude-instant-v1.0": "a2",
348
+ "gpt-3.5-turbo": "chinchilla",
349
+ }
350
+
351
+ _model = models[model] if not custom_model else custom_model
352
+
353
+ client = PoeClient(token)
354
+
355
+ for chunk in client.send_message(_model, prompt):
356
+ pass
357
+
358
+ return PoeResponse(
359
+ {
360
+ "id": chunk["messageId"],
361
+ "object": "text_completion",
362
+ "created": chunk["creationTime"],
363
+ "model": _model,
364
+ "choices": [
365
+ {
366
+ "text": chunk["text"],
367
+ "index": 0,
368
+ "logprobs": None,
369
+ "finish_reason": "stop",
370
+ }
371
+ ],
372
+ "usage": {
373
+ "prompt_tokens": len(prompt),
374
+ "completion_tokens": len(chunk["text"]),
375
+ "total_tokens": len(prompt) + len(chunk["text"]),
376
+ },
377
+ }
378
+ )
379
+
380
+
381
+ class Poe:
382
+ def __init__(self, model: str = "ChatGPT"):
383
+ # validating the model
384
+ if model and model not in MODELS:
385
+ raise RuntimeError(
386
+ "Sorry, the model you provided does not exist. Please check and try again."
387
+ )
388
+ self.model = MODELS[model]
389
+ self.cookie = self.__load_cookie()
390
+ self.client = PoeClient(self.cookie)
391
+
392
+ def __load_cookie(self) -> str:
393
+ if (cookie_file := Path("./quora/cookie.json")).exists():
394
+ with cookie_file.open() as fp:
395
+ cookie = json.load(fp)
396
+ if datetime.fromtimestamp(cookie["expiry"]) < datetime.now():
397
+ cookie = self.__register_and_get_cookie()
398
+ else:
399
+ print("Loading the cookie from file")
400
+ else:
401
+ cookie = self.__register_and_get_cookie()
402
+
403
+ return unquote(cookie["value"])
404
+
405
+ @classmethod
406
+ def __register_and_get_cookie(cls) -> dict:
407
+ mail_client = Emailnator()
408
+ mail_address = mail_client.get_mail()
409
+
410
+ print(mail_address)
411
+ options = webdriver.FirefoxOptions()
412
+ # options.add_argument("-headless")
413
+ try:
414
+ driver = webdriver.Firefox(options=options)
415
+
416
+ except Exception:
417
+ raise Exception(b'The error message you are receiving is due to the `geckodriver` executable not being found in your system\'s PATH. To resolve this issue, you need to download the geckodriver and add its location to your system\'s PATH.\n\nHere are the steps to resolve the issue:\n\n1. Download the geckodriver for your platform (Windows, macOS, or Linux) from the following link: https://github.com/mozilla/geckodriver/releases\n\n2. Extract the downloaded archive and locate the geckodriver executable.\n\n3. Add the geckodriver executable to your system\'s PATH.\n\nFor macOS and Linux:\n\n- Open a terminal window.\n- Move the geckodriver executable to a directory that is already in your PATH, or create a new directory and add it to your PATH:\n\n```bash\n# Example: Move geckodriver to /usr/local/bin\nmv /path/to/your/geckodriver /usr/local/bin\n```\n\n- If you created a new directory, add it to your PATH:\n\n```bash\n# Example: Add a new directory to PATH\nexport PATH=$PATH:/path/to/your/directory\n```\n\nFor Windows:\n\n- Right-click on "My Computer" or "This PC" and select "Properties".\n- Click on "Advanced system settings".\n- Click on the "Environment Variables" button.\n- In the "System variables" section, find the "Path" variable, select it, and click "Edit".\n- Click "New" and add the path to the directory containing the geckodriver executable.\n\nAfter adding the geckodriver to your PATH, restart your terminal or command prompt and try running your script again. The error should be resolved.')
418
+
419
+ driver.get("https://www.poe.com")
420
+
421
+ # clicking use email button
422
+ driver.find_element(By.XPATH, '//button[contains(text(), "Use email")]').click()
423
+
424
+ email = WebDriverWait(driver, 30).until(
425
+ EC.presence_of_element_located((By.XPATH, '//input[@type="email"]'))
426
+ )
427
+ email.send_keys(mail_address)
428
+ driver.find_element(By.XPATH, '//button[text()="Go"]').click()
429
+
430
+ code = findall(r';">(\d{6,7})</div>', mail_client.get_message())[0]
431
+ print(code)
432
+
433
+ verification_code = WebDriverWait(driver, 30).until(
434
+ EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Code"]'))
435
+ )
436
+ verification_code.send_keys(code)
437
+ verify_button = EC.presence_of_element_located(
438
+ (By.XPATH, '//button[text()="Verify"]')
439
+ )
440
+ login_button = EC.presence_of_element_located(
441
+ (By.XPATH, '//button[text()="Log In"]')
442
+ )
443
+
444
+ WebDriverWait(driver, 30).until(EC.any_of(verify_button, login_button)).click()
445
+
446
+ cookie = driver.get_cookie("p-b")
447
+
448
+ with open("./quora/cookie.json", "w") as fw:
449
+ json.dump(cookie, fw)
450
+
451
+ driver.close()
452
+ return cookie
453
+
454
+ def chat(self, message: str, model: Optional[str] = None) -> str:
455
+ if model and model not in MODELS:
456
+ raise RuntimeError(
457
+ "Sorry, the model you provided does not exist. Please check and try again."
458
+ )
459
+ model = MODELS[model] if model else self.model
460
+ response = None
461
+ for chunk in self.client.send_message(model, message):
462
+ response = chunk["text"]
463
+ return response
464
+
465
+ def create_bot(
466
+ self,
467
+ name: str,
468
+ /,
469
+ prompt: str = "",
470
+ base_model: str = "ChatGPT",
471
+ description: str = "",
472
+ ) -> None:
473
+ if base_model not in MODELS:
474
+ raise RuntimeError(
475
+ "Sorry, the base_model you provided does not exist. Please check and try again."
476
+ )
477
+
478
+ response = self.client.create_bot(
479
+ handle=name,
480
+ prompt=prompt,
481
+ base_model=MODELS[base_model],
482
+ description=description,
483
+ )
484
+ print(f'Successfully created bot with name: {response["bot"]["displayName"]}')
485
+
486
+ def list_bots(self) -> list:
487
+ return list(self.client.bot_names.values())
models/gpt4free/quora/api.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file was taken from the repository poe-api https://github.com/ading2210/poe-api and is unmodified
2
+ # This file is licensed under the GNU GPL v3 and written by @ading2210
3
+
4
+ # license:
5
+ # ading2210/poe-api: a reverse engineered Python API wrapepr for Quora's Poe
6
+ # Copyright (C) 2023 ading2210
7
+
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU General Public License as published by
10
+ # the Free Software Foundation, either version 3 of the License, or
11
+ # (at your option) any later version.
12
+
13
+ # This program is distributed in the hope that it will be useful,
14
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ # GNU General Public License for more details.
17
+
18
+ # You should have received a copy of the GNU General Public License
19
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
20
+
21
+ import requests
22
+ import re
23
+ import json
24
+ import random
25
+ import logging
26
+ import time
27
+ import queue
28
+ import threading
29
+ import traceback
30
+ import hashlib
31
+ import string
32
+ import random
33
+ import requests.adapters
34
+ import websocket
35
+ from pathlib import Path
36
+ from urllib.parse import urlparse
37
+
38
+
39
+ parent_path = Path(__file__).resolve().parent
40
+ queries_path = parent_path / "graphql"
41
+ queries = {}
42
+
43
+ logging.basicConfig()
44
+ logger = logging.getLogger()
45
+
46
+ user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0"
47
+
48
+
49
+ def load_queries():
50
+ for path in queries_path.iterdir():
51
+ if path.suffix != ".graphql":
52
+ continue
53
+ with open(path) as f:
54
+ queries[path.stem] = f.read()
55
+
56
+
57
+ def generate_payload(query_name, variables):
58
+ return {"query": queries[query_name], "variables": variables}
59
+
60
+
61
+ def request_with_retries(method, *args, **kwargs):
62
+ attempts = kwargs.get("attempts") or 10
63
+ url = args[0]
64
+ for i in range(attempts):
65
+ r = method(*args, **kwargs)
66
+ if r.status_code == 200:
67
+ return r
68
+ logger.warn(
69
+ f"Server returned a status code of {r.status_code} while downloading {url}. Retrying ({i+1}/{attempts})..."
70
+ )
71
+
72
+ raise RuntimeError(f"Failed to download {url} too many times.")
73
+
74
+
75
+ class Client:
76
+ gql_url = "https://poe.com/api/gql_POST"
77
+ gql_recv_url = "https://poe.com/api/receive_POST"
78
+ home_url = "https://poe.com"
79
+ settings_url = "https://poe.com/api/settings"
80
+
81
+ def __init__(self, token, proxy=None):
82
+ self.proxy = proxy
83
+ self.session = requests.Session()
84
+ self.adapter = requests.adapters.HTTPAdapter(
85
+ pool_connections=100, pool_maxsize=100
86
+ )
87
+ self.session.mount("http://", self.adapter)
88
+ self.session.mount("https://", self.adapter)
89
+
90
+ if proxy:
91
+ self.session.proxies = {"http": self.proxy, "https": self.proxy}
92
+ logger.info(f"Proxy enabled: {self.proxy}")
93
+
94
+ self.active_messages = {}
95
+ self.message_queues = {}
96
+
97
+ self.session.cookies.set("p-b", token, domain="poe.com")
98
+ self.headers = {
99
+ "User-Agent": user_agent,
100
+ "Referrer": "https://poe.com/",
101
+ "Origin": "https://poe.com",
102
+ }
103
+ self.session.headers.update(self.headers)
104
+
105
+ self.setup_connection()
106
+ self.connect_ws()
107
+
108
+ def setup_connection(self):
109
+ self.ws_domain = f"tch{random.randint(1, 1e6)}"
110
+ self.next_data = self.get_next_data(overwrite_vars=True)
111
+ self.channel = self.get_channel_data()
112
+ self.bots = self.get_bots(download_next_data=False)
113
+ self.bot_names = self.get_bot_names()
114
+
115
+ self.gql_headers = {
116
+ "poe-formkey": self.formkey,
117
+ "poe-tchannel": self.channel["channel"],
118
+ }
119
+ self.gql_headers = {**self.gql_headers, **self.headers}
120
+ self.subscribe()
121
+
122
+ def extract_formkey(self, html):
123
+ script_regex = r"<script>if\(.+\)throw new Error;(.+)</script>"
124
+ script_text = re.search(script_regex, html).group(1)
125
+ key_regex = r'var .="([0-9a-f]+)",'
126
+ key_text = re.search(key_regex, script_text).group(1)
127
+ cipher_regex = r".\[(\d+)\]=.\[(\d+)\]"
128
+ cipher_pairs = re.findall(cipher_regex, script_text)
129
+
130
+ formkey_list = [""] * len(cipher_pairs)
131
+ for pair in cipher_pairs:
132
+ formkey_index, key_index = map(int, pair)
133
+ formkey_list[formkey_index] = key_text[key_index]
134
+ formkey = "".join(formkey_list)
135
+
136
+ return formkey
137
+
138
+ def get_next_data(self, overwrite_vars=False):
139
+ logger.info("Downloading next_data...")
140
+
141
+ r = request_with_retries(self.session.get, self.home_url)
142
+ json_regex = (
143
+ r'<script id="__NEXT_DATA__" type="application\/json">(.+?)</script>'
144
+ )
145
+ json_text = re.search(json_regex, r.text).group(1)
146
+ next_data = json.loads(json_text)
147
+
148
+ if overwrite_vars:
149
+ self.formkey = self.extract_formkey(r.text)
150
+ self.viewer = next_data["props"]["pageProps"]["payload"]["viewer"]
151
+ self.next_data = next_data
152
+
153
+ return next_data
154
+
155
+ def get_bot(self, display_name):
156
+ url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/{display_name}.json'
157
+
158
+ r = request_with_retries(self.session.get, url)
159
+
160
+ chat_data = r.json()["pageProps"]["payload"]["chatOfBotDisplayName"]
161
+ return chat_data
162
+
163
+ def get_bots(self, download_next_data=True):
164
+ logger.info("Downloading all bots...")
165
+ if download_next_data:
166
+ next_data = self.get_next_data(overwrite_vars=True)
167
+ else:
168
+ next_data = self.next_data
169
+
170
+ if not "availableBots" in self.viewer:
171
+ raise RuntimeError("Invalid token or no bots are available.")
172
+ bot_list = self.viewer["availableBots"]
173
+
174
+ threads = []
175
+ bots = {}
176
+
177
+ def get_bot_thread(bot):
178
+ chat_data = self.get_bot(bot["displayName"])
179
+ bots[chat_data["defaultBotObject"]["nickname"]] = chat_data
180
+
181
+ for bot in bot_list:
182
+ thread = threading.Thread(target=get_bot_thread, args=(bot,), daemon=True)
183
+ threads.append(thread)
184
+
185
+ for thread in threads:
186
+ thread.start()
187
+ for thread in threads:
188
+ thread.join()
189
+
190
+ self.bots = bots
191
+ self.bot_names = self.get_bot_names()
192
+ return bots
193
+
194
+ def get_bot_names(self):
195
+ bot_names = {}
196
+ for bot_nickname in self.bots:
197
+ bot_obj = self.bots[bot_nickname]["defaultBotObject"]
198
+ bot_names[bot_nickname] = bot_obj["displayName"]
199
+ return bot_names
200
+
201
+ def get_remaining_messages(self, chatbot):
202
+ chat_data = self.get_bot(self.bot_names[chatbot])
203
+ return chat_data["defaultBotObject"]["messageLimit"]["numMessagesRemaining"]
204
+
205
+ def get_channel_data(self, channel=None):
206
+ logger.info("Downloading channel data...")
207
+ r = request_with_retries(self.session.get, self.settings_url)
208
+ data = r.json()
209
+
210
+ return data["tchannelData"]
211
+
212
+ def get_websocket_url(self, channel=None):
213
+ if channel is None:
214
+ channel = self.channel
215
+ query = f'?min_seq={channel["minSeq"]}&channel={channel["channel"]}&hash={channel["channelHash"]}'
216
+ return (
217
+ f'wss://{self.ws_domain}.tch.{channel["baseHost"]}/up/{channel["boxName"]}/updates'
218
+ + query
219
+ )
220
+
221
+ def send_query(self, query_name, variables):
222
+ for i in range(20):
223
+ json_data = generate_payload(query_name, variables)
224
+ payload = json.dumps(json_data, separators=(",", ":"))
225
+
226
+ base_string = (
227
+ payload + self.gql_headers["poe-formkey"] + "WpuLMiXEKKE98j56k"
228
+ )
229
+
230
+ headers = {
231
+ "content-type": "application/json",
232
+ "poe-tag-id": hashlib.md5(base_string.encode()).hexdigest(),
233
+ }
234
+ headers = {**self.gql_headers, **headers}
235
+
236
+ r = request_with_retries(
237
+ self.session.post, self.gql_url, data=payload, headers=headers
238
+ )
239
+
240
+ data = r.json()
241
+ if data["data"] == None:
242
+ logger.warn(
243
+ f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i+1}/20)'
244
+ )
245
+ time.sleep(2)
246
+ continue
247
+
248
+ return r.json()
249
+
250
+ raise RuntimeError(f"{query_name} failed too many times.")
251
+
252
+ def subscribe(self):
253
+ logger.info("Subscribing to mutations")
254
+ result = self.send_query(
255
+ "SubscriptionsMutation",
256
+ {
257
+ "subscriptions": [
258
+ {
259
+ "subscriptionName": "messageAdded",
260
+ "query": queries["MessageAddedSubscription"],
261
+ },
262
+ {
263
+ "subscriptionName": "viewerStateUpdated",
264
+ "query": queries["ViewerStateUpdatedSubscription"],
265
+ },
266
+ ]
267
+ },
268
+ )
269
+
270
+ def ws_run_thread(self):
271
+ kwargs = {}
272
+ if self.proxy:
273
+ proxy_parsed = urlparse(self.proxy)
274
+ kwargs = {
275
+ "proxy_type": proxy_parsed.scheme,
276
+ "http_proxy_host": proxy_parsed.hostname,
277
+ "http_proxy_port": proxy_parsed.port,
278
+ }
279
+
280
+ self.ws.run_forever(**kwargs)
281
+
282
+ def connect_ws(self):
283
+ self.ws_connected = False
284
+ self.ws = websocket.WebSocketApp(
285
+ self.get_websocket_url(),
286
+ header={"User-Agent": user_agent},
287
+ on_message=self.on_message,
288
+ on_open=self.on_ws_connect,
289
+ on_error=self.on_ws_error,
290
+ on_close=self.on_ws_close,
291
+ )
292
+ t = threading.Thread(target=self.ws_run_thread, daemon=True)
293
+ t.start()
294
+ while not self.ws_connected:
295
+ time.sleep(0.01)
296
+
297
+ def disconnect_ws(self):
298
+ if self.ws:
299
+ self.ws.close()
300
+ self.ws_connected = False
301
+
302
+ def on_ws_connect(self, ws):
303
+ self.ws_connected = True
304
+
305
+ def on_ws_close(self, ws, close_status_code, close_message):
306
+ self.ws_connected = False
307
+ logger.warn(
308
+ f"Websocket closed with status {close_status_code}: {close_message}"
309
+ )
310
+
311
+ def on_ws_error(self, ws, error):
312
+ self.disconnect_ws()
313
+ self.connect_ws()
314
+
315
+ def on_message(self, ws, msg):
316
+ try:
317
+ data = json.loads(msg)
318
+
319
+ if not "messages" in data:
320
+ return
321
+
322
+ for message_str in data["messages"]:
323
+ message_data = json.loads(message_str)
324
+ if message_data["message_type"] != "subscriptionUpdate":
325
+ continue
326
+ message = message_data["payload"]["data"]["messageAdded"]
327
+
328
+ copied_dict = self.active_messages.copy()
329
+ for key, value in copied_dict.items():
330
+ # add the message to the appropriate queue
331
+ if value == message["messageId"] and key in self.message_queues:
332
+ self.message_queues[key].put(message)
333
+ return
334
+
335
+ # indicate that the response id is tied to the human message id
336
+ elif (
337
+ key != "pending"
338
+ and value == None
339
+ and message["state"] != "complete"
340
+ ):
341
+ self.active_messages[key] = message["messageId"]
342
+ self.message_queues[key].put(message)
343
+ return
344
+
345
+ except Exception:
346
+ logger.error(traceback.format_exc())
347
+ self.disconnect_ws()
348
+ self.connect_ws()
349
+
350
+ def send_message(self, chatbot, message, with_chat_break=False, timeout=20):
351
+ # if there is another active message, wait until it has finished sending
352
+ while None in self.active_messages.values():
353
+ time.sleep(0.01)
354
+
355
+ # None indicates that a message is still in progress
356
+ self.active_messages["pending"] = None
357
+
358
+ logger.info(f"Sending message to {chatbot}: {message}")
359
+
360
+ # reconnect websocket
361
+ if not self.ws_connected:
362
+ self.disconnect_ws()
363
+ self.setup_connection()
364
+ self.connect_ws()
365
+
366
+ message_data = self.send_query(
367
+ "SendMessageMutation",
368
+ {
369
+ "bot": chatbot,
370
+ "query": message,
371
+ "chatId": self.bots[chatbot]["chatId"],
372
+ "source": None,
373
+ "withChatBreak": with_chat_break,
374
+ },
375
+ )
376
+ del self.active_messages["pending"]
377
+
378
+ if not message_data["data"]["messageEdgeCreate"]["message"]:
379
+ raise RuntimeError(f"Daily limit reached for {chatbot}.")
380
+ try:
381
+ human_message = message_data["data"]["messageEdgeCreate"]["message"]
382
+ human_message_id = human_message["node"]["messageId"]
383
+ except TypeError:
384
+ raise RuntimeError(
385
+ f"An unknown error occurred. Raw response data: {message_data}"
386
+ )
387
+
388
+ # indicate that the current message is waiting for a response
389
+ self.active_messages[human_message_id] = None
390
+ self.message_queues[human_message_id] = queue.Queue()
391
+
392
+ last_text = ""
393
+ message_id = None
394
+ while True:
395
+ try:
396
+ message = self.message_queues[human_message_id].get(timeout=timeout)
397
+ except queue.Empty:
398
+ del self.active_messages[human_message_id]
399
+ del self.message_queues[human_message_id]
400
+ raise RuntimeError("Response timed out.")
401
+
402
+ # only break when the message is marked as complete
403
+ if message["state"] == "complete":
404
+ if last_text and message["messageId"] == message_id:
405
+ break
406
+ else:
407
+ continue
408
+
409
+ # update info about response
410
+ message["text_new"] = message["text"][len(last_text) :]
411
+ last_text = message["text"]
412
+ message_id = message["messageId"]
413
+
414
+ yield message
415
+
416
+ del self.active_messages[human_message_id]
417
+ del self.message_queues[human_message_id]
418
+
419
+ def send_chat_break(self, chatbot):
420
+ logger.info(f"Sending chat break to {chatbot}")
421
+ result = self.send_query(
422
+ "AddMessageBreakMutation", {"chatId": self.bots[chatbot]["chatId"]}
423
+ )
424
+ return result["data"]["messageBreakCreate"]["message"]
425
+
426
+ def get_message_history(self, chatbot, count=25, cursor=None):
427
+ logger.info(f"Downloading {count} messages from {chatbot}")
428
+
429
+ messages = []
430
+ if cursor == None:
431
+ chat_data = self.get_bot(self.bot_names[chatbot])
432
+ if not chat_data["messagesConnection"]["edges"]:
433
+ return []
434
+ messages = chat_data["messagesConnection"]["edges"][:count]
435
+ cursor = chat_data["messagesConnection"]["pageInfo"]["startCursor"]
436
+ count -= len(messages)
437
+
438
+ cursor = str(cursor)
439
+ if count > 50:
440
+ messages = (
441
+ self.get_message_history(chatbot, count=50, cursor=cursor) + messages
442
+ )
443
+ while count > 0:
444
+ count -= 50
445
+ new_cursor = messages[0]["cursor"]
446
+ new_messages = self.get_message_history(
447
+ chatbot, min(50, count), cursor=new_cursor
448
+ )
449
+ messages = new_messages + messages
450
+ return messages
451
+ elif count <= 0:
452
+ return messages
453
+
454
+ result = self.send_query(
455
+ "ChatListPaginationQuery",
456
+ {"count": count, "cursor": cursor, "id": self.bots[chatbot]["id"]},
457
+ )
458
+ query_messages = result["data"]["node"]["messagesConnection"]["edges"]
459
+ messages = query_messages + messages
460
+ return messages
461
+
462
+ def delete_message(self, message_ids):
463
+ logger.info(f"Deleting messages: {message_ids}")
464
+ if not type(message_ids) is list:
465
+ message_ids = [int(message_ids)]
466
+
467
+ result = self.send_query("DeleteMessageMutation", {"messageIds": message_ids})
468
+
469
+ def purge_conversation(self, chatbot, count=-1):
470
+ logger.info(f"Purging messages from {chatbot}")
471
+ last_messages = self.get_message_history(chatbot, count=50)[::-1]
472
+ while last_messages:
473
+ message_ids = []
474
+ for message in last_messages:
475
+ if count == 0:
476
+ break
477
+ count -= 1
478
+ message_ids.append(message["node"]["messageId"])
479
+
480
+ self.delete_message(message_ids)
481
+
482
+ if count == 0:
483
+ return
484
+ last_messages = self.get_message_history(chatbot, count=50)[::-1]
485
+ logger.info(f"No more messages left to delete.")
486
+
487
+ def create_bot(
488
+ self,
489
+ handle,
490
+ prompt="",
491
+ base_model="chinchilla",
492
+ description="",
493
+ intro_message="",
494
+ api_key=None,
495
+ api_bot=False,
496
+ api_url=None,
497
+ prompt_public=True,
498
+ pfp_url=None,
499
+ linkification=False,
500
+ markdown_rendering=True,
501
+ suggested_replies=False,
502
+ private=False,
503
+ ):
504
+ result = self.send_query(
505
+ "PoeBotCreateMutation",
506
+ {
507
+ "model": base_model,
508
+ "handle": handle,
509
+ "prompt": prompt,
510
+ "isPromptPublic": prompt_public,
511
+ "introduction": intro_message,
512
+ "description": description,
513
+ "profilePictureUrl": pfp_url,
514
+ "apiUrl": api_url,
515
+ "apiKey": api_key,
516
+ "isApiBot": api_bot,
517
+ "hasLinkification": linkification,
518
+ "hasMarkdownRendering": markdown_rendering,
519
+ "hasSuggestedReplies": suggested_replies,
520
+ "isPrivateBot": private,
521
+ },
522
+ )
523
+
524
+ data = result["data"]["poeBotCreate"]
525
+ if data["status"] != "success":
526
+ raise RuntimeError(
527
+ f"Poe returned an error while trying to create a bot: {data['status']}"
528
+ )
529
+ self.get_bots()
530
+ return data
531
+
532
+ def edit_bot(
533
+ self,
534
+ bot_id,
535
+ handle,
536
+ prompt="",
537
+ base_model="chinchilla",
538
+ description="",
539
+ intro_message="",
540
+ api_key=None,
541
+ api_url=None,
542
+ private=False,
543
+ prompt_public=True,
544
+ pfp_url=None,
545
+ linkification=False,
546
+ markdown_rendering=True,
547
+ suggested_replies=False,
548
+ ):
549
+ result = self.send_query(
550
+ "PoeBotEditMutation",
551
+ {
552
+ "baseBot": base_model,
553
+ "botId": bot_id,
554
+ "handle": handle,
555
+ "prompt": prompt,
556
+ "isPromptPublic": prompt_public,
557
+ "introduction": intro_message,
558
+ "description": description,
559
+ "profilePictureUrl": pfp_url,
560
+ "apiUrl": api_url,
561
+ "apiKey": api_key,
562
+ "hasLinkification": linkification,
563
+ "hasMarkdownRendering": markdown_rendering,
564
+ "hasSuggestedReplies": suggested_replies,
565
+ "isPrivateBot": private,
566
+ },
567
+ )
568
+
569
+ data = result["data"]["poeBotEdit"]
570
+ if data["status"] != "success":
571
+ raise RuntimeError(
572
+ f"Poe returned an error while trying to edit a bot: {data['status']}"
573
+ )
574
+ self.get_bots()
575
+ return data
576
+
577
+
578
+ load_queries()
models/gpt4free/quora/cookies.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SmPiNXZI9hBTuf3viz74PA==
2
+ zw7RoKQfeEehiaelYMRWeA==
3
+ NEttgJ_rRQdO05Tppx6hFw==
4
+ 3OnmC0r9njYdNWhWszdQJg==
5
+ 8hZKR7MxwUTEHvO45TEViw==
6
+ Eea6BqK0AmosTKzoI3AAow==
7
+ pUEbtxobN_QUSpLIR8RGww==
8
+ 9_dUWxKkHHhpQRSvCvBk2Q==
9
+ UV45rvGwUwi2qV9QdIbMcw==
10
+ cVIN0pK1Wx-F7zCdUxlYqA==
11
+ UP2wQVds17VFHh6IfCQFrA==
12
+ 18eKr0ME2Tzifdfqat38Aw==
13
+ FNgKEpc2r-XqWe0rHBfYpg==
14
+ juCAh6kB0sUpXHvKik2woA==
15
+ nBvuNYRLaE4xE4HuzBPiIQ==
16
+ oyae3iClomSrk6RJywZ4iw==
17
+ 1Z27Ul8BTdNOhncT5H6wdg==
18
+ wfUfJIlwQwUss8l-3kDt3w==
19
+ f6Jw_Nr0PietpNCtOCXJTw==
20
+ 6Jc3yCs7XhDRNHa4ZML09g==
21
+ 3vy44sIy-ZlTMofFiFDttw==
22
+ p9FbMGGiK1rShKgL3YWkDg==
23
+ pw6LI5Op84lf4HOY7fn91A==
24
+ QemKm6aothMvqcEgeKFDlQ==
25
+ cceZzucA-CEHR0Gt6VLYLQ==
26
+ JRRObMp2RHVn5u4730DPvQ==
27
+ XNt0wLTjX7Z-EsRR3TJMIQ==
28
+ csjjirAUKtT5HT1KZUq1kg==
29
+ 8qZdCatCPQZyS7jsO4hkdQ==
30
+ esnUxcBhvH1DmCJTeld0qw==
models/gpt4free/quora/graphql/AddHumanMessageMutation.graphql ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mutation AddHumanMessageMutation(
2
+ $chatId: BigInt!
3
+ $bot: String!
4
+ $query: String!
5
+ $source: MessageSource
6
+ $withChatBreak: Boolean! = false
7
+ ) {
8
+ messageCreateWithStatus(
9
+ chatId: $chatId
10
+ bot: $bot
11
+ query: $query
12
+ source: $source
13
+ withChatBreak: $withChatBreak
14
+ ) {
15
+ message {
16
+ id
17
+ __typename
18
+ messageId
19
+ text
20
+ linkifiedText
21
+ authorNickname
22
+ state
23
+ vote
24
+ voteReason
25
+ creationTime
26
+ suggestedReplies
27
+ chat {
28
+ id
29
+ shouldShowDisclaimer
30
+ }
31
+ }
32
+ messageLimit{
33
+ canSend
34
+ numMessagesRemaining
35
+ resetTime
36
+ shouldShowReminder
37
+ }
38
+ chatBreak {
39
+ id
40
+ __typename
41
+ messageId
42
+ text
43
+ linkifiedText
44
+ authorNickname
45
+ state
46
+ vote
47
+ voteReason
48
+ creationTime
49
+ suggestedReplies
50
+ }
51
+ }
52
+ }
models/gpt4free/quora/graphql/AddMessageBreakMutation.graphql ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mutation AddMessageBreakMutation($chatId: BigInt!) {
2
+ messageBreakCreate(chatId: $chatId) {
3
+ message {
4
+ id
5
+ __typename
6
+ messageId
7
+ text
8
+ linkifiedText
9
+ authorNickname
10
+ state
11
+ vote
12
+ voteReason
13
+ creationTime
14
+ suggestedReplies
15
+ }
16
+ }
17
+ }