├── .github └── ISSUE_TEMPLATE │ ├── bug_report.yaml │ ├── config.yml │ └── feature_request.yml ├── LICENSE ├── MODEL_LICENSE ├── README.md ├── README_en.md ├── chatglm_parallel.py ├── cli_demo.py ├── examples ├── ad-writing-2.png ├── blog-outline.png ├── comments-writing.png ├── email-writing-1.png ├── email-writing-2.png ├── information-extraction.png ├── role-play.png ├── self-introduction.png ├── sport.png └── tour-guide.png ├── limitations ├── factual_error.png ├── math_error.png ├── self-confusion_google.jpg ├── self-confusion_openai.jpg └── self-confusion_tencent.jpg ├── requirements.txt ├── resources ├── cli-demo.png ├── web-demo.gif └── web-demo.png ├── web_demo.py └── web_demo2.py /.github/ISSUE_TEMPLATE/bug_report.yaml: -------------------------------------------------------------------------------- 1 | name: 🐞 Bug/Help 2 | description: File a bug/issue 3 | title: "[BUG/Help] " 4 | labels: [] 5 | body: 6 | - type: checkboxes 7 | attributes: 8 | label: Is there an existing issue for this? 9 | description: Please search to see if an issue already exists for the bug you encountered. 10 | options: 11 | - label: I have searched the existing issues 12 | required: true 13 | - type: textarea 14 | attributes: 15 | label: Current Behavior 16 | description: | 17 | A concise description of what you're experiencing, with screenshot attached if possible. 18 | Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. 19 | validations: 20 | required: true 21 | - type: textarea 22 | attributes: 23 | label: Expected Behavior 24 | description: A concise description of what you expected to happen. 25 | validations: 26 | required: false 27 | - type: textarea 28 | attributes: 29 | label: Steps To Reproduce 30 | description: Steps to reproduce the behavior. 31 | placeholder: | 32 | 1. In this environment... 33 | 2. With this config... 34 | 3. Run '...' 35 | 4. See error... 36 | validations: 37 | required: true 38 | - type: textarea 39 | attributes: 40 | label: Environment 41 | description: | 42 | examples: 43 | - **OS**: Ubuntu 20.04 44 | - **Python**: 3.8 45 | - **Transformers**: 4.26.1 46 | - **PyTorch**: 1.12 47 | - **CUDA Support**: True 48 | value: | 49 | - OS: 50 | - Python: 51 | - Transformers: 52 | - PyTorch: 53 | - CUDA Support (`python -c "import torch; print(torch.cuda.is_available())"`) : 54 | render: markdown 55 | validations: 56 | required: true 57 | - type: textarea 58 | attributes: 59 | label: Anything else? 60 | description: | 61 | Links? References? Anything that will give us more context about the issue you are encountering! 62 | validations: 63 | required: false 64 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project 3 | title: "[Feature] <title>" 4 | labels: [] 5 | body: 6 | - type: textarea 7 | attributes: 8 | label: Is your feature request related to a problem? Please describe. 9 | description: | 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | validations: 12 | required: false 13 | - type: textarea 14 | attributes: 15 | label: Solutions 16 | description: | 17 | Describe the solution you'd like 18 | A clear and concise description of what you want to happen. 19 | validations: 20 | required: true 21 | - type: textarea 22 | attributes: 23 | label: Additional context 24 | description: Add any other context or screenshots about the feature request here. 25 | validations: 26 | required: false 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /MODEL_LICENSE: -------------------------------------------------------------------------------- 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 glm-130b@googlegroups.com. 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGLM-6B 2 | 3 | ## 修改介绍 4 | 将模型加载到多张gpu卡中,根据gpu的数量自动分配平均的显存占用,需要安装accelerate 5 | ```shell 6 | python -m pip install accelerate 7 | ``` 8 | 请注意,仍然需要24GB的内存, 后续优化 TODO 9 | ## 介绍 10 | 11 | ChatGLM-6B 是一个开源的、支持中英双语的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。 12 | ChatGLM-6B 使用了和 ChatGPT 相似的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。更多信息请参考我们的[博客](https://chatglm.cn/blog)。 13 | 14 | 不过,由于 ChatGLM-6B 的规模较小,目前已知其具有相当多的[**局限性**](#局限性),如事实性/数学逻辑错误,可能生成有害/有偏见内容,较弱的上下文能力,自我认知混乱,以及对英文指示生成与中文指示完全矛盾的内容。请大家在使用前了解这些问题,以免产生误解。更大的基于1300亿参数[GLM-130B](https://github.com/THUDM/GLM-130B)的ChatGLM正在内测开发中。 15 | 16 | *Read this in [English](README_en.md).* 17 | 18 | ## 更新信息 19 | **[2023/03/19]** 增加流式输出接口 `stream_chat`,已更新到网页版和命令行 Demo。修复输出中的中文标点。增加量化后的模型 [ChatGLM-6B-INT4](https://huggingface.co/THUDM/chatglm-6b-int4) 20 | 21 | ## 使用方式 22 | 23 | ### 硬件需求 24 | 25 | | **量化等级** | **最低 GPU 显存** | 26 | | -------------- | ----------------- | 27 | | FP16(无量化) | 13 GB | 28 | | INT8 | 10 GB | 29 | | INT4 | 6 GB | 30 | 31 | ### 环境安装 32 | 33 | 使用 pip 安装依赖:`pip install -r requirements.txt`,其中 `transformers` 库版本推荐为 `4.26.1`,但理论上不低于 `4.23.1` 即可。 34 | 35 | ### 代码调用 36 | 37 | 可以通过如下代码调用 ChatGLM-6B 模型来生成对话: 38 | 39 | ```python 40 | >>> from transformers import AutoTokenizer, AutoModel 41 | >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 42 | >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() 43 | >>> model = model.eval() 44 | >>> response, history = model.chat(tokenizer, "你好", history=[]) 45 | >>> print(response) 46 | 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。 47 | >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history) 48 | >>> print(response) 49 | 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法: 50 | 51 | 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。 52 | 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。 53 | 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。 54 | 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。 55 | 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。 56 | 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。 57 | 58 | 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。 59 | ``` 60 | 完整的模型实现可以在 [Hugging Face Hub](https://huggingface.co/THUDM/chatglm-6b) 上查看。如果你从 Hugging Face Hub 上下载checkpoint的速度较慢,也可以从[这里](https://cloud.tsinghua.edu.cn/d/fb9f16d6dc8f482596c2/)手动下载。 61 | 62 | ### Demo 63 | 64 | 我们提供了一个基于 [Gradio](https://gradio.app) 的网页版 Demo 和一个命令行 Demo。使用时首先需要下载本仓库: 65 | 66 | ```shell 67 | git clone https://github.com/THUDM/ChatGLM-6B 68 | cd ChatGLM-6B 69 | ``` 70 | 71 | #### 网页版 Demo 72 | 73 | ![web-demo](resources/web-demo.gif) 74 | 75 | 首先安装 Gradio:`pip install gradio`,然后运行仓库中的 [web_demo.py](web_demo.py): 76 | 77 | ```shell 78 | python web_demo.py 79 | ``` 80 | 81 | 程序会运行一个 Web Server,并输出地址。在浏览器中打开输出的地址即可使用。最新版 Demo 实现了打字机效果,速度体验大大提升。注意,由于国内 Gradio 的网络访问较为缓慢,启用 `demo.queue().launch(share=True, inbrowser=True)` 时所有网络会经过 Gradio 服务器转发,导致打字机体验大幅下降,现在默认启动方式已经改为 `share=False`,如有需要公网访问的需求,可以重新修改为 `share=True` 启动。 82 | 83 | 感谢[@AdamBear](https://github.com/AdamBear) 实现了基于 Streamlit 的网页版 Demo,运行方式见[#117](https://github.com/THUDM/ChatGLM-6B/pull/117). 84 | 85 | #### 命令行 Demo 86 | 87 | ![cli-demo](resources/cli-demo.png) 88 | 89 | 运行仓库中 [cli_demo.py](cli_demo.py): 90 | 91 | ```shell 92 | python cli_demo.py 93 | ``` 94 | 95 | 程序会在命令行中进行交互式的对话,在命令行中输入指示并回车即可生成回复,输入`clear`可以清空对话历史,输入`stop`终止程序。 96 | 97 | ## 低成本部署 98 | ### 模型量化 99 | 默认情况下,模型以 FP16 精度加载,运行上述代码需要大概 13GB 显存。如果你的 GPU 显存有限,可以尝试以量化方式加载模型,使用方法如下: 100 | 101 | ```python 102 | # 按需修改,目前只支持 4/8 bit 量化 103 | model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().quantize(4).cuda() 104 | ``` 105 | 106 | 进行 2 至 3 轮对话后,8-bit 量化下 GPU 显存占用约为 10GB,4-bit 量化下仅需 6GB 占用。随着对话轮数的增多,对应消耗显存也随之增长,由于采用了相对位置编码,理论上 ChatGLM-6B 支持无限长的 context-length,但总长度超过 2048(训练长度)后性能会逐渐下降。 107 | 108 | 模型量化会带来一定的性能损失,经过测试,ChatGLM-6B 在 4-bit 量化下仍然能够进行自然流畅的生成。使用 [GPT-Q](https://arxiv.org/abs/2210.17323) 等量化方案可以进一步压缩量化精度/提升相同量化精度下的模型性能,欢迎大家提出对应的 Pull Request。 109 | 110 | **[2023/03/19]** 量化过程需要在内存中首先加载 FP16 格式的模型,消耗大概 13GB 的内存。如果你的内存不足的话,可以直接加载量化后的模型,仅需大概 5.2GB 的内存: 111 | ```python 112 | model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda() 113 | ``` 114 | 115 | ### CPU 部署 116 | 如果你没有 GPU 硬件的话,也可以在 CPU 上进行推理,但是推理速度会更慢。使用方法如下(需要大概 32GB 内存) 117 | ```python 118 | model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float() 119 | ``` 120 | 121 | **[2023/03/19]** 如果你的内存不足,可以直接加载量化后的模型: 122 | ```python 123 | model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4",trust_remote_code=True).float() 124 | ``` 125 | 126 | 如果遇到了报错 `Could not find module 'nvcuda.dll'` 或者 `RuntimeError: Unknown platform: darwin` (MacOS) 的话请参考这个[Issue](https://github.com/THUDM/ChatGLM-6B/issues/6#issuecomment-1470060041). 127 | 128 | ## ChatGLM-6B 示例 129 | 130 | 以下是一些使用 `web_demo.py` 得到的示例截图。更多 ChatGLM-6B 的可能,等待你来探索发现! 131 | 132 | <details><summary><b>自我认知</b></summary> 133 | 134 | ![](examples/self-introduction.png) 135 | 136 | </details> 137 | 138 | <details><summary><b>提纲写作</b></summary> 139 | 140 | ![](examples/blog-outline.png) 141 | 142 | </details> 143 | 144 | <details><summary><b>文案写作</b></summary> 145 | 146 | ![](examples/ad-writing-2.png) 147 | 148 | ![](examples/comments-writing.png) 149 | 150 | </details> 151 | 152 | <details><summary><b>邮件写作助手</b></summary> 153 | 154 | ![](examples/email-writing-1.png) 155 | 156 | ![](examples/email-writing-2.png) 157 | 158 | </details> 159 | 160 | <details><summary><b>信息抽取</b></summary> 161 | 162 | ![](examples/information-extraction.png) 163 | 164 | </details> 165 | 166 | <details><summary><b>角色扮演</b></summary> 167 | 168 | ![](examples/role-play.png) 169 | 170 | </details> 171 | 172 | <details><summary><b>评论比较</b></summary> 173 | 174 | ![](examples/sport.png) 175 | 176 | </details> 177 | 178 | <details><summary><b>旅游向导</b></summary> 179 | 180 | ![](examples/tour-guide.png) 181 | 182 | </details> 183 | 184 | ## 局限性 185 | 186 | 由于 ChatGLM-6B 的小规模,其能力仍然有许多局限性。以下是我们目前发现的一些问题: 187 | 188 | - 模型容量较小:6B 的小容量,决定了其相对较弱的模型记忆和语言能力。在面对许多事实性知识任务时,ChatGLM-6B 可能会生成不正确的信息;它也不擅长逻辑类问题(如数学、编程)的解答。 189 | <details><summary><b>点击查看例子</b></summary> 190 | 191 | ![](limitations/factual_error.png) 192 | 193 | ![](limitations/math_error.png) 194 | 195 | </details> 196 | 197 | - 产生有害说明或有偏见的内容:ChatGLM-6B 只是一个初步与人类意图对齐的语言模型,可能会生成有害、有偏见的内容。(内容可能具有冒犯性,此处不展示) 198 | 199 | - 英文能力不足:ChatGLM-6B 训练时使用的指示/回答大部分都是中文的,仅有极小一部分英文内容。因此,如果输入英文指示,回复的质量远不如中文,甚至与中文指示下的内容矛盾,并且出现中英夹杂的情况。 200 | 201 | - 易被误导,对话能力较弱:ChatGLM-6B 对话能力还比较弱,而且 “自我认知” 存在问题,并很容易被误导并产生错误的言论。例如当前版本的模型在被误导的情况下,会在自我认知上发生偏差。 202 | <details><summary><b>点击查看例子</b></summary> 203 | 204 | ![](limitations/self-confusion_google.jpg) 205 | 206 | ![](limitations/self-confusion_openai.jpg) 207 | 208 | ![](limitations/self-confusion_tencent.jpg) 209 | 210 | </details> 211 | 212 | ## 协议 213 | 214 | 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。 215 | 216 | ## 引用 217 | 218 | 如果你觉得我们的工作有帮助的话,请考虑引用下列论文 219 | 220 | ``` 221 | @inproceedings{ 222 | zeng2023glm-130b, 223 | title={{GLM}-130B: An Open Bilingual Pre-trained Model}, 224 | 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}, 225 | booktitle={The Eleventh International Conference on Learning Representations (ICLR)}, 226 | year={2023}, 227 | url={https://openreview.net/forum?id=-Aw0rrrPUF} 228 | } 229 | ``` 230 | ``` 231 | @inproceedings{du2022glm, 232 | title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling}, 233 | author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie}, 234 | booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, 235 | pages={320--335}, 236 | year={2022} 237 | } 238 | ``` 239 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | # ChatGLM-6B 2 | 3 | ## Modification 4 | Load the model into multiple GPUs and automatically allocate the average memory usage according to the number of GPUs. 5 | ```shell 6 | python -m pip install accelerate 7 | ``` 8 | Please note that 24GB of cpu memory is still required. TODO optimization.” 9 | 10 | ## Introduction 11 | 12 | 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). 13 | 14 | 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. 15 | 16 | ## Update 17 | **[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). 18 | 19 | ## Getting Started 20 | 21 | ### Hardware Requirements 22 | 23 | | **Quantization Level** | **GPU Memory** | 24 | |------------------------|----------------| 25 | | FP16(no quantization) | 13 GB | 26 | | INT8 | 10 GB | 27 | | INT4 | 6 GB | 28 | 29 | ### Environment Setup 30 | 31 | Install the requirements with pip: `pip install -r requirements.txt`. `transformers` library version is recommended to be `4.26.1`, but theoretically any version no lower than `4.23.1` is acceptable. 32 | 33 | ### Usage 34 | 35 | Generate dialogue with the following code 36 | 37 | ```python 38 | >>> from transformers import AutoTokenizer, AutoModel 39 | >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 40 | >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() 41 | >>> model = model.eval() 42 | >>> response, history = model.chat(tokenizer, "你好", history=[]) 43 | >>> print(response) 44 | 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。 45 | >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history) 46 | >>> print(response) 47 | 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法: 48 | 49 | 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。 50 | 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。 51 | 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。 52 | 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。 53 | 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。 54 | 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。 55 | 56 | 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。 57 | ``` 58 | 59 | The full model implementation is on [HuggingFace Hub](https://huggingface.co/THUDM/chatglm-6b). 60 | 61 | ### Demo 62 | 63 | We provide a Web demo based on [Gradio](https://gradio.app) and a command line demo in the repo. First clone our repo with: 64 | 65 | ```shell 66 | git clone https://github.com/THUDM/ChatGLM-6B 67 | cd ChatGLM-6B 68 | ``` 69 | 70 | #### Web Demo 71 | 72 | ![web-demo](resources/web-demo.png) 73 | 74 | Install Gradio `pip install gradio`,and run [web_demo.py](web_demo.py): 75 | 76 | ```shell 77 | python web_demo.py 78 | ``` 79 | 80 | The program runs a web server and outputs the URL. Open the URL in the browser to use the web demo. 81 | 82 | #### CLI Demo 83 | 84 | ![cli-demo](resources/cli-demo.png) 85 | 86 | Run [cli_demo.py](cli_demo.py) in the repo: 87 | 88 | ```shell 89 | python cli_demo.py 90 | ``` 91 | 92 | 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. 93 | 94 | ## Deployment 95 | 96 | ### Quantization 97 | 98 | 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: 99 | 100 | ```python 101 | # Change according to your hardware. Only support 4/8 bit quantization now. 102 | model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().quantize(4).cuda() 103 | ``` 104 | 105 | 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). 106 | 107 | 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. 108 | 109 | **[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: 110 | ```python 111 | model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda() 112 | ``` 113 | 114 | ### CPU Deployment 115 | 116 | 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): 117 | 118 | ```python 119 | model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float() 120 | ``` 121 | 122 | **[2023/03/19]** If your CPU memory is limited, you can directly load the quantized model: 123 | ```python 124 | model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).float() 125 | ``` 126 | 127 | **For Mac users**: if your encounter the error `RuntimeError: Unknown platform: darwin`, please refer to this [Issue](https://github.com/THUDM/ChatGLM-6B/issues/6#issuecomment-1470060041). 128 | 129 | ## ChatGLM-6B Examples 130 | 131 | The following are some Chinese examples with `web_demo.py`. Welcome to explore more possibility with ChatGLM-6B. 132 | 133 | <details><summary><b>Self Cognition</b></summary> 134 | 135 | ![](examples/self-introduction.png) 136 | 137 | </details> 138 | 139 | <details><summary><b>Outline</b></summary> 140 | 141 | ![](examples/blog-outline.png) 142 | 143 | </details> 144 | 145 | <details><summary><b>Ad</b></summary> 146 | 147 | ![](examples/ad-writing-2.png) 148 | 149 | ![](examples/comments-writing.png) 150 | 151 | </details> 152 | 153 | <details><summary><b>Email</b></summary> 154 | 155 | ![](examples/email-writing-1.png) 156 | 157 | ![](examples/email-writing-2.png) 158 | 159 | </details> 160 | 161 | <details><summary><b>Information Extraction</b></summary> 162 | 163 | ![](examples/information-extraction.png) 164 | 165 | </details> 166 | 167 | <details><summary><b>Role Play</b></summary> 168 | 169 | ![](examples/role-play.png) 170 | 171 | </details> 172 | 173 | <details><summary><b>Comparison</b></summary> 174 | 175 | ![](examples/sport.png) 176 | 177 | </details> 178 | 179 | <details><summary><b>Travel Guide</b></summary> 180 | 181 | ![](examples/tour-guide.png) 182 | 183 | </details> 184 | 185 | ## License 186 | 187 | 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)。 188 | 189 | ## Citation 190 | 191 | If you find our work useful, please consider citing the following papers: 192 | 193 | ``` 194 | @inproceedings{ 195 | zeng2023glm-130b, 196 | title={{GLM}-130B: An Open Bilingual Pre-trained Model}, 197 | 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}, 198 | booktitle={The Eleventh International Conference on Learning Representations (ICLR)}, 199 | year={2023}, 200 | url={https://openreview.net/forum?id=-Aw0rrrPUF} 201 | } 202 | ``` 203 | 204 | ``` 205 | @inproceedings{du2022glm, 206 | title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling}, 207 | author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie}, 208 | booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, 209 | pages={320--335}, 210 | year={2022} 211 | } 212 | ``` 213 | -------------------------------------------------------------------------------- /chatglm_parallel.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Author: lichuang 3 | Date: 2023-03-23 09:18:13 4 | Description: 将模型加载到多张GPU卡中,根据gpu的数量自动分配平均的显存占用 5 | ''' 6 | 7 | from transformers import AutoModel, AutoTokenizer 8 | from accelerate import load_checkpoint_and_dispatch 9 | 10 | 11 | def load_model_on_gpus(checkpoint_path, num_gpus=2): 12 | # 总共占用13GB显存,28层transformer每层0.39GB左右 13 | # 第一层 word_embeddings和最后一层 lm_head 层各占用1.2GB左右 14 | num_trans_layers = 28 15 | vram_per_layer = 0.39 16 | average = 13/num_gpus 17 | used = 1.2 18 | device_map = {'transformer.word_embeddings': 0, 19 | 'transformer.final_layernorm': num_gpus-1, 'lm_head': num_gpus-1} 20 | gpu_target = 0 21 | for i in range(num_trans_layers): 22 | if used > average-vram_per_layer/2 and gpu_target < num_gpus: 23 | gpu_target += 1 24 | used = 0 25 | else: 26 | used += vram_per_layer 27 | device_map['transformer.layers.%d' % i] = gpu_target 28 | 29 | model = AutoModel.from_pretrained( 30 | checkpoint_path, trust_remote_code=True) 31 | model = model.eval() 32 | model = load_checkpoint_and_dispatch( 33 | model, checkpoint_path, device_map=device_map, offload_folder="offload", offload_state_dict=True).half() 34 | return model 35 | -------------------------------------------------------------------------------- /cli_demo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | from transformers import AutoTokenizer, AutoModel 4 | from chatglm_parallel import load_model_on_gpus 5 | 6 | tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 7 | model = load_model_on_gpus("THUDM/chatglm-6b", num_gpus=2) 8 | 9 | os_name = platform.system() 10 | clear_command = 'cls' if os_name == 'Windows' else 'clear' 11 | 12 | 13 | def build_prompt(history): 14 | prompt = "欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序" 15 | for query, response in history: 16 | prompt += f"\n\n用户:{query}" 17 | prompt += f"\n\nChatGLM-6B:{response}" 18 | return prompt 19 | 20 | 21 | def main(): 22 | history = [] 23 | print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") 24 | while True: 25 | query = input("\n用户:") 26 | if query == "stop": 27 | break 28 | if query == "clear": 29 | history = [] 30 | os.system(clear_command) 31 | print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") 32 | continue 33 | count = 0 34 | for response, history in model.stream_chat(tokenizer, query, history=history): 35 | count += 1 36 | if count % 8 == 0: 37 | os.system(clear_command) 38 | print(build_prompt(history), flush=True) 39 | os.system(clear_command) 40 | print(build_prompt(history), flush=True) 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /examples/ad-writing-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/ad-writing-2.png -------------------------------------------------------------------------------- /examples/blog-outline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/blog-outline.png -------------------------------------------------------------------------------- /examples/comments-writing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/comments-writing.png -------------------------------------------------------------------------------- /examples/email-writing-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/email-writing-1.png -------------------------------------------------------------------------------- /examples/email-writing-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/email-writing-2.png -------------------------------------------------------------------------------- /examples/information-extraction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/information-extraction.png -------------------------------------------------------------------------------- /examples/role-play.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/role-play.png -------------------------------------------------------------------------------- /examples/self-introduction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/self-introduction.png -------------------------------------------------------------------------------- /examples/sport.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/sport.png -------------------------------------------------------------------------------- /examples/tour-guide.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/examples/tour-guide.png -------------------------------------------------------------------------------- /limitations/factual_error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/limitations/factual_error.png -------------------------------------------------------------------------------- /limitations/math_error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/limitations/math_error.png -------------------------------------------------------------------------------- /limitations/self-confusion_google.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/limitations/self-confusion_google.jpg -------------------------------------------------------------------------------- /limitations/self-confusion_openai.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/limitations/self-confusion_openai.jpg -------------------------------------------------------------------------------- /limitations/self-confusion_tencent.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/limitations/self-confusion_tencent.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | protobuf>=3.19.5,<3.20.1 2 | transformers==4.26.1 3 | icetk 4 | cpm_kernels 5 | torch>=1.10 6 | gradio 7 | -------------------------------------------------------------------------------- /resources/cli-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/resources/cli-demo.png -------------------------------------------------------------------------------- /resources/web-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/resources/web-demo.gif -------------------------------------------------------------------------------- /resources/web-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChuangLee/ChatGLM-6B-multiGPU/de9f26c2018943662e829a787f96d981c8ec8b1d/resources/web-demo.png -------------------------------------------------------------------------------- /web_demo.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoModel, AutoTokenizer 2 | import gradio as gr 3 | from chatglm_parallel import load_model_on_gpus 4 | 5 | tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 6 | model = load_model_on_gpus("THUDM/chatglm-6b", num_gpus=2) 7 | 8 | MAX_TURNS = 20 9 | MAX_BOXES = MAX_TURNS * 2 10 | 11 | 12 | def predict(input, max_length, top_p, temperature, history=None): 13 | if history is None: 14 | history = [] 15 | for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p, 16 | temperature=temperature): 17 | updates = [] 18 | for query, response in history: 19 | updates.append(gr.update(visible=True, value="用户:" + query)) 20 | updates.append(gr.update(visible=True, value="ChatGLM-6B:" + response)) 21 | if len(updates) < MAX_BOXES: 22 | updates = updates + [gr.Textbox.update(visible=False)] * (MAX_BOXES - len(updates)) 23 | yield [history] + updates 24 | 25 | 26 | with gr.Blocks() as demo: 27 | state = gr.State([]) 28 | text_boxes = [] 29 | for i in range(MAX_BOXES): 30 | if i % 2 == 0: 31 | text_boxes.append(gr.Markdown(visible=False, label="提问:")) 32 | else: 33 | text_boxes.append(gr.Markdown(visible=False, label="回复:")) 34 | 35 | with gr.Row(): 36 | with gr.Column(scale=4): 37 | txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter", lines=11).style( 38 | container=False) 39 | with gr.Column(scale=1): 40 | max_length = gr.Slider(0, 4096, value=2048, step=1.0, label="Maximum length", interactive=True) 41 | top_p = gr.Slider(0, 1, value=0.7, step=0.01, label="Top P", interactive=True) 42 | temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True) 43 | button = gr.Button("Generate") 44 | button.click(predict, [txt, max_length, top_p, temperature, state], [state] + text_boxes) 45 | demo.queue().launch(share=False, inbrowser=True) 46 | -------------------------------------------------------------------------------- /web_demo2.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoModel, AutoTokenizer 2 | import streamlit as st 3 | from streamlit_chat import message 4 | from chatglm_parallel import load_model_on_gpus 5 | 6 | 7 | st.set_page_config( 8 | page_title="ChatGLM-6b 演示", 9 | page_icon=":robot:" 10 | ) 11 | 12 | 13 | @st.cache_resource 14 | def get_model(): 15 | tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 16 | model = load_model_on_gpus("THUDM/chatglm-6b", num_gpus=2) 17 | return tokenizer, model 18 | 19 | 20 | MAX_TURNS = 20 21 | MAX_BOXES = MAX_TURNS * 2 22 | 23 | 24 | def predict(input, history=None): 25 | tokenizer, model = get_model() 26 | if history is None: 27 | history = [] 28 | response, history = model.chat(tokenizer, input, history) 29 | 30 | for i, (query, response) in enumerate(history): 31 | message(query, avatar_style="big-smile", key=str(i) + "_user") 32 | message(response, avatar_style="bottts", key=str(i)) 33 | 34 | return history 35 | 36 | 37 | # create a prompt text for the text generation 38 | prompt_text = st.text_area(label="用户命令输入", 39 | height = 100, 40 | placeholder="请在这儿输入您的命令") 41 | 42 | if 'state' not in st.session_state: 43 | st.session_state['state'] = [] 44 | 45 | if st.button("发送", key="predict"): 46 | with st.spinner("AI正在思考,请稍等........"): 47 | # text generation 48 | st.session_state["state"] = predict(prompt_text, st.session_state["state"]) 49 | 50 | st.balloons() --------------------------------------------------------------------------------