[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yaml",
    "content": "name: \"\\U0001F41B Bug Report\"\ndescription: Submit a bug report to help us improve GLM-4-9B / 提交一个 Bug 问题报告来帮助我们改进 GLM-4-9B\nbody:\n  - type: textarea\n    id: system-info\n    attributes:\n      label: System Info / 系統信息\n      description: Your operating environment / 您的运行环境信息\n      placeholder: Includes Cuda version, Transformers version, Python version, operating system, hardware information (if you suspect a hardware problem)... / 包括Cuda版本，Transformers版本，Python版本，操作系统，硬件信息(如果您怀疑是硬件方面的问题)...\n    validations:\n      required: true\n\n  - type: textarea\n    id: who-can-help\n    attributes:\n      label: Who can help? / 谁可以帮助到您？\n      description: |\n        Your issue will be replied to more quickly if you can figure out the right person to tag with @\n        All issues are read by one of the maintainers, so if you don't know who to tag, just leave this blank and our maintainer will ping the right person.\n\n        Please tag fewer than 3 people.\n\n        如果您能找到合适的标签 @，您的问题会更快得到回复。\n        所有问题都会由我们的维护者阅读，如果您不知道该标记谁，只需留空，我们的维护人员会找到合适的开发组成员来解决问题。\n\n        标记的人数应该不超过 3 个人。\n\n        If it's not a bug in these three subsections, you may not specify the helper. Our maintainer will find the right person in the development group to solve the problem.\n\n        如果不是这三个子版块的bug，您可以不指明帮助者，我们的维护人员会找到合适的开发组成员来解决问题。\n\n      placeholder: \"@Username ...\"\n\n  - type: checkboxes\n    id: information-scripts-examples\n    attributes:\n      label: Information / 问题信息\n      description: 'The problem arises when using: / 问题出现在'\n      options:\n        - label: \"The official example scripts / 官方的示例脚本\"\n        - label: \"My own modified scripts / 我自己修改的脚本和任务\"\n\n  - type: textarea\n    id: reproduction\n    validations:\n      required: true\n    attributes:\n      label: Reproduction / 复现过程\n      description: |\n        Please provide a code example that reproduces the problem you encountered, preferably with a minimal reproduction unit.\n        If you have code snippets, error messages, stack traces, please provide them here as well.\n        Please format your code correctly using code tags. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting\n        Do not use screenshots, as they are difficult to read and (more importantly) do not allow others to copy and paste your code.\n\n        请提供能重现您遇到的问题的代码示例,最好是最小复现单元。\n        如果您有代码片段、错误信息、堆栈跟踪，也请在此提供。\n        请使用代码标签正确格式化您的代码。请参见 https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting\n        请勿使用截图，因为截图难以阅读，而且（更重要的是）不允许他人复制粘贴您的代码。\n      placeholder: |\n        Steps to reproduce the behavior/复现Bug的步骤:\n\n          1.\n          2.\n          3.\n\n  - type: textarea\n    id: expected-behavior\n    validations:\n      required: true\n    attributes:\n      label: Expected behavior / 期待表现\n      description: \"A clear and concise description of what you would expect to happen. /简单描述您期望发生的事情。\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.yaml",
    "content": "name: \"\\U0001F680 Feature request\"\ndescription: Submit a request for a new GLM-4-9B feature / 提交一个新的 GLM-4-9B 的功能建议\nlabels: [ \"feature\" ]\nbody:\n  - type: textarea\n    id: feature-request\n    validations:\n      required: true\n    attributes:\n      label: Feature request  / 功能建议\n      description: |\n        A brief description of the functional proposal. Links to corresponding papers and code are desirable.\n        对功能建议的简述。最好提供对应的论文和代码链接\n\n  - type: textarea\n    id: motivation\n    validations:\n      required: true\n    attributes:\n      label: Motivation / 动机\n      description: |\n        Your motivation for making the suggestion. If that motivation is related to another GitHub issue, link to it here.\n        您提出建议的动机。如果该动机与另一个 GitHub 问题有关，请在此处提供对应的链接。\n\n  - type: textarea\n    id: contribution\n    validations:\n      required: true\n    attributes:\n      label: Your contribution / 您的贡献\n      description: |\n\n        Your PR link or any other link you can help with.\n        您的PR链接或者其他您能提供帮助的链接。\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "# Contribution Guide\n\nWe welcome your contributions to this repository. To ensure elegant code style and better code quality, we have prepared the following contribution guidelines.\n\n## What We Accept\n\n+ This PR fixes a typo or improves the documentation (if this is the case, you may skip the other checks).\n+ This PR fixes a specific issue — please reference the issue number in the PR description. Make sure your code strictly follows the coding standards below.\n+ This PR introduces a new feature — please clearly explain the necessity and implementation of the feature. Make sure your code strictly follows the coding standards below.\n\n## Code Style Guide\n\nGood code style is an art. We have prepared a `pyproject.toml` and a `pre-commit` hook to enforce consistent code formatting across the project. You can clean up your code following the steps below:\n\n1. Install the required dependencies:\n```shell\n    pip install ruff pre-commit\n```\n2. Then, run the following command:\n```shell\n    pre-commit run --all-files\n```\nIf your code complies with the standards, you should not see any errors.\n\n## Naming Conventions\n\n- Please use **English** for naming; do not use Pinyin or other languages. All comments should also be in English.\n- Follow **PEP8** naming conventions strictly, and use underscores to separate words. Avoid meaningless names such as `a`, `b`, `c`.\n"
  },
  {
    "path": ".gitignore",
    "content": "*venv\n*.DS_Store\n*.idea/\ndataset\ntest*\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.4.5\n    hooks:\n      - id: ruff\n        args: [--fix, --respect-gitignore, --config=pyproject.toml]\n      - id: ruff-format\n        args: [--config=pyproject.toml]\n\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.5.0\n    hooks:\n      - id: trailing-whitespace\n      - id: end-of-file-fixer\n      - id: check-yaml\n      - id: check-toml\n      - id: check-case-conflict\n      - id: check-merge-conflict\n      - id: debug-statements\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2025 Zhipu AI\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# GLM-4-0414 Model Series\n\n<p align=\"center\">\n👋 Join our <a href=\"https://discord.gg/8cnQKdAprg\" target=\"_blank\">Discord</a>, <a href=\"https://x.com/Zai_org\" target=\"_blank\">X</a> and <a href=\"resources/WECHAT.md\" target=\"_blank\"> WeChat (Chinese) </a>\n</p>\n<p align=\"center\">\n📍The open-source models released this time can be experienced for free at <a href=\"https://chat.z.ai\">Z.ai</a>; for GLM commercial model services, please visit <a href=\"https://bigmodel.cn\">bigmodel.cn</a>.\n</p>\n\nRead this in [中文](README_zh.md)\n\n## Project Updates\n\n- 🔥 **News**: ```2025/07/02```: We are releasing the [GLM-4.1V-9B-Thinking](https://huggingface.co/collections/THUDM/glm-41v-thinking-6862bbfc44593a8601c2578d) series VLM, check [this github repo](https://github.com/THUDM/GLM-4.1V-Thinking) to get more information.\n- **News**: ```2025/04/14```: We are releasing the [GLM-4-32B-0414](https://huggingface.co/collections/THUDM/glm-4-0414-67f3cbcb34dd9d252707cb2e) series models, scaled up to 32B parameters, including models with capabilities for dialogue, reasoning, and rumination.\n- **News**: ``2024/06/18``: We have released our [Technical Report](https://arxiv.org/pdf/2406.12793), feel free to check it out.\n- **News**: ``2024/06/05``: We released the `GLM-4-9B` series of open-source models. Details can be found [here](README_20240605.md).\n\n## Model Introduction\n\nThe GLM family welcomes new members, the **GLM-4-32B-0414** series models, featuring 32 billion parameters. Its performance is comparable to OpenAI’s GPT series and DeepSeek’s V3/R1 series. It also supports very user-friendly local deployment features. GLM-4-32B-Base-0414 was pre-trained on 15T of high-quality data, including substantial reasoning-type synthetic data. This lays the foundation for subsequent reinforcement learning extensions. In the post-training stage, we employed human preference alignment for dialogue scenarios. Additionally, using techniques like rejection sampling and reinforcement learning, we enhanced the model’s performance in instruction following, engineering code, and function calling, thus strengthening the atomic capabilities required for agent tasks. GLM-4-32B-0414 achieves good results in engineering code, Artifact generation, function calling, search-based Q&A, and report generation. In particular, on several benchmarks, such as code generation or specific Q&A tasks, GLM-4-32B-Base-0414 achieves comparable performance with those larger models like GPT-4o and DeepSeek-V3-0324 (671B).\n\n**GLM-Z1-32B-0414** is a reasoning model with deep thinking capabilities. This was developed based on GLM-4-32B-0414 through cold start, extended reinforcement learning, and further training on tasks including mathematics, code, and logic. Compared to the base model, GLM-Z1-32B-0414 significantly improves mathematical abilities and the capability to solve complex tasks. During training, we also introduced general reinforcement learning based on pairwise ranking feedback, which enhances the model's general capabilities.\n\n**GLM-Z1-Rumination-32B-0414** is a deep reasoning model with rumination capabilities (against OpenAI's Deep Research). Unlike typical deep thinking models, the rumination model is capable of deeper and longer thinking to solve more open-ended and complex problems (e.g., writing a comparative analysis of AI development in two cities and their future development plans). Z1-Rumination is trained through scaling end-to-end reinforcement learning with responses graded by the ground truth answers or rubrics and can make use of search tools during its deep thinking process to handle complex tasks. The model shows significant improvements in research-style writing and complex  tasks.\n\nFinally, **GLM-Z1-9B-0414** is a surprise. We employed all the aforementioned techniques to train a small model (9B). GLM-Z1-9B-0414  exhibits excellent capabilities in mathematical reasoning and general tasks. Its overall performance is top-ranked among all open-source models of the same size. Especially in resource-constrained scenarios, this model achieves an excellent balance between efficiency and effectiveness, providing a powerful option for users seeking lightweight deployment.\n\n\n## Showcase\n\n### Animation Generation\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-Z1-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <video src=\"https://github.com/user-attachments/assets/849ff9fd-b54d-4c74-9ee5-3412e1a09e32\"\n             style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n        write a Python program that shows a ball bouncing inside a spinning hexagon. The ball should be affected by gravity and friction, and it must bounce off the rotating walls realistically\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <video src=\"https://github.com/user-attachments/assets/8dccdb9d-cc44-4732-b438-74a4e3cb9dfb\"\n             style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n         Use HTML to simulate the scenario of a small ball released from the center of a rotating hexagon. Consider the collision between the ball and the hexagon's edges, the gravity acting on the ball, and assume all collisions are perfectly elastic. (Prompt translated from Chinese)\n      </div>\n    </td>\n  </tr>\n</table>\n\n### Web Design\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/bd9c1fc1-c784-4e8f-9c76-5f7389a715f1\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n          Design a drawing board that supports custom function plotting, allowing adding and deleting custom functions, and assigning colors to functions. (Prompt translated from Chinese)\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/7ad12d52-9229-4278-8d1b-ffbf43e99070\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\"> Design a UI for a mobile machine learning platform, which should include interfaces for training tasks, storage management, and personal statistics. The personal statistics interface should use charts to display the user's resource usage over a period. Use Tailwind CSS to style the page, and display these 3 mobile interfaces tiled on a single HTML page. (Prompt translated from Chinese) </div>\n    </td>\n  </tr>\n</table>\n\n### SVG Generation\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/9407e4c1-1876-4ab5-838c-839836fb418a\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n          Create a misty Jiangnan scene using SVG. (Prompt translated from Chinese)\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/bcce8c5a-cedf-45c8-b666-ddb023d5b49c\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\"> Use SVG to illustrate the training process of an LLM. (Prompt translated from Chinese) </div>\n    </td>\n  </tr>\n</table>\n\n### Analysis and Research Report Writing\n\n<td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n  <video src=\"https://github.com/user-attachments/assets/7939c8c5-0fcf-4bc4-be45-3964aad0e61c\" style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n  <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n    Analysis of AI Development in Chinese Cities: A Comparative Study of Beijing and Hangzhou, Alongside an Investigation of International Cases of AI in Urban Governance. (Prompt translated from Chinese)\n  </div>\n</td>\n\n## Model List\n\n### GLM-4-0414 Series Models\n\nGLM-Z1-9B-0414 Open-Source Model [Try it Online](https://modelscope.cn/studios/ZhipuAI/GLM-Z1-9B-0414/summary)\n\n|           Model            |   Type    | Seq Length* |                                                                                                                                                              Download                                                                                                                                                              |\n|:--------------------------:|:---------:|:-----------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|       GLM-4-9B-0414        |   Chat    | 32K -> 128K |                           [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-9B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-9B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-9B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-0414)                           |\n|       GLM-Z1-9B-0414       | Reasoning | 32K -> 128K |                        [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-Z1-9B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-9B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-9B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-9B-0414)                        |\n|    GLM-4-32B-Base-0414     |   Base    | 32K -> 128K |               [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-32B-Base-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-32B-Base-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-32B-Base-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-32B-Base-0414)               |\n|       GLM-4-32B-0414       |   Chat    | 32K -> 128K |                      [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-32B-Base-0414)                       |\n|      GLM-Z1-32B-0414       | Reasoning | 32K -> 128K |                       [🤗 Huggingface](https://huggingface.co/THUDM/GLM-Z1-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-32B-0414)                       |\n| GLM-Z1-Rumination-32B-0414 | Reasoning |    128K     | [🤗 Huggingface](https://huggingface.co/THUDM/GLM-Z1-Rumination-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-Rumination-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-Rumination-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-Rumination-32B-0414) |\n\nDue to its smaller model capacity, GLM-4-9B-0414 has not undergone the same agent capability enhancements as GLM-4-32B-0414. Instead, it has been optimized primarily for scenarios that require large-scale batch operations, such as translation tasks.\n\n\\* Models are natively trained with a 32K context. For requests where the total input + output length might exceed 32K tokens, we recommend activating YaRN for better extrapolation performance. See the [Model and Prompt Implementation](#model-and-prompt-implementation) section for details.\n\nBelow are the GLM-4 series models released on June 5, 2024. Details can be found [here](README_240605.md).\n\n|             Model             |   Type    | Seq Length* |                                                                                                      Download                                                                                                       |\n|:-----------------------------:|:---------:|:----------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|      GLM-4-9B       | Base |     8K     |                                           [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b)<br>                                            |\n|    GLM-4-9B-Chat    | Chat |    128K    |     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat)      |\n|  GLM-4-9B-Chat-HF   | Chat |    128K    |                                     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-hf)                                      |\n|  GLM-4-9B-Chat-1M   | Chat |     1M     | [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat-1M) |\n| GLM-4-9B-Chat-1M-HF | Chat |     1M     |                                  [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m-hf)                                   |\n|      GLM-4V-9B      | Chat |     8K     |        [🤗 Huggingface](https://huggingface.co/THUDM/glm-4v-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4v-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4V-9B)               |\n\n## Evaluation Results\n\n### GLM-4-0414 Series\n\n<div style=\"text-align: center;\">\n  <img src=\"resources/Bench-32B.png\" style=\"width: 80%;\" />\n</div>\n\n| Model             | IFEval | BFCL-v3 (Overall) | BFCL-v3 (MultiTurn) | TAU-Bench (Retail) | TAU-Bench (Airline) | SimpleQA | HotpotQA |\n| ---------------- | ------ | ----------------- | ------------------- | ------------------ | ------------------- | -------- | -------- |\n| Qwen2.5-Max      | 85.6   | 50.9              | 30.5                | 58.3               | 22.0                | 79.0     | 52.8     |\n| GPT-4o-1120      | 81.9   | 69.6              | 41.0                | 62.8               | 46.0                | 82.8     | 63.9     |\n| DeepSeek-V3-0324 | 83.4   | 66.2              | 35.8                | 60.7               | 32.4                | 82.6     | 54.6     |\n| DeepSeek-R1      | 84.3   | 57.5              | 12.4                | 33.0               | 37.3                | 83.9     | 63.1     |\n| GLM-4-32B-0414   | 87.6   | 69.6              | 41.5                | 68.7               | 51.2                | 88.1     | 63.8     |\n\n> For `SimpleQA` and `HotpotQA`, we sampled nearly 500 test cases from each test set, provided all models with basic `search` and `click` tools, ensured other settings remained consistent, and averaged the results over 3 runs.\n\n| Model  | Framework  | [SWE-bench Verified](https://openai.com/index/introducing-swe-bench-verified/)  | [SWE-bench Verified mini](https://github.com/mariushobbhahn/SWEBench-verified-mini) |\n|---|---|---|---|\n| GLM-4-32B-0414  | Moatless<sup>[1]</sup> | 33.8 | 38.0 |\n| GLM-4-32B-0414  | Agentless<sup>[2]</sup>  | 30.7 | 34.0 |\n| GLM-4-32B-0414  | OpenHands<sup>[3]</sup> | 27.2  | 28.0  |\n\n[1] [Moatless v0.0.3](https://github.com/aorwall/moatless-tools) used the following parameters: `response_format=\"react\", thoughts_in_action=False, max_interations=30`. No retries on failed trajectories; other settings are default.\n\n[2] [Agentless v1.5.0](https://github.com/OpenAutoCoder/Agentless) used [BGE](https://github.com/FlagOpen/FlagEmbedding/blob/master/README.md) as the embedding model and [FAISS](https://github.com/facebookresearch/faiss) for similarity search. To speed up patch verification while maintaining performance, the timeout for running a single instance was changed from the default 300s to 180s.\n\n[3] [OpenHands v0.29.1](https://github.com/All-Hands-AI/OpenHands/tree/main) did not use YaRN context extension but limited runs to a maximum of 60 iterations and summarized the history to prevent exceeding the 32K context limit. Summarization was configured as `llm_config=\"condenser\", keep_first=1, max_size=32`. No retries on failed trajectories.\n\n### GLM-Z1-0414 Series\n\n<div style=\"text-align: center;\">\n  <img src=\"resources/Bench-Z1-9B.png\" style=\"width: 80%;\" />\n  <img src=\"resources/Bench-Z1-32B.png\" style=\"width: 80%;\" />\n</div>\n\n## Model and Prompt Implementation\n\n### Model Implementation\n\nIf you want to see our model implementation, please check the Pull Requests in the relevant repositories, which have been merged:\n\n+ [vLLM Model Implementation](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/models/glm4.py)\n+ [transformers Model Implementation](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm4/modeling_glm4.py)\n+ [llama.cpp Model Implementation](https://github.com/ggml-org/llama.cpp/pull/12867)\n\n### Handling Long Context (YaRN)\n\nIf the total input + output token count might exceed the model's native context length (mostly 32k for the GLM-4-0414 series), it is recommended to enable YaRN to achieve better long-context modeling capabilities. For supported frameworks, you can modify the corresponding `config.json`. Specifically, for GLM-Z1 series models, consider enabling YaRN (Rope Scaling) when the input length exceeds **8,192 tokens**.\n\n```json\n\"rope_scaling\": {\n    \"factor\": 4.0,\n    \"original_max_position_embeddings\": 32768,\n    \"type\": \"yarn\"\n}\n```\nFor most user requests, if the input + output token count does not exceed the native context length, no modifications are needed.\n\n### Model Fine-tuning\n\nYou can find information about the computational resources required for model fine-tuning, as well as example fine-tuning scripts, in `finetune/README.md`.\n\nTo start a simple model fine-tuning example, run the following commands:\n\n```shell\ncd finetune\npip install -r ../inference/requirements.txt\npip install -r requirements.txt\n# Use single GPU for Chat Fine-tune\npython finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml\n```\n\n🎉 The script also supports fine-tuning with visual tracking using **SwanLab**. You can view the training logs of the example fine-tuning script on the [SwanLab Visualization Dashboard](https://swanlab.cn/@ShaohonChen/GLM4-Finetune/overview).\n\n### Prompt Implementation\n\nIf you use the `apply_chat_template` method provided by the `transformers` library to construct prompts, here are the restrictions on `System Prompts` for different GLM-4-0414 models.\n\n+ `GLM-4-32B-Base-0414`: Base model, no chat template.\n+ `GLM-4-*-0414` / `GLM-Z1-*-0414`: If `tools` are provided, `apply_chat_template` will populate the tools into a fixed template within the `chat_template`, creating a separate `system` message with tool bindings prepended to the message list (`messages[0]`). All originally passed `messages` are automatically shifted one position back.\n+ `GLM-Z1-Rumination-32B-0414`:\n    + Does not support custom system prompts or custom tools. Your `tools` and `system` fields will be ignored by `apply_chat_template`. Using this model requires an external search engine or a custom retrieval API.\n    + Supports four tools in total:\n        ```\n        1. search\n           Description: Executes a search query and returns search results. Use this when you need to find information about a specific topic.\n           Parameters: query (string) - The search query string. Use English words unless it's a Chinese proper noun.\n\n        2. click\n           Description: Clicks on a link from the search results and navigates to the corresponding page. Use this when you need to view the detailed content of a specific search result.\n           Parameters: link_id (integer) - The ID of the link to click (from the sequence number in the search results).\n\n        3. open\n           Description: Opens a specific website. Gets the content of any website via URL.\n           Parameters: url (string) - The target website URL or domain name.\n\n        4. finish\n           Description: Completes the task. Use this when you have found the required information.\n           Parameters: None\n        ```\n    + The fixed template in `chat_template` uses English for the thought process. If you want to change to another language, you need to modify the following section (currently supports Chinese and English):\n        ```\n        <Important Configuration>\n        - Language Used\n            * Search Keywords: English -> Change here to \"Chinese\" or another language\n            * Thinking: English -> Change here to \"Chinese\" or another language\n        ```\n\nTo see the specific chat templates for the GLM-4-0414 series models, please check the `chat_template.jinja` file in the corresponding model repository.\n\n## Citation\n\nIf you find our work helpful, please consider citing the following paper.\n\n```bibtex\n@misc{glm2024chatglm,\n      title={ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools},\n      author={Team GLM and Aohan Zeng and Bin Xu and Bowen Wang and Chenhui Zhang and Da Yin and Diego Rojas and Guanyu Feng and Hanlin Zhao and Hanyu Lai and Hao Yu and Hongning Wang and Jiadai Sun and Jiajie Zhang and Jiale Cheng and Jiayi Gui and Jie Tang and Jing Zhang and Juanzi Li and Lei Zhao and Lindong Wu and Lucen Zhong and Mingdao Liu and Minlie Huang and Peng Zhang and Qinkai Zheng and Rui Lu and Shuaiqi Duan and Shudan Zhang and Shulin Cao and Shuxun Yang and Weng Lam Tam and Wenyi Zhao and Xiao Liu and Xiao Xia and Xiaohan Zhang and Xiaotao Gu and Xin Lv and Xinghan Liu and Xinyi Liu and Xinyue Yang and Xixuan Song and Xunkai Zhang and Yifan An and Yifan Xu and Yilin Niu and Yuantao Yang and Yueyan Li and Yushi Bai and Yuxiao Dong and Zehan Qi and Zhaoyu Wang and Zhen Yang and Zhengxiao Du and Zhenyu Hou and Zihan Wang},\n      year={2024},\n      eprint={2406.12793},\n      archivePrefix={arXiv},\n      primaryClass={id='cs.CL' full_name='Computation and Language' is_active=True alt_name='cmp-lg' in_archive='cs' is_general=False description='Covers natural language processing. Roughly includes material in ACM Subject Class I.2.7. Note that work on artificial languages (programming languages, logics, formal systems) that does not explicitly address natural-language issues broadly construed (natural-language processing, computational linguistics, speech, text retrieval, etc.) is not appropriate for this area.'}\n}\n```\n"
  },
  {
    "path": "README_20240605.md",
    "content": "# GLM-4\n\n<p align=\"center\">\n 📄<a href=\"https://arxiv.org/pdf/2406.12793\" target=\"_blank\"> Report </a> • 🤗 <a href=\"https://huggingface.co/collections/THUDM/glm-4-665fcf188c414b03c2f7e3b7\" target=\"_blank\">HF Repo</a> • 🤖 <a href=\"https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat\" target=\"_blank\">ModelScope</a>  • 🟣 <a href=\"https://wisemodel.cn/models/ZhipuAI/glm-4-9b-chat\" target=\"_blank\">WiseModel</a>  • 🐦 <a href=\"https://twitter.com/thukeg\" target=\"_blank\">Twitter</a> • 👋 Join <a href=\"https://discord.gg/8cnQKdAprg\" target=\"_blank\">Discord</a> and <a href=\"resources/WECHAT.md\" target=\"_blank\">WeChat</a>\n</p>\n<p align=\"center\">\n📍Experience and use a larger-scale GLM business model on the <a href=\"https://open.bigmodel.cn/?utm_campaign=open&_channel_track_key=OWTVNma9\">Zhipu AI Open Platform</a>\n</p>\n\n## Update\n\n- 🔥🔥 **News**: ```2024/11/01```: Dependencies have been updated in this repository. Please update the dependencies in\n  `requirements.txt` to ensure the model runs correctly. The model weights\n  for [glm-4-9b-chat-hf](https://huggingface.co/THUDM/glm-4-9b-chat-hf) are compatible with `transformers>=4.46.2` and can\n  be implemented using the `GlmModel` class in the `transformers` library. Additionally, `tokenizer_chatglm.py`\n  in [glm-4-9b-chat](https://huggingface.co/THUDM/glm-4-9b-chat) and [glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b)\n  has been updated for the latest version of `transformers`. Please update the files on HuggingFace.\n- 🔥 **News**: ```2024/10/27```: We have open-sourced [LongReward](https://github.com/THUDM/LongReward), a model that\n  uses AI feedback to enhance long-context large language models.\n- 🔥 **News**: ```2024/10/25```: We have open-sourced the end-to-end Mandarin-English voice dialogue\n  model [GLM-4-Voice](https://github.com/THUDM/GLM-4-Voice).\n- 🔥 **News**: ```2024/09/05```: We have open-sourced [longcite-glm4-9b](https://huggingface.co/THUDM/LongCite-glm4-9b),\n  a model enabling LLMs to produce fine-grained citations in long-context Q&A, along with the\n  dataset [LongCite-45k](https://huggingface.co/datasets/THUDM/LongCite-45k). Try it out online\n  at [Huggingface Space](https://huggingface.co/spaces/THUDM/LongCite).\n- 🔥 **News**: ```2024/08/15```: We have\n  open-sourced [longwriter-glm4-9b](https://huggingface.co/THUDM/LongWriter-glm4-9b), a model capable of generating over\n  10,000 tokens in single-turn dialogue, along with the\n  dataset [LongWriter-6k](https://huggingface.co/datasets/THUDM/LongWriter-6k). Experience it online\n  at [Huggingface Space](https://huggingface.co/spaces/THUDM/LongWriter) or\n  the [ModelScope Community Space](https://modelscope.cn/studios/ZhipuAI/LongWriter-glm4-9b-demo).\n- 🔥 **News**: ```2024/07/24```: We published the latest technical insights on long-text processing. Check out our\n  technical report on training the open-source GLM-4-9B model for long\n  texts [here](https://medium.com/@ChatGLM/glm-long-scaling-pre-trained-model-contexts-to-millions-caa3c48dea85).\n- 🔥 **News**: ```2024/07/09```: The GLM-4-9B-Chat model is now compatible\n  with [Ollama](https://github.com/ollama/ollama) and [Llama.cpp](https://github.com/ggerganov/llama.cpp). See detailed\n  information in this [PR](https://github.com/ggerganov/llama.cpp/pull/8031).\n- 🔥 **News**: ```2024/06/18```: We have released a [technical report](https://arxiv.org/pdf/2406.12793), available for\n  viewing.\n- 🔥 **News**: ```2024/06/05```: We released the GLM-4-9B series of open-source models.\n\n## Model Introduction\n\nGLM-4-9B is the open-source version of the latest generation of pre-trained models in the GLM-4 series launched by Zhipu\nAI. In the evaluation of data sets in semantics, mathematics, reasoning, code, and knowledge, **GLM-4-9B**\nand its human preference-aligned version **GLM-4-9B-Chat** have shown superior performance beyond Llama-3-8B. In\naddition to multi-round conversations, GLM-4-9B-Chat also has advanced features such as web browsing, code execution,\ncustom tool calls (Function Call), and long text reasoning (supporting up to 128K context).\nThis generation of models has added multi-language support, supporting 26 languages including Japanese, Korean,\nand German. We have also launched the **GLM-4-9B-Chat-1M** model that supports 1M\ncontext length (about 2 million Chinese characters) and the multimodal model GLM-4V-9B based on GLM-4-9B.\n**GLM-4V-9B** possesses dialogue capabilities in both Chinese and English at a high resolution of 1120*1120.\nIn various multimodal evaluations, including comprehensive abilities in Chinese and English, perception & reasoning,\ntext recognition, and chart understanding, GLM-4V-9B demonstrates superior performance compared to\nGPT-4-turbo-2024-04-09, Gemini 1.0 Pro, Qwen-VL-Max, and Claude 3 Opus.\n\n## Model List\n\n|        Model        | Type | Seq Length | Transformers Version |                                                                                                      Download                                                                                                       |                                                                                        Online Demo                                                                                         |\n|:-------------------:|:----:|:----------:|:--------------------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|      GLM-4-9B       | Base |     8K     |  `4.44.0 - 4.45.0`   |             [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/glm-4-9b)             |                                                                                             /                                                                                              |\n|    GLM-4-9B-Chat    | Chat |    128K    |     `>= 4.44.0`      |     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat)      | [🤖 ModelScope CPU](https://modelscope.cn/studios/dash-infer/GLM-4-Chat-DashInfer-Demo/summary)<br> [🤖 ModelScope vLLM](https://modelscope.cn/studios/ZhipuAI/glm-4-9b-chat-vllm/summary) |\n|  GLM-4-9B-Chat-HF   | Chat |    128K    |     `>= 4.46.0`      |                                     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-hf)                                      | [🤖 ModelScope CPU](https://modelscope.cn/studios/dash-infer/GLM-4-Chat-DashInfer-Demo/summary)<br> [🤖 ModelScope vLLM](https://modelscope.cn/studios/ZhipuAI/glm-4-9b-chat-vllm/summary) |\n|  GLM-4-9B-Chat-1M   | Chat |     1M     |     `>= 4.44.0`      | [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat-1M) |                                                                                             /                                                                                              |\n| GLM-4-9B-Chat-1M-HF | Chat |     1M     |     `>= 4.46.0`      |                                  [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m-hf)                                   |                                                                                             /                                                                                              |\n|      GLM-4V-9B      | Chat |     8K     |     `>= 4.46.0`      |           [🤗 Huggingface](https://huggingface.co/THUDM/glm-4v-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4v-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4V-9B)            |                                                       [🤖 ModelScope](https://modelscope.cn/studios/ZhipuAI/glm-4v-9b-Demo/summary)                                                        |\n\n## BenchMarkß\n\n### Typical Tasks\n\n| Model               | AlignBench | MT-Bench | IFEval | MMLU | C-Eval | GSM8K | MATH | HumanEval | NaturalCodeBench |\n|:--------------------|:----------:|:--------:|:------:|:----:|:------:|:-----:|:----:|:---------:|:----------------:|\n| Llama-3-8B-Instruct |    6.40    |   8.00   | 68.58  | 68.4 |  51.3  | 79.6  | 30.0 |   62.2    |       24.7       |\n| ChatGLM3-6B         |    5.18    |   5.50   |  28.1  | 66.4 |  69.0  | 72.3  | 25.7 |   58.5    |       11.3       |\n| GLM-4-9B-Chat       |    7.01    |   8.35   |  69.0  | 72.4 |  75.6  | 79.6  | 50.6 |   71.8    |       32.2       |\n\n### Base Model\n\n| Model               | MMLU | C-Eval | GPQA | GSM8K | MATH | HumanEval |\n|:--------------------|:----:|:------:|:----:|:-----:|:----:|:---------:|\n| Llama-3-8B          | 66.6 |  51.2  |  -   | 45.8  |  -   |   33.5    |\n| Llama-3-8B-Instruct | 68.4 |  51.3  | 34.2 | 79.6  | 30.0 |   62.2    |\n| ChatGLM3-6B-Base    | 61.4 |  69.0  | 26.8 | 72.3  | 25.7 |   58.5    |\n| GLM-4-9B            | 74.7 |  77.1  | 34.3 | 84.0  | 30.4 |   70.1    |\n\n> Since `GLM-4-9B` adds some math, reasoning, and code-related instruction data during pre-training, Llama-3-8B-Instruct\n> is also included in the comparison range.\n\n### Long Context\n\nThe [needle-in-the-haystack experiment](https://github.com/LargeWorldModel/LWM/blob/main/scripts/eval_needle.py) was\nconducted with a context length of 1M, and the results are as follows:\n\n![needle](resources/eval_needle.jpeg)\n\nThe long text capability was further evaluated on LongBench-Chat, and the results are as follows:\n\n<p align=\"center\">\n<img src=\"resources/longbench.png\" alt=\"Description text\" style=\"display: block; margin: auto; width: 65%;\">\n</p>\n\n### Multi Language\n\nThe tests for GLM-4-9B-Chat and Llama-3-8B-Instruct are conducted on six multilingual datasets. The test results and the\ncorresponding languages selected for each dataset are shown in the table below:\n\n| Dataset     | Llama-3-8B-Instruct | GLM-4-9B-Chat |                                           Languages                                            |\n|:------------|:-------------------:|:-------------:|:----------------------------------------------------------------------------------------------:|\n| M-MMLU      |        49.6         |     56.6      |                                              all                                               |\n| FLORES      |        25.0         |     28.8      | ru, es, de, fr, it, pt, pl, ja, nl, ar, tr, cs, vi, fa, hu, el, ro, sv, uk, fi, ko, da, bg, no |\n| MGSM        |        54.0         |     65.3      |                           zh, en, bn, de, es, fr, ja, ru, sw, te, th                           |\n| XWinograd   |        61.7         |     73.1      |                                     zh, en, fr, jp, ru, pt                                     |\n| XStoryCloze |        84.7         |     90.7      |                           zh, en, ar, es, eu, hi, id, my, ru, sw, te                           |\n| XCOPA       |        73.3         |     80.1      |                           zh, et, ht, id, it, qu, sw, ta, th, tr, vi                           |\n\n### Function Call\n\nTested\non [Berkeley Function Calling Leaderboard](https://github.com/ShishirPatil/gorilla/tree/main/berkeley-function-call-leaderboard).\n\n| Model                  | Overall Acc. | AST Summary | Exec Summary | Relevance |\n|:-----------------------|:------------:|:-----------:|:------------:|:---------:|\n| Llama-3-8B-Instruct    |    58.88     |    59.25    |    70.01     |   45.83   |\n| gpt-4-turbo-2024-04-09 |    81.24     |    82.14    |    78.61     |   88.75   |\n| ChatGLM3-6B            |    57.88     |    62.18    |    69.78     |   5.42    |\n| GLM-4-9B-Chat          |    81.00     |    80.26    |    84.40     |   87.92   |\n\n### Multi-Modal\n\nGLM-4V-9B is a multimodal language model with visual understanding capabilities. The evaluation results of its related\nclassic tasks are as follows:\n\n|                            | **MMBench-EN-Test** | **MMBench-CN-Test** | **SEEDBench_IMG** | **MMStar** | **MMMU** | **MME** | **HallusionBench** | **AI2D** | **OCRBench** |\n|----------------------------|---------------------|---------------------|-------------------|------------|----------|---------|--------------------|----------|--------------|\n| **gpt-4o-2024-05-13**      | 83.4                | 82.1                | 77.1              | 63.9       | 69.2     | 2310.3  | 55                 | 84.6     | 736          |\n| **gpt-4-turbo-2024-04-09** | 81.0                | 80.2                | 73.0              | 56.0       | 61.7     | 2070.2  | 43.9               | 78.6     | 656          |\n| **gpt-4-1106-preview**     | 77.0                | 74.4                | 72.3              | 49.7       | 53.8     | 1771.5  | 46.5               | 75.9     | 516          |\n| **InternVL-Chat-V1.5**     | 82.3                | 80.7                | 75.2              | 57.1       | 46.8     | 2189.6  | 47.4               | 80.6     | 720          |\n| **LLaVA-Next-Yi-34B**      | 81.1                | 79                  | 75.7              | 51.6       | 48.8     | 2050.2  | 34.8               | 78.9     | 574          |\n| **Step-1V**                | 80.7                | 79.9                | 70.3              | 50.0       | 49.9     | 2206.4  | 48.4               | 79.2     | 625          |\n| **MiniCPM-Llama3-V2.5**    | 77.6                | 73.8                | 72.3              | 51.8       | 45.8     | 2024.6  | 42.4               | 78.4     | 725          |\n| **Qwen-VL-Max**            | 77.6                | 75.7                | 72.7              | 49.5       | 52       | 2281.7  | 41.2               | 75.7     | 684          |\n| **Gemini 1.0 Pro**         | 73.6                | 74.3                | 70.7              | 38.6       | 49       | 2148.9  | 45.7               | 72.9     | 680          |\n| **Claude 3 Opus**          | 63.3                | 59.2                | 64                | 45.7       | 54.9     | 1586.8  | 37.8               | 70.6     | 694          |\n| **GLM-4V-9B**              | 81.1                | 79.4                | 76.8              | 58.7       | 47.2     | 2163.8  | 46.6               | 81.1     | 786          |\n\n## Quick call\n\n**For hardware configuration and system requirements, please check [here](basic_demo/README_en.md).**\n\n### Use the following method to quickly call the GLM-4-9B-Chat language model\n\nUse the transformers backend for inference:\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport os\n\nos.environ[\n    'CUDA_VISIBLE_DEVICES'] = '0'  # Set the GPU number. If inference with multiple GPUs, set multiple GPU numbers\nMODEL_PATH = \"THUDM/glm-4-9b-chat-hf\"\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n\nquery = \"你好\"\n\ninputs = tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": query}],\n                                       add_generation_prompt=True,\n                                       tokenize=True,\n                                       return_tensors=\"pt\",\n                                       return_dict=True\n                                       )\n\ninputs = inputs.to(device)\nmodel = AutoModelForCausalLM.from_pretrained(\n    MODEL_PATH,\n    torch_dtype=torch.bfloat16,\n    low_cpu_mem_usage=True,\n    trust_remote_code=True,\n    device_map=\"auto\"\n).eval()\n\ngen_kwargs = {\"max_length\": 2500, \"do_sample\": True, \"top_k\": 1}\nwith torch.no_grad():\n    outputs = model.generate(**inputs, **gen_kwargs)\n    outputs = outputs[:, inputs['input_ids'].shape[1]:]\n    print(tokenizer.decode(outputs[0], skip_special_tokens=True))\n```\n\nUse the vLLM backend for inference:\n\n```python\nfrom transformers import AutoTokenizer\nfrom vllm import LLM, SamplingParams\n\n# GLM-4-9B-Chat\n# If you encounter OOM, you can try to reduce max_model_len or increase tp_size\nmax_model_len, tp_size = 131072, 1\nmodel_name = \"THUDM/glm-4-9b-chat-hf\"\nprompt = [{\"role\": \"user\", \"content\": \"你好\"}]\n\ntokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)\nllm = LLM(\n    model=model_name,\n    tensor_parallel_size=tp_size,\n    max_model_len=max_model_len,\n    trust_remote_code=True,\n    enforce_eager=True,\n    # if you encounter OOM in GLM-4-9B-Chat-1M, you can try to enable the following parameters\n    # enable_chunked_prefill=True,\n    # max_num_batched_tokens=8192\n)\nstop_token_ids = [151329, 151336, 151338]\nsampling_params = SamplingParams(temperature=0.95, max_tokens=1024, stop_token_ids=stop_token_ids)\n\ninputs = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)\noutputs = llm.generate(prompts=inputs, sampling_params=sampling_params)\n\nprint(outputs[0].outputs[0].text)\n\n```\n\n### Use the following method to quickly call the GLM-4V-9B multimodal model\n\nUse the transformers backend for inference:\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport os\n\nos.environ[\n    'CUDA_VISIBLE_DEVICES'] = '0'  # Set the GPU number. If inference with multiple GPUs, set multiple GPU numbers\nMODEL_PATH = \"THUDM/glm-4v-9b\"\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n\nquery = '描述这张图片'\nimage = Image.open(\"your image\").convert('RGB')\ninputs = tokenizer.apply_chat_template([{\"role\": \"user\", \"image\": image, \"content\": query}],\n                                       add_generation_prompt=True, tokenize=True, return_tensors=\"pt\",\n                                       return_dict=True)  # chat mode\n\ninputs = inputs.to(device)\nmodel = AutoModelForCausalLM.from_pretrained(\n    MODEL_PATH,\n    torch_dtype=torch.bfloat16,\n    low_cpu_mem_usage=True,\n    trust_remote_code=True,\n    device_map=\"auto\"\n).eval()\n\ngen_kwargs = {\"max_length\": 2500, \"do_sample\": True, \"top_k\": 1}\nwith torch.no_grad():\n    outputs = model.generate(**inputs, **gen_kwargs)\n    outputs = outputs[:, inputs['input_ids'].shape[1]:]\n    print(tokenizer.decode(outputs[0]))\n```\n\nUse the vLLM backend for inference:\n\n```python\nfrom PIL import Image\nfrom vllm import LLM, SamplingParams\n\nmodel_name = \"THUDM/glm-4v-9b\"\n\nllm = LLM(model=model_name,\n          tensor_parallel_size=1,\n          max_model_len=8192,\n          trust_remote_code=True,\n          enforce_eager=True)\nstop_token_ids = [151329, 151336, 151338]\nsampling_params = SamplingParams(temperature=0.2,\n                                 max_tokens=1024,\n                                 stop_token_ids=stop_token_ids)\n\nprompt = \"What's the content of the image?\"\nimage = Image.open(\"your image\").convert('RGB')\ninputs = {\n    \"prompt\": prompt,\n    \"multi_modal_data\": {\n        \"image\": image\n    },\n}\noutputs = llm.generate(inputs, sampling_params=sampling_params)\n\nfor o in outputs:\n    generated_text = o.outputs[0].text\n    print(generated_text)\n\n```\n\n## Complete project list\n\nIf you want to learn more about the GLM-4-9B series open source models, this open source repository provides developers\nwith basic GLM-4-9B usage and development code through the following content\n\n+ [basic_demo](basic_demo/README.md): Contains\n  + Interaction code using transformers and vLLM backend\n  + OpenAI API backend interaction code\n  + Batch reasoning code\n\n+ [composite_demo](composite_demo/README.md): Contains\n  + Fully functional demonstration code for GLM-4-9B and GLM-4V-9B open source models, including All Tools capabilities,\n    long document interpretation, and multimodal capabilities.\n\n+ [fintune_demo](finetune_demo/README.md): Contains\n  + PEFT (LORA, P-Tuning) fine-tuning code\n  + SFT fine-tuning code\n\n+ [intel_device_demo](intel_device_demo/): Contains\n  + OpenVINO deployment code\n  + Intel® Extension for Transformers deployment code\n\n## Friendly Links\n\n+ [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory): Efficient open-source fine-tuning framework,\n  already supports GLM-4-9B-Chat language model fine-tuning.\n+ [SWIFT](https://github.com/modelscope/swift): LLM/VLM training framework from ModelScope, supports\n  GLM-4-9B-Chat / GLM-4V-9b fine-tuning.\n+ [Xorbits Inference](https://github.com/xorbitsai/inference): Performance-enhanced and comprehensive global inference\n  framework, easily deploy your own models or import cutting-edge open source models with one click.\n+ [LangChain-ChatChat](https://github.com/chatchat-space/Langchain-Chatchat): RAG and Agent applications based on\n  language models such as Langchain and ChatGLM\n+ [self-llm](https://github.com/datawhalechina/self-llm/tree/master/models/GLM-4): Datawhale's self-llm project, which\n  includes\n  the GLM-4-9B open source model cookbook.\n+ [chatglm.cpp](https://github.com/li-plus/chatglm.cpp): Real-time inference on your laptop accelerated by quantization,\n  similar to llama.cpp.\n+ [OpenVINO](https://github.com/openvinotoolkit): glm-4-9b-chat already supports the use of OpenVINO. The toolkit accelerates inference and has a greater inference speed improvement on Intel's GPU, GPU and NPU devices. For\nspecific usage, please refer to  [OpenVINO notebooks](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/llm-chatbot/llm-chatbot-generate-api.ipynb)\n\n\n## License\n\n+ The use of GLM-4 model weights must follow\n  the [Model License](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE).\n\n+ The code in this open source repository follows the [Apache 2.0](LICENSE) license.\n\nPlease strictly follow the open source license.\n\n## Reference\n\nIf you find our work helpful, please consider citing the following paper.\n\n```\n@misc{glm2024chatglm,\n      title={ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools},\n      author={Team GLM  and Aohan Zeng and Bin Xu and Bowen Wang and Chenhui Zhang and Da Yin and Diego Rojas and Guanyu Feng and Hanlin Zhao and Hanyu Lai and Hao Yu and Hongning Wang and Jiadai Sun and Jiajie Zhang and Jiale Cheng and Jiayi Gui and Jie Tang and Jing Zhang and Juanzi Li and Lei Zhao and Lindong Wu and Lucen Zhong and Mingdao Liu and Minlie Huang and Peng Zhang and Qinkai Zheng and Rui Lu and Shuaiqi Duan and Shudan Zhang and Shulin Cao and Shuxun Yang and Weng Lam Tam and Wenyi Zhao and Xiao Liu and Xiao Xia and Xiaohan Zhang and Xiaotao Gu and Xin Lv and Xinghan Liu and Xinyi Liu and Xinyue Yang and Xixuan Song and Xunkai Zhang and Yifan An and Yifan Xu and Yilin Niu and Yuantao Yang and Yueyan Li and Yushi Bai and Yuxiao Dong and Zehan Qi and Zhaoyu Wang and Zhen Yang and Zhengxiao Du and Zhenyu Hou and Zihan Wang},\n      year={2024},\n      eprint={2406.12793},\n      archivePrefix={arXiv},\n      primaryClass={id='cs.CL' full_name='Computation and Language' is_active=True alt_name='cmp-lg' in_archive='cs' is_general=False description='Covers natural language processing. Roughly includes material in ACM Subject Class I.2.7. Note that work on artificial languages (programming languages, logics, formal systems) that does not explicitly address natural-language issues broadly construed (natural-language processing, computational linguistics, speech, text retrieval, etc.) is not appropriate for this area.'}\n}\n```\n\n```\n@misc{wang2023cogvlm,\n      title={CogVLM: Visual Expert for Pretrained Language Models},\n      author={Weihan Wang and Qingsong Lv and Wenmeng Yu and Wenyi Hong and Ji Qi and Yan Wang and Junhui Ji and Zhuoyi Yang and Lei Zhao and Xixuan Song and Jiazheng Xu and Bin Xu and Juanzi Li and Yuxiao Dong and Ming Ding and Jie Tang},\n      year={2023},\n      eprint={2311.03079},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n"
  },
  {
    "path": "README_zh.md",
    "content": "# GLM-4-0414 系列模型\n\n<p align=\"center\">\n👋 加入我们的 <a href=\"https://discord.gg/8cnQKdAprg\" target=\"_blank\">Discord</a>, <a href=\"https://x.com/Zai_org\" target=\"_blank\">X</a> 和 <a href=\"resources/WECHAT.md\" target=\"_blank\"> 微信 </a>\n</p>\n<p align=\"center\">\n📍本次开源模型可以在 <a href=\"https://chat.z.ai\">Z.ai</a> 免费体验；使用 GLM 商业模型服务请到 <a href=\"https://bigmodel.cn\">bigmodel.cn</a>。\n</p>\n\nRead this in [English](README)\n\n## 项目更新\n\n- 🔥 **News**：`2025/07/02`：我们正式发布 [GLM-4.1V-9B-Thinking](https://huggingface.co/collections/THUDM/glm-41v-thinking-6862bbfc44593a8601c2578d) 系列视觉理解模型，更多信息请查看 [GitHub 仓库](https://github.com/THUDM/GLM-4.1V-Thinking)。\n- **News**: ```2025/04/14```: 我们发布 [GLM-4-32B-0414](https://huggingface.co/collections/THUDM/glm-4-0414-67f3cbcb34dd9d252707cb2e) 系列模型，规模提升至 32B，包含对话、推理、沉思多种能力的模型。\n- **News**: ``2024/06/18``: 我们发布 [技术报告](https://arxiv.org/pdf/2406.12793), 欢迎查看。\n- **News**: ``2024/06/05``: 我们发布 `GLM-4-9B` 系列开源模型，其内容可以在[这里](README_240605.md)查看。\n\n## 模型介绍\n\nGLM 家族迎来新一代开源模型 **GLM-4-32B-0414** 系列，320 亿参数，效果比肩 OpenAI 的 GPT 系列和 DeepSeek 的 V3/R1 系列，且支持非常友好的本地部署特性。GLM-4-32B-Base-0414 经过 15T 高质量数据的预训练，其中包含大量推理类的合成数据，这为后续的强化学习扩展打下了基础。在后训练阶段，除了针对对话场景进行了人类偏好对齐外，我们还通过拒绝采样和强化学习等技术强化了模型在指令遵循、工程代码、函数调用方面的效果，加强了智能体任务所需的原子能力。GLM-4-32B-0414 在工程代码、Artifacts 生成、函数调用、搜索问答及报告等方面都取得了不错的效果，部分 Benchmark 甚至可以媲美更大规模的 GPT-4o、DeepSeek-V3-0324（671B）等模型。\n\n**GLM-Z1-32B-0414** 是具有**深度思考能力**的推理模型，这是在 GLM-4-32B-0414 的基础上，通过冷启动和扩展强化学习，以及在数学、代码和逻辑等任务上对模型的进一步训练得到的。相对于基础模型，GLM-Z1-32B-0414 显著提升了数理能力和解决复杂任务的能力。在训练的过程中，我们还引入了基于对战排序反馈的通用强化学习，进一步增强了模型的通用能力。\n\n**GLM-Z1-Rumination-32B-0414** 是具有**沉思能力**的深度推理模型（对标 Open AI 的 Deep Research）。不同于一般的深度思考模型，沉思模型通过更长时间的深度思考来解决更开放和复杂的问题（例如：撰写两个城市AI发展对比情况，以及未来的发展规划），沉思模型在深度思考过程中结合搜索工具处理复杂任务，并经过利用多种规则型奖励来指导和扩展端到端强化学习训练得到。Z1-Rumination 在研究型写作和复杂检索任务上的能力得到了显著提升。\n\n最后，**GLM-Z1-9B-0414** 是一个惊喜。我们沿用上述一系列技术，训练了一个保持开源传统的 9B 小尺寸模型。尽管规模更小，GLM-Z1-9B-0414 在数学推理和通用任务中依然展现出极为优秀的能力，其整体表现已处于同尺寸开源模型中的领先水平。特别是在资源受限的场景下，该模型在效率与效果之间实现了出色的平衡，为追求轻量化部署的用户提供了强有力的选择。\n\n## 效果展示\n\n### 动画绘制\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-Z1-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <video src=\"https://github.com/user-attachments/assets/849ff9fd-b54d-4c74-9ee5-3412e1a09e32\"\n             style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n        write a Python program that shows a ball bouncing inside a spinning hexagon. The ball should be affected by gravity and friction, and it must bounce off the rotating walls realistically\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <video src=\"https://github.com/user-attachments/assets/8dccdb9d-cc44-4732-b438-74a4e3cb9dfb\"\n             style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n         用 HTML 模拟一个小球在从一个旋转中的六边形中心释放后的场景。考虑小球和六边形边框的碰撞和小球受到的重力，并假设碰撞都是完全弹性碰撞\n      </div>\n    </td>\n  </tr>\n</table>\n\n### 网页设计\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/bd9c1fc1-c784-4e8f-9c76-5f7389a715f1\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n          设计一个支持自定义函数绘制的绘图板，可以添加和删除自定义函数，并为函数指定颜色\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/7ad12d52-9229-4278-8d1b-ffbf43e99070\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\"> 给我设计一个移动端机器学习平台的 UI，其中要包括训练任务，存储管理，和个人统计信息界面。个人信息统计界面要用图表展示用户过去一段时间的各类资源使用情况。使用 Tailwind CSS 来美化页面，把这 3 个手机界面平铺展示到一个 HTML 页面中 </div>\n    </td>\n  </tr>\n</table>\n\n### SVG 生成\n\n<table>\n  <tr>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n    <td style=\"text-align: center; font-size: 16px; font-weight: bold; padding: 10px; width: 420px;\">\n      GLM-4-32B-0414\n    </td>\n  </tr>\n  <tr>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/9407e4c1-1876-4ab5-838c-839836fb418a\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n          用SVG创作一幅烟雨江南\n      </div>\n    </td>\n    <td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n      <img src=\"https://github.com/user-attachments/assets/bcce8c5a-cedf-45c8-b666-ddb023d5b49c\"/>\n      <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\"> 用 SVG 展示一个 LLM 的训练流程 </div>\n    </td>\n  </tr>\n</table>\n\n### 分析调研撰写\n\n<td style=\"vertical-align: top; padding: 10px; width: 420px;\">\n  <video src=\"https://github.com/user-attachments/assets/7939c8c5-0fcf-4bc4-be45-3964aad0e61c\" style=\"width: 400px; height: 300px; object-fit: contain;\" autoplay loop muted playsinline></video>\n  <div style=\"margin-top: 10px; font-size: 14px; color: #333; width: 400px;\">\n    中国城市 AI 发展分析：北京与杭州的对比研究。同时调研国外城市用 AI 进行城市治理的案例。\n  </div>\n</td>\n\n\n## 模型列表\n\n### GLM-4-0414 系列模型\n\nGLM-Z1-9B-0414 开源模型 [在线体验](https://modelscope.cn/studios/ZhipuAI/GLM-Z1-9B-0414/summary)\n\n|           Model            |   Type    | Seq Length* |                                                                                                                                                              Download                                                                                                                                                              |\n|:--------------------------:|:---------:|:-----------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|       GLM-4-9B-0414        |   Chat    | 32K -> 128K |                           [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-9B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-9B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-9B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-0414)                           |\n|       GLM-Z1-9B-0414       | Reasoning | 32K -> 128K |                        [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-Z1-9B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-9B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-9B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-9B-0414)                        |\n|    GLM-4-32B-Base-0414     |   Base    | 32K -> 128K |               [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-32B-Base-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-32B-Base-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-32B-Base-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-32B-Base-0414)               |\n|       GLM-4-32B-0414       |   Chat    | 32K -> 128K |                      [🤗 Huggingface](https://huggingface.co/THUDM/GLM-4-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-4-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-4-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-32B-Base-0414)                       |\n|      GLM-Z1-32B-0414       | Reasoning | 32K -> 128K |                       [🤗 Huggingface](https://huggingface.co/THUDM/GLM-Z1-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-32B-0414)                       |\n| GLM-Z1-Rumination-32B-0414 | Reasoning |    128K     | [🤗 Huggingface](https://huggingface.co/THUDM/GLM-Z1-Rumination-32B-0414)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/GLM-Z1-Rumination-32B-0414)<br> [🧩 Modelers](https://modelers.cn/models/zhipuai/GLM-Z1-Rumination-32B-0414)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-Z1-Rumination-32B-0414) |\n\nGLM-4-9B-0414 由于其较小的模型容量，我们未对其智能体能力进行类似 GLM-4-32B-0414 的强化，主要针对翻译等需要大批量调用的场景进行优化。\n\n\\* 模型原生采用 32K 上下文进行训练，对于输入 + 输出长度可能超过 32K 的请求，我们建议激活 YaRN 来获得较好的外推性能，详情见[部署章节](#%E6%A8%A1%E5%9E%8B%E5%92%8C%E6%8F%90%E7%A4%BA%E8%AF%8D%E5%AE%9E%E7%8E%B0)。\n\n以下为 2024 年 6 月 5 日发布的 GLM-4 系列模型，其详细内容可以在[这里](README_zh_240605.md)查看。\n\n|             Model             |   Type    | Seq Length* |                                                                                                      Download                                                                                                       |\n|:-----------------------------:|:---------:|:----------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|      GLM-4-9B       | Base |     8K     |                                           [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b)<br>                                            |\n|    GLM-4-9B-Chat    | Chat |    128K    |     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat)      |\n|  GLM-4-9B-Chat-HF   | Chat |    128K    |                                     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-hf)                                      |\n|  GLM-4-9B-Chat-1M   | Chat |     1M     | [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat-1M) |\n| GLM-4-9B-Chat-1M-HF | Chat |     1M     |                                  [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m-hf)                                   |\n|      GLM-4V-9B      | Chat |     8K     |        [🤗 Huggingface](https://huggingface.co/THUDM/glm-4v-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4v-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4V-9B)               |\n\n## 评测结果\n\n### GLM-4-0414 系列\n\n<div style=\"text-align: center;\">\n  <img src=\"resources/Bench-32B.png\" style=\"width: 80%;\" />\n</div>\n\n| 模型             | IFEval | BFCL-v3 (Overall) | BFCL-v3 (MultiTurn) | TAU-Bench (Retail) | TAU-Bench (Airline) | SimpleQA | HotpotQA |\n| ---------------- | ------ | ----------------- | ------------------- | ------------------ | ------------------- | -------- | -------- |\n| Qwen2.5-Max      | 85.6   | 50.9              | 30.5                | 58.3               | 22.0                | 79.0     | 52.8     |\n| GPT-4o-1120      | 81.9   | 69.6              | 41.0                | 62.8               | 46.0                | 82.8     | 63.9     |\n| DeepSeek-V3-0324 | 83.4   | 66.2              | 35.8                | 60.7               | 32.4                | 82.6     | 54.6     |\n| DeepSeek-R1      | 84.3   | 57.5              | 12.4                | 33.0               | 37.3                | 83.9     | 63.1     |\n| GLM-4-32B-0414   | 87.6   | 69.6              | 41.5                | 68.7               | 51.2                | 88.1     | 63.8     |\n\n> 对于 `SimpleQA` 和 `HotpotQA`，我们分别从测试集中采样了近500条测试样例，提供所有模型最基础的 `search` 和 `click` 工具，另外确保其余 Setting 保持一致后，3次评测取平均值\n\n| 模型  | 框架                       | [SWE-bench Verified](https://openai.com/index/introducing-swe-bench-verified/)  | [SWE-bench Verified mini](https://github.com/mariushobbhahn/SWEBench-verified-mini) |\n|---|--------------------------|---|-------------------------------------------------------------------------------------|\n| GLM-4-32B-0414  | Moatless<sup>[1]</sup>   | 33.8 | 38.0                                                                                |\n| GLM-4-32B-0414  | Agentless<sup>[2]</sup>  | 30.7 | 34.0                                                                                |\n| GLM-4-32B-0414  | OpenHands<sup>[3]</sup>  | 27.2  | 28.0                                                                                |\n\n\n[1] [Moatless v0.0.3](https://github.com/aorwall/moatless-tools) 使用如下参数 `response_format=\"react\", thoughts_in_action=False, max_interations=30`，未对失败轨迹进行重试，其余为默认配置\n\n[2] [Agentless v1.5.0](https://github.com/OpenAutoCoder/Agentless) 其中的 Embedding 模型使用了 [BGE](https://github.com/FlagOpen/FlagEmbedding/blob/master/README_zh.md)，基于[FAISS](https://github.com/facebookresearch/faiss)进行相似性检索，为加快patch验证的速度同时尽可能保证效果，将运行单个实例的超时时间从默认的300s修改为180s\n\n[3] [OpenHands v0.29.1](https://github.com/All-Hands-AI/OpenHands/tree/main) 未采用 YaRN 上下文扩展，而是限制了最大 60 个 iterations，并对 history 进行 summarization 以防止超出 32K 上下文限制，summarization 配置为 `llm_config=\"condenser\", keep_first=1, max_size=32`，同样未对失败轨迹进行重试\n\n\n### GLM-Z1-0414 系列\n\n<div style=\"text-align: center;\">\n  <img src=\"resources/Bench-Z1-9B.png\" style=\"width: 80%;\" />\n  <img src=\"resources/Bench-Z1-32B.png\" style=\"width: 80%;\" />\n</div>\n\n## 模型和提示词实现\n\n### 模型实现\n\n如果你想查看我们的模型实现，欢迎查看在相关仓库的模型实现 Pull Request，他们已经被合并。\n\n+ [vLLM 模型实现](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/models/glm4.py)\n+ [transformers 模型实现](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm4/modeling_glm4.py)\n+ [llama.cpp 模型实现](https://github.com/ggml-org/llama.cpp/pull/12867)\n\n### 处理长上下文（YaRN）\n\n如果模型的输出 + 输出 token 数可能超过模型的原生上下文长度（GLM-4-0414系列多数为32k），建议开启 YaRN 来获得更好的长上下文建模能力。对于支持的框架，你可以在对应的`config.json`中修改。具体地，对于 GLM-Z1 系列模型，当输入长度超过 **8,192 tokens** 时，考虑启用 YaRN（Rope Scaling）。\n\n```json\n\"rope_scaling\": {\n    \"factor\": 4.0,\n    \"original_max_position_embeddings\": 32768,\n    \"type\": \"yarn\"\n}\n```\n对于多数用户请求，如果输出 + 输出 token 数不会超过原生上下文长度，则无需任何修改。\n\n### 模型微调\n\n可以在`finetune/README.md`下找到模型的微调所需算力信息和案例的微调脚本。\n\n可以通过以下命令开启一个简单的模型微调案例\n\n```shell\ncd finetune\npip install -r ../inference/requirements.txt\npip install -r requirements.txt\n# Use single GPU for Chat Fine-tune\npython finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml\n```\n🎉 脚本也支持使用**SwanLab**进行微调可视化跟踪，可以访问[SwanLab可视化看板](https://swanlab.cn/@ShaohonChen/GLM4-Finetune/overview)获得案例微调脚本的训练日志。\n\n### 提示词实现\n\n如果你使用`transformers`库提供的`apply_chat_template`方法构建提示词。以下是对不同 GLM-4-0414 模型中 `系统提示词`的限制。\n\n+ `GLM-4-32B-Base-0414`: 基座模型，无对话模板。\n+ `GLM-4-*-0414` / `GLM-Z1-*-0414`: 如果传入`tools`，则由 `apply_chat_template` 填充工具到`chat_template`中的固定模板，单独作为一条带有`tools`绑定的 `system`字段信息并拼接于`messages[0]`。原本传入的所有 `messages` 自动往后移动一个位置。\n+ `GLM-Z1-Rumination-32B-0414`:\n    + 不支持自定义系统提示词，不支持自定义工具，你的所有 `tools` 和 `system` 字段会被 `apply_chat_template` 忽略。使用该模型需要外接搜索引擎或者自定义retrieval API。\n    + 一共支持四个工具，分别是\n        ```\n        1. search\n           描述: 执行搜索查询并返回搜索结果。当您需要查找有关特定主题的信息时使用此功能。\n           参数: query (字符串) - 搜索查询字符串，除非是中文专有名词，否则使用英文单词\n\n        2. click\n           描述: 点击搜索结果中的链接并导航到相应页面。当您需要查看特定搜索结果的详细内容时使用此功能。\n           参数: link_id (整数) - 要点击的链接ID（来自搜索结果中的序号）\n\n        3. open\n           描述: 打开特定网站。通过URL获取任何网站的内容。\n           参数: url (字符串) - 目标网站URL或域名\n\n        4. finish\n           描述: 完成任务。当您已找到所需信息时使用此功能。\n           参数: 无\n        ```\n    + `chat_template`中的固定模板使用英文思过程，如果要更换其他语言，需要修改以下部分（暂时支持中文和英文）\n        ```\n        <重要配置>\n        - 采用语言\n            * 搜索关键词：英文 -> 在这里换成“中文”或者其他语言\n            * 思考：英文 -> 在这里换成“中文”或者其他语言\n        ```\n\nGLM-4-0414 系列模型的提示词构造可以前往对应的模型仓库中的 `chat_template.jinja` 查看具体的模型对话模板。\n\n\n## 引用\n\n如果你觉得我们的工作有帮助的话，请考虑引用下列论文。\n\n```\n@misc{glm2024chatglm,\n      title={ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools},\n      author={Team GLM and Aohan Zeng and Bin Xu and Bowen Wang and Chenhui Zhang and Da Yin and Diego Rojas and Guanyu Feng and Hanlin Zhao and Hanyu Lai and Hao Yu and Hongning Wang and Jiadai Sun and Jiajie Zhang and Jiale Cheng and Jiayi Gui and Jie Tang and Jing Zhang and Juanzi Li and Lei Zhao and Lindong Wu and Lucen Zhong and Mingdao Liu and Minlie Huang and Peng Zhang and Qinkai Zheng and Rui Lu and Shuaiqi Duan and Shudan Zhang and Shulin Cao and Shuxun Yang and Weng Lam Tam and Wenyi Zhao and Xiao Liu and Xiao Xia and Xiaohan Zhang and Xiaotao Gu and Xin Lv and Xinghan Liu and Xinyi Liu and Xinyue Yang and Xixuan Song and Xunkai Zhang and Yifan An and Yifan Xu and Yilin Niu and Yuantao Yang and Yueyan Li and Yushi Bai and Yuxiao Dong and Zehan Qi and Zhaoyu Wang and Zhen Yang and Zhengxiao Du and Zhenyu Hou and Zihan Wang},\n      year={2024},\n      eprint={2406.12793},\n      archivePrefix={arXiv},\n      primaryClass={id='cs.CL' full_name='Computation and Language' is_active=True alt_name='cmp-lg' in_archive='cs' is_general=False description='Covers natural language processing. Roughly includes material in ACM Subject Class I.2.7. Note that work on artificial languages (programming languages, logics, formal systems) that does not explicitly address natural-language issues broadly construed (natural-language processing, computational linguistics, speech, text retrieval, etc.) is not appropriate for this area.'}\n}\n```\n"
  },
  {
    "path": "README_zh_240605.md",
    "content": "# GLM-4\n\n<p align=\"center\">\n 📄<a href=\"https://arxiv.org/pdf/2406.12793\" target=\"_blank\"> Report </a> • 🤗 <a href=\"https://huggingface.co/collections/THUDM/glm-4-665fcf188c414b03c2f7e3b7\" target=\"_blank\">HF Repo</a> • 🤖 <a href=\"https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat\" target=\"_blank\">ModelScope</a> • 🟣 <a href=\"https://wisemodel.cn/models/ZhipuAI/glm-4-9b-chat\" target=\"_blank\">WiseModel</a> • 🐦 <a href=\"https://twitter.com/thukeg\" target=\"_blank\">Twitter</a> • 👋 加入我们的 <a href=\"https://discord.gg/8cnQKdAprg\" target=\"_blank\">Discord</a> 和 <a href=\"resources/WECHAT.md\" target=\"_blank\">微信</a>\n</p>\n<p align=\"center\">\n📍在 <a href=\"https://open.bigmodel.cn/?utm_campaign=open&_channel_track_key=OWTVNma9\">智谱AI开放平台</a> 体验和使用更大规模的 GLM 商业模型。\n</p>\n\nRead this in [English](README_en.md)\n\n## 项目更新\n\n- 🔥🔥 **News**: ```2024/12/10```: 本仓库微调代码支持使用`Ascend NPU`进行微调。请更新微调代码并查看代码内注释。\n- 🔥 **News**: ```2024/11/01```: 本仓库依赖进行升级，请更新`requirements.txt`中的依赖以保证正常运行模型。[glm-4-9b-chat-hf](https://huggingface.co/THUDM/glm-4-9b-chat-hf) 是适配 `transformers>=4.46.2` 的模型权重，使用 `transformers` 库中的 `GlmModel` 类实现。\n同时，[glm-4-9b-chat](https://huggingface.co/THUDM/glm-4-9b-chat), [glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b) 中的 `tokenzier_chatglm.py` 已经更新以适配最新版本的 `transformers`库。请前往 HuggingFace 更新文件。\n- 🔥 **News**: ```2024/10/27```: 我们开源了 [LongReward](https://github.com/THUDM/LongReward)，这是一个使用 AI 反馈改进长上下文大型语言模型。\n- 🔥 **News**: ```2024/10/25```: 我们开源了端到端中英语音对话模型 [GLM-4-Voice](https://github.com/THUDM/GLM-4-Voice)。\n- 🔥 **News**: ```2024/09/05``` 我们开源了使LLMs能够在长上下文问答中生成细粒度引用的模型 [longcite-glm4-9b](https://huggingface.co/THUDM/LongCite-glm4-9b) 以及数据集 [LongCite-45k](https://huggingface.co/datasets/THUDM/LongCite-45k), 欢迎在 [Huggingface Space](https://huggingface.co/spaces/THUDM/LongCite) 在线体验。\n- 🔥**News**: ```2024/08/15```: 我们开源具备长文本输出能力(单轮对话大模型输出可超过1万token) 的模型 [longwriter-glm4-9b](https://huggingface.co/THUDM/LongWriter-glm4-9b) 以及数据集 [LongWriter-6k](https://huggingface.co/datasets/THUDM/LongWriter-6k),  欢迎在 [Huggingface Space](https://huggingface.co/spaces/THUDM/LongWriter) 或 [魔搭社区空间](https://modelscope.cn/studios/ZhipuAI/LongWriter-glm4-9b-demo) 在线体验。\n- 🔥 **News**: ```2024/07/24```: 我们发布了与长文本相关的最新技术解读，关注 [这里](https://medium.com/@ChatGLM/glm-long-scaling-pre-trained-model-contexts-to-millions-caa3c48dea85) 查看我们在训练 GLM-4-9B 开源模型中关于长文本技术的技术报告。\n- 🔥 **News**: ``2024/07/09``: GLM-4-9B-Chat 模型已适配 [Ollama](https://github.com/ollama/ollama), [Llama.cpp](https://github.com/ggerganov/llama.cpp)，您可以在 [PR](https://github.com/ggerganov/llama.cpp/pull/8031) 查看具体的细节。\n- 🔥 **News**: ``2024/06/18``: 我们发布 [技术报告](https://arxiv.org/pdf/2406.12793), 欢迎查看。\n- 🔥 **News**: ``2024/06/05``: 我们发布 GLM-4-9B 系列开源模型。\n\n## 模型介绍\n\nGLM-4-9B 是智谱 AI 推出的最新一代预训练模型 GLM-4 系列中的开源版本。 在语义、数学、推理、代码和知识等多方面的数据集测评中，\n**GLM-4-9B** 及其人类偏好对齐的版本 **GLM-4-9B-Chat** 均表现出超越 Llama-3-8B 的卓越性能。除了能进行多轮对话，GLM-4-9B-Chat\n还具备网页浏览、代码执行、自定义工具调用（Function Call）和长文本推理（支持最大 128K 上下文）等高级功能。本代模型增加了多语言支持，支持包括日语，韩语，德语在内的\n26 种语言。我们还推出了支持 1M 上下文长度（约 200 万中文字符）的 **GLM-4-9B-Chat-1M** 模型和基于 GLM-4-9B 的多模态模型\nGLM-4V-9B。**GLM-4V-9B** 具备 1120 * 1120 高分辨率下的中英双语多轮对话能力，在中英文综合能力、感知推理、文字识别、图表理解等多方面多模态评测中，GLM-4V-9B\n表现出超越 GPT-4-turbo-2024-04-09、Gemini 1.0 Pro、Qwen-VL-Max 和 Claude 3 Opus 的卓越性能。\n\n## Model List\n\n|        Model        | Type | Seq Length | Transformers Version |                                                                                                      Download                                                                                                       |                                                                                        Online Demo                                                                                         |\n|:-------------------:|:----:|:----------:|:--------------------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|      GLM-4-9B       | Base |     8K     |  `4.44.0 - 4.45.0`   |             [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/glm-4-9b)             |                                                                                             /                                                                                              |\n|    GLM-4-9B-Chat    | Chat |    128K    |     `>= 4.44.0`      |     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat)      | [🤖 ModelScope CPU](https://modelscope.cn/studios/dash-infer/GLM-4-Chat-DashInfer-Demo/summary)<br> [🤖 ModelScope vLLM](https://modelscope.cn/studios/ZhipuAI/glm-4-9b-chat-vllm/summary) |\n|  GLM-4-9B-Chat-HF   | Chat |    128K    |     `>= 4.46.0`      |                                     [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-hf)                                      | [🤖 ModelScope CPU](https://modelscope.cn/studios/dash-infer/GLM-4-Chat-DashInfer-Demo/summary)<br> [🤖 ModelScope vLLM](https://modelscope.cn/studios/ZhipuAI/glm-4-9b-chat-vllm/summary) |\n|  GLM-4-9B-Chat-1M   | Chat |     1M     |     `>= 4.44.0`      | [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4-9B-Chat-1M) |                                                                                             /                                                                                              |\n| GLM-4-9B-Chat-1M-HF | Chat |     1M     |     `>= 4.46.0`      |                                  [🤗 Huggingface](https://huggingface.co/THUDM/glm-4-9b-chat-1m-hf)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat-1m-hf)                                   |                                                                                             /                                                                                              |\n|      GLM-4V-9B      | Chat |     8K     |     `>= 4.46.0`      |           [🤗 Huggingface](https://huggingface.co/THUDM/glm-4v-9b)<br> [🤖 ModelScope](https://modelscope.cn/models/ZhipuAI/glm-4v-9b)<br> [🟣 WiseModel](https://wisemodel.cn/models/ZhipuAI/GLM-4V-9B)            |                                                       [🤖 ModelScope](https://modelscope.cn/studios/ZhipuAI/glm-4v-9b-Demo/summary)                                                        |\n\n## 评测结果\n\n### 对话模型典型任务\n\n| Model               | AlignBench | MT-Bench | IFEval | MMLU | C-Eval | GSM8K | MATH | HumanEval | NaturalCodeBench |\n|:--------------------|:----------:|:--------:|:------:|:----:|:------:|:-----:|:----:|:---------:|:----------------:|\n| Llama-3-8B-Instruct |    6.40    |   8.00   |  68.6  | 68.4 |  51.3  | 79.6  | 30.0 |   62.2    |       24.7       |\n| ChatGLM3-6B         |    5.18    |   5.50   |  28.1  | 61.4 |  69.0  | 72.3  | 25.7 |   58.5    |       11.3       |\n| GLM-4-9B-Chat       |    7.01    |   8.35   |  69.0  | 72.4 |  75.6  | 79.6  | 50.6 |   71.8    |       32.2       |\n\n### 基座模型典型任务\n\n| Model               | MMLU | C-Eval | GPQA | GSM8K | MATH | HumanEval |\n|:--------------------|:----:|:------:|:----:|:-----:|:----:|:---------:|\n| Llama-3-8B          | 66.6 |  51.2  |  -   | 45.8  |  -   |   33.5    |\n| Llama-3-8B-Instruct | 68.4 |  51.3  | 34.2 | 79.6  | 30.0 |   62.2    |\n| ChatGLM3-6B-Base    | 61.4 |  69.0  | 26.8 | 72.3  | 25.7 |   58.5    |\n| GLM-4-9B            | 74.7 |  77.1  | 34.3 | 84.0  | 30.4 |   70.1    |\n\n> 由于 `GLM-4-9B` 在预训练过程中加入了部分数学、推理、代码相关的 instruction 数据，所以将 Llama-3-8B-Instruct 也列入比较范围。\n\n### 长文本\n\n在 1M 的上下文长度下进行[大海捞针实验](https://github.com/LargeWorldModel/LWM/blob/main/scripts/eval_needle.py)，结果如下：\n\n![needle](resources/eval_needle.jpeg)\n\n在 LongBench-Chat 上对长文本能力进行了进一步评测，结果如下:\n\n<p align=\"center\">\n<img src=\"resources/longbench.png\" alt=\"描述文字\" style=\"display: block; margin: auto; width: 65%;\">\n</p>\n\n### 多语言能力\n\n在六个多语言数据集上对 GLM-4-9B-Chat 和 Llama-3-8B-Instruct 进行了测试，测试结果及数据集对应选取语言如下表\n\n| Dataset     | Llama-3-8B-Instruct | GLM-4-9B-Chat |                                           Languages                                            |\n|:------------|:-------------------:|:-------------:|:----------------------------------------------------------------------------------------------:|\n| M-MMLU      |        49.6         |     56.6      |                                              all                                               |\n| FLORES      |        25.0         |     28.8      | ru, es, de, fr, it, pt, pl, ja, nl, ar, tr, cs, vi, fa, hu, el, ro, sv, uk, fi, ko, da, bg, no |\n| MGSM        |        54.0         |     65.3      |                           zh, en, bn, de, es, fr, ja, ru, sw, te, th                           |\n| XWinograd   |        61.7         |     73.1      |                                     zh, en, fr, jp, ru, pt                                     |\n| XStoryCloze |        84.7         |     90.7      |                           zh, en, ar, es, eu, hi, id, my, ru, sw, te                           |\n| XCOPA       |        73.3         |     80.1      |                           zh, et, ht, id, it, qu, sw, ta, th, tr, vi                           |\n\n### 工具调用能力\n\n我们在 [Berkeley Function Calling Leaderboard](https://github.com/ShishirPatil/gorilla/tree/main/berkeley-function-call-leaderboard)\n上进行了测试并得到了以下结果：\n\n| Model                  | Overall Acc. | AST Summary | Exec Summary | Relevance |\n|:-----------------------|:------------:|:-----------:|:------------:|:---------:|\n| Llama-3-8B-Instruct    |    58.88     |    59.25    |    70.01     |   45.83   |\n| gpt-4-turbo-2024-04-09 |    81.24     |    82.14    |    78.61     |   88.75   |\n| ChatGLM3-6B            |    57.88     |    62.18    |    69.78     |   5.42    |\n| GLM-4-9B-Chat          |    81.00     |    80.26    |    84.40     |   87.92   |\n\n### 多模态能力\n\nGLM-4V-9B 是一个多模态语言模型，具备视觉理解能力，其相关经典任务的评测结果如下：\n\n|                            | **MMBench-EN-Test** | **MMBench-CN-Test** | **SEEDBench_IMG** | **MMStar** | **MMMU** | **MME** | **HallusionBench** | **AI2D** | **OCRBench** |\n|----------------------------|---------------------|---------------------|-------------------|------------|----------|---------|--------------------|----------|--------------|\n| **gpt-4o-2024-05-13**      | 83.4                | 82.1                | 77.1              | 63.9       | 69.2     | 2310.3  | 55.0               | 84.6     | 736          |\n| **gpt-4-turbo-2024-04-09** | 81.0                | 80.2                | 73.0              | 56.0       | 61.7     | 2070.2  | 43.9               | 78.6     | 656          |\n| **gpt-4-1106-preview**     | 77.0                | 74.4                | 72.3              | 49.7       | 53.8     | 1771.5  | 46.5               | 75.9     | 516          |\n| **InternVL-Chat-V1.5**     | 82.3                | 80.7                | 75.2              | 57.1       | 46.8     | 2189.6  | 47.4               | 80.6     | 720          |\n| **LLaVA-Next-Yi-34B**      | 81.1                | 79.0                | 75.7              | 51.6       | 48.8     | 2050.2  | 34.8               | 78.9     | 574          |\n| **Step-1V**                | 80.7                | 79.9                | 70.3              | 50.0       | 49.9     | 2206.4  | 48.4               | 79.2     | 625          |\n| **MiniCPM-Llama3-V2.5**    | 77.6                | 73.8                | 72.3              | 51.8       | 45.8     | 2024.6  | 42.4               | 78.4     | 725          |\n| **Qwen-VL-Max**            | 77.6                | 75.7                | 72.7              | 49.5       | 52.0     | 2281.7  | 41.2               | 75.7     | 684          |\n| **Gemini 1.0 Pro**         | 73.6                | 74.3                | 70.7              | 38.6       | 49.0     | 2148.9  | 45.7               | 72.9     | 680          |\n| **Claude 3 Opus**          | 63.3                | 59.2                | 64.0              | 45.7       | 54.9     | 1586.8  | 37.8               | 70.6     | 694          |\n| **GLM-4V-9B**              | 81.1                | 79.4                | 76.8              | 58.7       | 47.2     | 2163.8  | 46.6               | 81.1     | 786          |\n\n## 快速调用\n\n**硬件配置和系统要求，请查看[这里](basic_demo/README.md)。**\n\n### 使用以下方法快速调用 GLM-4-9B-Chat 语言模型\n\n使用 transformers 后端进行推理:\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0' # 设置 GPU 编号，如果单机单卡指定一个，单机多卡指定多个 GPU 编号\nMODEL_PATH = \"THUDM/glm-4-9b-chat-hf\"\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n\nquery = \"你好\"\n\ninputs = tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": query}],\n                                       add_generation_prompt=True,\n                                       tokenize=True,\n                                       return_tensors=\"pt\",\n                                       return_dict=True\n                                       )\n\ninputs = inputs.to(device)\nmodel = AutoModelForCausalLM.from_pretrained(\n    MODEL_PATH,\n    torch_dtype=torch.bfloat16,\n    low_cpu_mem_usage=True,\n    trust_remote_code=True,\n    device_map=\"auto\"\n).eval()\n\ngen_kwargs = {\"max_length\": 2500, \"do_sample\": True, \"top_k\": 1}\nwith torch.no_grad():\n    outputs = model.generate(**inputs, **gen_kwargs)\n    outputs = outputs[:, inputs['input_ids'].shape[1]:]\n    print(tokenizer.decode(outputs[0], skip_special_tokens=True))\n```\n\n使用 vLLM 后端进行推理:\n\n```python\nfrom transformers import AutoTokenizer\nfrom vllm import LLM, SamplingParams\n\n# GLM-4-9B-Chat-1M\n# max_model_len, tp_size = 1048576, 4\n# 如果遇见 OOM 现象，建议减少max_model_len，或者增加tp_size\nmax_model_len, tp_size = 131072, 1\nmodel_name = \"THUDM/glm-4-9b-chat-hf\"\nprompt = [{\"role\": \"user\", \"content\": \"你好\"}]\n\ntokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)\nllm = LLM(\n    model=model_name,\n    tensor_parallel_size=tp_size,\n    max_model_len=max_model_len,\n    trust_remote_code=True,\n    enforce_eager=True,\n    # GLM-4-9B-Chat-1M 如果遇见 OOM 现象，建议开启下述参数\n    # enable_chunked_prefill=True,\n    # max_num_batched_tokens=8192\n)\nstop_token_ids = [151329, 151336, 151338]\nsampling_params = SamplingParams(temperature=0.95, max_tokens=1024, stop_token_ids=stop_token_ids)\n\ninputs = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)\noutputs = llm.generate(prompts=inputs, sampling_params=sampling_params)\n\nprint(outputs[0].outputs[0].text)\n```\n\n### 使用以下方法快速调用 GLM-4V-9B 多模态模型\n\n使用 transformers 后端进行推理:\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0' # 设置 GPU 编号，如果单机单卡指定一个，单机多卡指定多个 GPU 编号\nMODEL_PATH = \"THUDM/glm-4v-9b\"\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n\nquery = '描述这张图片'\nimage = Image.open(\"your image\").convert('RGB')\ninputs = tokenizer.apply_chat_template([{\"role\": \"user\", \"image\": image, \"content\": query}],\n                                       add_generation_prompt=True, tokenize=True, return_tensors=\"pt\",\n                                       return_dict=True)  # chat mode\n\ninputs = inputs.to(device)\nmodel = AutoModelForCausalLM.from_pretrained(\n    MODEL_PATH,\n    torch_dtype=torch.bfloat16,\n    low_cpu_mem_usage=True,\n    trust_remote_code=True,\n    device_map=\"auto\"\n).eval()\n\ngen_kwargs = {\"max_length\": 2500, \"do_sample\": True, \"top_k\": 1}\nwith torch.no_grad():\n    outputs = model.generate(**inputs, **gen_kwargs)\n    outputs = outputs[:, inputs['input_ids'].shape[1]:]\n    print(tokenizer.decode(outputs[0]))\n```\n\n使用 vLLM 后端进行推理:\n\n```python\nfrom PIL import Image\nfrom vllm import LLM, SamplingParams\n\nmodel_name = \"THUDM/glm-4v-9b\"\n\nllm = LLM(model=model_name,\n          tensor_parallel_size=1,\n          max_model_len=8192,\n          trust_remote_code=True,\n          enforce_eager=True)\nstop_token_ids = [151329, 151336, 151338]\nsampling_params = SamplingParams(temperature=0.2,\n                                 max_tokens=1024,\n                                 stop_token_ids=stop_token_ids)\n\nprompt = \"What's the content of the image?\"\nimage = Image.open(\"your image\").convert('RGB')\ninputs = {\n    \"prompt\": prompt,\n    \"multi_modal_data\": {\n        \"image\": image\n        },\n        }\noutputs = llm.generate(inputs, sampling_params=sampling_params)\n\nfor o in outputs:\n    generated_text = o.outputs[0].text\n    print(generated_text)\n\n```\n\n## 完整项目列表\n\n如果你想更进一步了解 GLM-4-9B 系列开源模型，本开源仓库通过以下内容为开发者提供基础的 GLM-4-9B 的使用和开发代码\n\n+ [basic_demo](basic_demo/README.md): 在这里包含了\n    + 使用 transformers 和 vLLM 后端的交互代码\n    + OpenAI API 后端交互代码\n    + Batch 推理代码\n\n+ [composite_demo](composite_demo/README.md): 在这里包含了\n    + GLM-4-9B-Chat 以及 GLM-4V-9B 开源模型的完整功能演示代码，包含了 All Tools 能力、长文档解读和多模态能力的展示。\n\n+ [fintune_demo](finetune_demo/README.md): 在这里包含了\n    + PEFT (LORA, P-Tuning) 微调代码\n    + SFT 微调代码\n\n + [intel_device_demo](intel_device_demo/): 在这里包含了\n   + 使用 OpenVINO 部署模型代码\n   + 使用 Intel® Extension for Transformers 部署模型代码\n\n## 友情链接\n\n+ [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory): 高效开源微调框架，已支持 GLM-4-9B-Chat 语言模型微调。\n+ [SWIFT](https://github.com/modelscope/swift): 魔搭社区的大模型/多模态大模型训练框架，已支持 GLM-4-9B-Chat / GLM-4V-9B\n  模型微调。\n+ [Xorbits Inference](https://github.com/xorbitsai/inference): 性能强大且功能全面的分布式推理框架，轻松一键部署你自己的模型或内置的前沿开源模型。\n+ [LangChain-ChatChat](https://github.com/chatchat-space/Langchain-Chatchat): 基于 Langchain 与 ChatGLM 等语言模型的 RAG\n  与 Agent 应用\n+ [self-llm](https://github.com/datawhalechina/self-llm/tree/master/models/GLM-4): Datawhale 团队的提供的 GLM-4-9B\n  系列模型使用教程。\n+ [chatglm.cpp](https://github.com/li-plus/chatglm.cpp): 类似 llama.cpp 的量化加速推理方案，实现笔记本上实时对话\n+ [OpenVINO](https://github.com/openvinotoolkit):\nIntel 开发的高性能 CPU,GPU及NPU 加速推理方案，可以参考此 [步骤](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/llm-chatbot/llm-chatbot-generate-api.ipynb) 部署 glm-4-9b-chat 模型。\n\n## 协议\n\n+ GLM-4 模型的权重的使用则需要遵循 [模型协议](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE)。\n\n+ 本开源仓库的代码则遵循 [Apache 2.0](LICENSE) 协议。\n\n请您严格遵循开源协议。\n\n## 引用\n\n如果你觉得我们的工作有帮助的话，请考虑引用下列论文。\n\n```\n@misc{glm2024chatglm,\n      title={ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools},\n      author={Team GLM and Aohan Zeng and Bin Xu and Bowen Wang and Chenhui Zhang and Da Yin and Diego Rojas and Guanyu Feng and Hanlin Zhao and Hanyu Lai and Hao Yu and Hongning Wang and Jiadai Sun and Jiajie Zhang and Jiale Cheng and Jiayi Gui and Jie Tang and Jing Zhang and Juanzi Li and Lei Zhao and Lindong Wu and Lucen Zhong and Mingdao Liu and Minlie Huang and Peng Zhang and Qinkai Zheng and Rui Lu and Shuaiqi Duan and Shudan Zhang and Shulin Cao and Shuxun Yang and Weng Lam Tam and Wenyi Zhao and Xiao Liu and Xiao Xia and Xiaohan Zhang and Xiaotao Gu and Xin Lv and Xinghan Liu and Xinyi Liu and Xinyue Yang and Xixuan Song and Xunkai Zhang and Yifan An and Yifan Xu and Yilin Niu and Yuantao Yang and Yueyan Li and Yushi Bai and Yuxiao Dong and Zehan Qi and Zhaoyu Wang and Zhen Yang and Zhengxiao Du and Zhenyu Hou and Zihan Wang},\n      year={2024},\n      eprint={2406.12793},\n      archivePrefix={arXiv},\n      primaryClass={id='cs.CL' full_name='Computation and Language' is_active=True alt_name='cmp-lg' in_archive='cs' is_general=False description='Covers natural language processing. Roughly includes material in ACM Subject Class I.2.7. Note that work on artificial languages (programming languages, logics, formal systems) that does not explicitly address natural-language issues broadly construed (natural-language processing, computational linguistics, speech, text retrieval, etc.) is not appropriate for this area.'}\n}\n```\n\n```\n@misc{wang2023cogvlm,\n      title={CogVLM: Visual Expert for Pretrained Language Models},\n      author={Weihan Wang and Qingsong Lv and Wenmeng Yu and Wenyi Hong and Ji Qi and Yan Wang and Junhui Ji and Zhuoyi Yang and Lei Zhao and Xixuan Song and Jiazheng Xu and Bin Xu and Juanzi Li and Yuxiao Dong and Ming Ding and Jie Tang},\n      year={2023},\n      eprint={2311.03079},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n"
  },
  {
    "path": "demo/composite_demo/.gitignore",
    "content": "*venv\n*.DS_Store\n*model\n*.idea/\n\n# Created by https://www.toptal.com/developers/gitignore/api/python\n# Edit at https://www.toptal.com/developers/gitignore?templates=python\n\n### Python ###\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n\n### Python Patch ###\n# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration\npoetry.toml\n\n# ruff\n.ruff_cache/\n\n# LSP config files\npyrightconfig.json\n\n# End of https://www.toptal.com/developers/gitignore/api/python\n"
  },
  {
    "path": "demo/composite_demo/README.md",
    "content": "# GLM-4-9B Web Demo\n\nRead this in [English](README_en.md)\n\n![Demo webpage](assets/demo.png)\n\n## 安装\n\n我们建议通过 [Conda](https://docs.conda.io/en/latest/) 进行环境管理。\n执行以下命令新建一个 conda 环境并安装所需依赖：\n\n```bash\nconda create -n glm-4-demo python=3.12\nconda activate glm-4-demo\npip install -r requirements.txt\n```\n\n请注意，本项目需要 Python 3.10 或更高版本。\n此外，使用 Code Interpreter 还需要安装 Jupyter 内核：\n\n```bash\nipython kernel install --name glm-4-demo --user\n```\n\n您可以修改 `~/.local/share/jupyter/kernels/glm-4-demo/kernel.json` 来改变 Jupyter 内核的配置，包括内核的启动参数等。例如，若您希望在使用 All Tools 的 Python 代码执行能力时使用 Matplotlib 画图，可以在 `argv` 数组中添加 `\"--matplotlib=inline\"`。\n\n若要使用浏览器和搜索功能，还需要启动浏览器后端。首先，根据 [Node.js](https://nodejs.org/en/download/package-manager)\n官网的指示安装 Node.js，然后安装包管理器 [PNPM](https://pnpm.io) 之后安装浏览器服务的依赖：\n\n```bash\ncd browser\nnpm install -g pnpm\npnpm install\n```\n\n## 运行\n\n1. 修改 `browser/src/config.ts` 中的 `BING_SEARCH_API_KEY` 配置浏览器服务需要使用的 Bing 搜索 API Key：\n\n    ```diff\n    export default {\n\n        BROWSER_TIMEOUT: 10000,\n        BING_SEARCH_API_URL: 'https://api.bing.microsoft.com/v7.0',\n        BING_SEARCH_API_KEY: '<PUT_YOUR_BING_SEARCH_KEY_HERE>',\n\n        HOST: 'localhost',\n        PORT: 3000,\n    };\n    ```\n   如果您注册的是Bing Customer Search的API，您可以修改您的配置文件为如下，并且填写您的Custom Configuration ID:\n\n    ```diff\n    export default {\n        LOG_LEVEL: 'debug',\n        BROWSER_TIMEOUT: 10000,\n        BING_SEARCH_API_URL: 'https://api.bing.microsoft.com/v7.0/custom/',\n        BING_SEARCH_API_KEY: 'YOUR_BING_SEARCH_API_KEY',\n        CUSTOM_CONFIG_ID :  'YOUR_CUSTOM_CONFIG_ID', //将您的Custom Configuration ID放在此处\n        HOST: 'localhost',\n        PORT: 3000,\n   };\n    ```\n\n2. 文生图功能需要调用 CogView API。修改 `src/tools/config.py`\n   ，提供文生图功能需要使用的 [智谱 AI 开放平台](https://open.bigmodel.cn) API Key：\n\n    ```diff\n    BROWSER_SERVER_URL = 'http://localhost:3000'\n\n    IPYKERNEL = 'glm-4-demo'\n\n    ZHIPU_AI_KEY = '<PUT_YOUR_ZHIPU_AI_KEY_HERE>'\n    COGVIEW_MODEL = 'cogview-3'\n    ```\n\n3. 启动浏览器后端，在单独的 shell 中：\n\n    ```bash\n    cd browser\n    pnpm start\n    ```\n\n4. 运行以下命令在本地加载模型并启动 demo：\n\n    ```bash\n    streamlit run src/main.py\n    ```\n\n之后即可从命令行中看到 demo 的地址，点击即可访问。初次访问需要下载并加载模型，可能需要花费一定时间。\n\n如果已经在本地下载了模型，可以通过 `export *_MODEL_PATH=/path/to/model` 来指定从本地加载模型。可以指定的模型包括：\n- `CHAT_MODEL_PATH`: 用于 All Tools 模式与文档解读模式，默认为 `THUDM/glm-4-9b-chatglm-4-9b-chat`。\n- `VLM_MODEL_PATH`: 用于 VLM 模式，默认为 `THUDM/glm-4v-9b`。\n\nChat 模型支持使用 [vLLM](https://github.com/vllm-project/vllm) 推理。若要使用，请安装 vLLM 并设置环境变量 `USE_VLLM=1`。\n\nChat 模型支持使用 [OpenAI API](https://platform.openai.com/docs/api-reference/introduction) 推理。若要使用，请启动basic_demo目录下的openai_api_server并设置环境变量 `USE_API=1`。该功能可以解耦推理服务器和demo服务器。\n\n如果需要自定义 Jupyter 内核，可以通过 `export IPYKERNEL=<kernel_name>` 来指定。\n\n## 使用\n\nGLM-4 Demo 拥有三种模式：\n\n- All Tools: 具有完整工具调用能力的对话模式，原生支持网页浏览、代码执行、图片生成，并支持自定义工具。\n- 文档解读: 支持上传文档进行文档解读与对话。\n- 多模态: 支持上传图像进行图像理解与对话。\n\n### All Tools\n\n本模式兼容 ChatGLM3-6B 的工具注册流程。\n+ 代码能力，绘图能力，联网能力已经自动集成，用户只需按照要求配置对应的Key。\n+ 本模式下不支持系统提示词，模型会自动构建提示词。\n\n对话模式下，用户可以直接在侧边栏修改 top_p, temperature 等参数来调整模型的行为。\n\n与模型对话时，模型将会自主决定进行工具调用。\n\n![Tool calling](assets/tool.png)\n\n由于原始结果可能较长，默认情况下工具调用结果被隐藏，可以通过展开折叠框查看原始的工具调用结果。\n\n模型拥有进行网页搜索和 Python 代码执行的能力。同时，模型也可以连续调用多个工具。例如：\n\n![Consecutive tool calling, 1](assets/web_plot_1.png)\n\n此时模型通过调用浏览器工具进行搜索获取到了需要的数据，之后将会调用 Python 工具执行代码，利用 Matplotlib 绘图：\n\n![Consecutive tool calling, 2](assets/web_plot_2.png)\n\n如果提供了智谱开放平台 API Key，模型也可以调用 CogView 进行图像生成：\n\n![Image generation](assets/cogview.png)\n\n#### 自定义工具\n\n可以通过在 `tool_registry.py` 中注册新的工具来增强模型的能力。只需要使用 `@register_tool`\n装饰函数即可完成注册。对于工具声明，函数名称即为工具的名称，函数 docstring\n即为工具的说明；对于工具的参数，使用 `Annotated[typ: type, description: str, required: bool]` 标注参数的类型、描述和是否必须。\n\n例如，`get_weather` 工具的注册如下：\n\n```python\n@register_tool\ndef get_weather(\n        city_name: Annotated[str, 'The name of the city to be queried', True],\n) -> str:\n    \"\"\"\n    Get the weather for `city_name` in the following week\n    \"\"\"\n    ...\n```\n\n![The model uses tool to query the weather of Bangkok.](assets/weather.png)\n\n### 文档解读\n\n用户可以上传文档，使用 GLM-4-9B的长文本能力，对文本进行理解。可以解析 pptx，docx，pdf等文件。\n\n+ 本模式下不支持工具调用和系统提示词。\n+ 如果文本很长，可能导致模型需要的显存较高，请确认你的硬件配置。\n\n![Doc reader demo](assets/doc_reader.png)\n\n### 多模态\n\n多模态模式下，用户可以利用 GLM-4V 的多模态理解能力，上传图像并与 GLM-4V 进行多轮对话：\n\n用户可以上传图片，使用 GLM-4-9B的图像理解能力，对图片进行理解。\n\n+ 本模式必须使用 glm-4v-9b 模型。\n+ 本模式下不支持工具调用和系统提示词。\n+ 模型仅能对一张图片进行理解和联系对话，如需更换图片，需要开启一个新的对话。\n+ 图像支持的分辨率为 1120 x 1120\n\n![VLM demo](assets/vlm.png)\n"
  },
  {
    "path": "demo/composite_demo/README_en.md",
    "content": "# GLM-4-9B Web Demo\n\n![Demo webpage](assets/demo.png)\n\n## Installation\n\nWe recommend using [Conda](https://docs.conda.io/en/latest/) for environment management.\n\nExecute the following commands to create a conda environment and install the required dependencies:\n\n```bash\nconda create -n glm-4-demo python=3.12\nconda activate glm-4-demo\npip install -r requirements.txt\n```\n\nPlease note that this project requires Python 3.10 or higher.\nIn addition, you need to install the Jupyter kernel to use the Code Interpreter:\n\n```bash\nipython kernel install --name glm-4-demo --user\n```\n\nYou can modify `~/.local/share/jupyter/kernels/glm-4-demo/kernel.json` to change the configuration of the Jupyter\nkernel, including the kernel startup parameters. For example, if you want to use Matplotlib to draw when using the\nPython code execution capability of All Tools, you can add `\"--matplotlib=inline\"` to the `argv` array.\n\nTo use the browser and search functions, you also need to start the browser backend. First, install Node.js according to\nthe instructions on the [Node.js](https://nodejs.org/en/download/package-manager)\nofficial website, then install the package manager [PNPM](https://pnpm.io) and then install the browser service\ndependencies:\n\n```bash\ncd browser\nnpm install -g pnpm\npnpm install\n```\n\n## Run\n\n1. Modify `BING_SEARCH_API_KEY` in `browser/src/config.ts` to configure the Bing Search API Key that the browser service\n   needs to use:\n\n```diff\nexport default {\n\n   BROWSER_TIMEOUT: 10000,\n   BING_SEARCH_API_URL: 'https://api.bing.microsoft.com/v7.0',\n   BING_SEARCH_API_KEY: '<PUT_YOUR_BING_SEARCH_KEY_HERE>',\n\n   HOST: 'localhost',\n   PORT: 3000,\n};\n```\n\n2. The Wenshengtu function needs to call the CogView API. Modify `src/tools/config.py`\n   , provide the [Zhipu AI Open Platform](https://open.bigmodel.cn) API Key required for the Wenshengtu function:\n\n```diff\nBROWSER_SERVER_URL = 'http://localhost:3000'\n\nIPYKERNEL = 'glm4-demo'\n\nZHIPU_AI_KEY = '<PUT_YOUR_ZHIPU_AI_KEY_HERE>'\nCOGVIEW_MODEL = 'cogview-3'\n```\n\n3. Start the browser backend in a separate shell:\n\n```bash\ncd browser\npnpm start\n```\n\n4. Run the following commands to load the model locally and start the demo:\n\n```bash\nstreamlit run src/main.py\n```\n\nThen you can see the demo address from the command line and click it to access it. The first access requires downloading\nand loading the model, which may take some time.\n\nIf you have downloaded the model locally, you can specify to load the model from the local\nby `export *_MODEL_PATH=/path/to/model`. The models that can be specified include:\n\n- `CHAT_MODEL_PATH`: used for All Tools mode and document interpretation mode, the default is `THUDM/glm-4-9b-chat`.\n\n- `VLM_MODEL_PATH`: used for VLM mode, the default is `THUDM/glm-4v-9b`.\n\nThe Chat model supports reasoning using [vLLM](https://github.com/vllm-project/vllm). To use it, please install vLLM and\nset the environment variable `USE_VLLM=1`.\n\nThe Chat model also supports reasoning using [OpenAI API](https://platform.openai.com/docs/api-reference/introduction). To use it, please run `openai_api_server.py` in `inference` and set the environment variable `USE_API=1`. This function is used to deploy inference server and demo server in different machine.\n\nIf you need to customize the Jupyter kernel, you can specify it by `export IPYKERNEL=<kernel_name>`.\n\n## Usage\n\nGLM4 Demo has three modes:\n\n- All Tools mode\n- VLM mode\n- Text interpretation mode\n\n### All Tools mode\n\nYou can enhance the model's capabilities by registering new tools in `tool_registry.py`. Just use `@register_tool`\ndecorated function to complete the registration. For tool declarations, the function name is the name of the tool, and\nthe function docstring\nis the description of the tool; for tool parameters, use `Annotated[typ: type, description: str, required: bool]` to\nannotate the parameter type, description, and whether it is required.\n\nFor example, the registration of the `get_weather` tool is as follows:\n\n```python\n@register_tool\ndef get_weather(\n        city_name: Annotated[str, 'The name of the city to be queried', True],\n) -> str:\n\n\n    \"\"\"\n    Get the weather for `city_name` in the following week\n    \"\"\"\n...\n```\n\nThis mode is compatible with the tool registration process of ChatGLM3-6B.\n\n+ Code capability, drawing capability, and networking capability have been automatically integrated. Users only need to\n  configure the corresponding Key as required.\n+ System prompt words are not supported in this mode. The model will automatically build prompt words.\n\n## Text interpretation mode\n\nUsers can upload documents and use the long text capability of GLM-4-9B to understand the text. It can parse pptx, docx,\npdf and other files.\n\n+ Tool calls and system prompt words are not supported in this mode.\n+ If the text is very long, the model may require a high amount of GPU memory. Please confirm your hardware\n  configuration.\n\n## Image Understanding Mode\n\nUsers can upload images and use the image understanding capabilities of GLM-4-9B to understand the images.\n\n+ This mode must use the glm-4v-9b model.\n+ Tool calls and system prompts are not supported in this mode.\n+ The model can only understand and communicate with one image. If you need to change the image, you need to open a new\n  conversation.\n+ The supported image resolution is 1120 x 1120\n"
  },
  {
    "path": "demo/composite_demo/browser/.gitignore",
    "content": "# Created by https://www.toptal.com/developers/gitignore/api/node\n# Edit at https://www.toptal.com/developers/gitignore?templates=node\n\n### Node ###\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp and cache directory\n.temp\n\n# Docusaurus cache and generated files\n.docusaurus\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# yarn v2\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.yarn/install-state.gz\n.pnp.*\n\n### Node Patch ###\n# Serverless Webpack directories\n.webpack/\n\n# Optional stylelint cache\n\n# SvelteKit build / generate output\n.svelte-kit\n\n# End of https://www.toptal.com/developers/gitignore/api/node\n"
  },
  {
    "path": "demo/composite_demo/browser/package.json",
    "content": "{\n  \"name\": \"glm4-browser\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Browser system for GLM-4\",\n  \"main\": \"src/server.ts\",\n  \"scripts\": {\n    \"dev\": \"npx nodemon src/server\",\n    \"start\": \"npx ts-node src/server.ts\"\n  },\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.18.3\",\n    \"jsdom\": \"^24.0.0\",\n    \"pnpm\": \"^9.1.2\",\n    \"turndown\": \"^7.1.2\",\n    \"winston\": \"^3.11.0\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.21\",\n    \"@types/jsdom\": \"^21.1.6\",\n    \"@types/node\": \"^20.11.20\",\n    \"@types/turndown\": \"^5.0.4\",\n    \"nodemon\": \"^3.1.0\",\n    \"ts-node\": \"^10.9.2\"\n  }\n}\n"
  },
  {
    "path": "demo/composite_demo/browser/src/browser.ts",
    "content": "import { JSDOM } from 'jsdom';\nimport TurndownService from 'turndown';\n\nimport config from './config';\nimport { Message, ToolObservation } from './types';\nimport { logger, withTimeout } from './utils';\n\n// represent a quote from a display\ninterface Quote {\n  text: string;\n  metadata: Metadata[];\n}\n\ninterface ActionResult {\n  contentType: string;\n  metadataList?: TetherQuoteMetadata[];\n  metadata?: any;\n  roleMetadata: string;\n  message: string;\n}\n\n// represent a piece of metadata to be marked in the final answer\ninterface Metadata {\n  type: string;\n  title: string;\n  url: string;\n  lines: string[];\n}\n\ninterface TetherQuoteExtra {\n  cited_message_idx: number;\n  evidence_text: string;\n}\n\ninterface TetherQuoteMetadata {\n  type: string;\n  title: string;\n  url: string;\n  text: string;\n  pub_date?: string;\n  extra?: TetherQuoteExtra;\n}\n\ninterface Citation {\n  citation_format_type: string;\n  start_ix: number;\n  end_ix: number;\n  metadata?: TetherQuoteMetadata;\n  invalid_reason?: string;\n}\n\ninterface PageState {\n  aCounter: number;\n  imgCounter: number;\n\n  url: URL;\n  url_string: string;\n  hostname: string;\n  links: string[];\n  links_meta: TetherQuoteMetadata[];\n  lines: string[];\n  line_source: Record<string, Metadata>; // string representation of number interval\n  title?: string;\n}\n\ninterface BrowserState {\n  pageStack: PageState[];\n  quoteCounter: number;\n  quotes: Record<string, Quote>;\n}\n\nfunction removeDenseLinks(document: Document, ratioThreshold: number = 0.5) {\n  // Remove nav elements\n  const navs = document.querySelectorAll('nav');\n  navs.forEach(nav => {\n    if (nav.parentNode) {\n      nav.parentNode.removeChild(nav);\n    }\n  });\n\n  // Query for lists, divs, spans, tables, and paragraphs\n  const elements = document.querySelectorAll('ul, ol, div, span, nav, table, p');\n  elements.forEach(element => {\n    if (element === null) return;\n\n    const children = Array.from(element.childNodes);\n    const links = element.querySelectorAll('a');\n\n    if (children.length <= 1) return;\n\n    const allText = element.textContent ? element.textContent.trim().replace(/\\s+/g, '') : '';\n    const linksText = Array.from(links)\n      .map(link => (link.textContent ? link.textContent.trim() : ''))\n      .join('')\n      .replace(/\\s+/g, '');\n\n    if (allText.length === 0 || linksText.length === 0) return;\n\n    let ratio = linksText.length / allText.length;\n    if (ratio > ratioThreshold && element.parentNode) {\n      element.parentNode.removeChild(element);\n    }\n  });\n}\n\nabstract class BaseBrowser {\n  public static toolName = 'browser' as const;\n  public description = 'BaseBrowser';\n\n  private turndownService = new TurndownService({\n    headingStyle: 'atx',\n  });\n\n  private state: BrowserState;\n\n  private transform(dom: JSDOM): string {\n    let state = this.lastPageState();\n    state.aCounter = 0;\n    state.imgCounter = 0;\n    state.links = [];\n\n    return this.turndownService.turndown(dom.window.document);\n  }\n\n  private formatPage(state: PageState): string {\n    let formatted_lines = state.lines.join('\\n');\n    let formatted_title = state.title ? `TITLE: ${state.title}\\n\\n` : '';\n    let formatted_range = `\\nVisible: 0% - 100%`;\n    let formatted_message = formatted_title + formatted_lines + formatted_range;\n    return formatted_message;\n  }\n\n  private newPageState(): PageState {\n    return {\n      aCounter: 0,\n      imgCounter: 0,\n\n      url: new URL('about:blank'),\n      url_string: 'about:blank',\n      hostname: '',\n      title: '',\n      links: [],\n      links_meta: [],\n      lines: [],\n      line_source: {},\n    };\n  }\n\n  private pushPageState(): PageState {\n    let state = this.newPageState();\n    this.state.pageStack.push(state);\n    return state;\n  }\n\n  private lastPageState(): PageState {\n    if (this.state.pageStack.length === 0) {\n      throw new Error('No page state');\n    }\n    return this.state.pageStack[this.state.pageStack.length - 1];\n  }\n\n  private formatErrorUrl(url: string): string {\n    let TRUNCATION_LIMIT = 80;\n    if (url.length <= TRUNCATION_LIMIT) {\n      return url;\n    }\n    return url.slice(0, TRUNCATION_LIMIT) + `... (URL truncated at ${TRUNCATION_LIMIT} chars)`;\n  }\n\n  protected functions = {\n    search: async (query: string, recency_days: number = -1) => {\n      logger.debug(`Searching for: ${query}`);\n      const search = new URLSearchParams({ q: query });\n      recency_days > 0 && search.append('recency_days', recency_days.toString());\n      if (config.CUSTOM_CONFIG_ID) {\n    search.append('customconfig', config.CUSTOM_CONFIG_ID.toString());\n}\n      const url = `${config.BING_SEARCH_API_URL}/search?${search.toString()}`;\n      console.log('Full URL:', url); // 输出完整的 URL查看是否正确\n\n      return withTimeout(\n        config.BROWSER_TIMEOUT,\n        fetch(url, {\n          headers: {\n            'Ocp-Apim-Subscription-Key': config.BING_SEARCH_API_KEY,\n          }\n        })\n            .then(\n          res =>\n            res.json() as Promise<{\n              queryContext: {\n                originalQuery: string;\n              };\n              webPages: {\n                webSearchUrl: string;\n                totalEstimatedMatches: number;\n                value: {\n                  id: string;\n                  name: string;\n                  url: string;\n                  datePublished: string; // 2018-05-18T08:00:00.0000000\n                  datePublishedDisplayText: string;\n                  isFamilyFriendly: boolean;\n                  displayUrl: string;\n                  snippet: string;\n                  dateLastCrawled: string;\n                  cachedPageUrl: string;\n                  language: string;\n                  isNavigational: boolean;\n                }[];\n              };\n              rankingResponse: {\n                mainline: {\n                  items: {\n                    answerType: 'WebPages';\n                    resultIndex: number;\n                    value: {\n                      id: string;\n                    };\n                  }[];\n                };\n              };\n            }>,\n        ),\n      )\n        .then(async ({ value: res }) => {\n          try {\n            let state = this.pushPageState();\n            let metadataList: TetherQuoteMetadata[] = [];\n            for (const [i, entry] of res.webPages.value.entries()) {\n              const url = new URL(entry.url);\n              const hostname = url.hostname;\n              state.lines.push(` # 【${i}†${entry.name}†${hostname}】`);\n              state.lines.push(entry.snippet);\n              const quoteMetadata: Metadata = {\n                type: 'webpage',\n                title: entry.name,\n                url: entry.url,\n                lines: state.lines.slice(2 * i, 2 * i + 2),\n              };\n              state.line_source[`${2 * i}-${2 * i + 1}`] = quoteMetadata;\n              state.links[i] = entry.url;\n\n              const returnMetadata: TetherQuoteMetadata = {\n                type: quoteMetadata.type,\n                title: quoteMetadata.title,\n                url: quoteMetadata.url,\n                text: state.lines[2 * i + 1], // only content, not link\n                pub_date: entry.datePublished,\n              };\n              metadataList.push(returnMetadata);\n            }\n            const returnContentType = 'browser_result';\n            return {\n              contentType: returnContentType,\n              roleMetadata: returnContentType,\n              message: this.formatPage(state),\n              metadataList,\n            };\n          } catch (err) {\n            throw new Error(`parse error: ${err}`);\n          }\n        })\n        .catch(err => {\n          logger.error(`搜索请求失败：${query}，错误信息：${err.message}`);\n          if (err.code === 'ECONNABORTED') {\n            throw new Error(`Timeout while executing search for: ${query}`);\n          }\n          throw new Error(`网络或服务器发生错误，请检查URL: ${url}`);\n        });\n    },\n    open_url: (url: string) => {\n      logger.debug(`Opening ${url}`);\n\n      return withTimeout(\n        config.BROWSER_TIMEOUT,\n        fetch(url).then(res => res.text()),\n      )\n        .then(async ({ value: res, time }) => {\n          try {\n            const state = this.pushPageState();\n            state.url = new URL(url);\n            state.url_string = url;\n            state.hostname = state.url.hostname;\n\n            const html = res;\n            const dom = new JSDOM(html);\n            const title = dom.window.document.title;\n            const markdown = this.transform(dom);\n\n            state.title = title;\n\n            // Remove first line, because it will be served as the title\n            const lines = markdown.split('\\n');\n            lines.shift();\n            // Remove consequent empty lines\n            let i = 0;\n            while (i < lines.length - 1) {\n              if (lines[i].trim() === '' && lines[i + 1].trim() === '') {\n                lines.splice(i, 1);\n              } else {\n                i++;\n              }\n            }\n\n            let page = lines.join('\\n');\n\n            // The first line feed is not a typo\n            let text_result = `\\nURL: ${url}\\n${page}`;\n            state.lines = text_result.split('\\n');\n\n            // all lines has only one source\n            state.line_source = {};\n            state.line_source[`0-${state.lines.length - 1}`] = {\n              type: 'webpage',\n              title: title,\n              url: url,\n              lines: state.lines,\n            };\n\n            let message = this.formatPage(state);\n\n            const returnContentType = 'browser_result';\n            return {\n              contentType: returnContentType,\n              roleMetadata: returnContentType,\n              message,\n              metadataList: state.links_meta,\n            };\n          } catch (err) {\n            throw new Error(`parse error: ${err}`);\n          }\n        })\n        .catch(err => {\n          logger.error(err.message);\n          if (err.code === 'ECONNABORTED') {\n            throw new Error(`Timeout while loading page w/ URL: ${url}`);\n          }\n          throw new Error(`Failed to load page w/ URL: ${url}`);\n        });\n    },\n    mclick: (ids: number[]) => {\n      logger.info('Entering mclick', ids);\n      let promises: Promise<ActionResult>[] = [];\n      let state = this.lastPageState();\n      for (let id of ids) {\n        if (isNaN(id) || id >= state.links.length) {\n          promises.push(\n            Promise.reject(\n              new Error(\n                `recorded='click(${id})' temporary=None permanent=None new_state=None final=None success=False feedback='Error parsing ID ${id}' metadata={}`,\n              ),\n            ),\n          );\n          continue;\n        }\n\n        let url: string;\n        try {\n          url = new URL(state.links[id], state.url).href;\n        } catch (err) {\n          logger.error(`Failed in getting ${state.links[id]}, ${state.url}`);\n          promises.push(\n            Promise.reject(\n              new Error(\n                `recorded='click(${id})' temporary=None permanent='${err}' new_state=None final=None success=False feedback='Error parsing URL for ID ${id}' metadata={}`,\n              ),\n            ),\n          );\n          continue;\n        }\n\n        const quoteIndex = this.state.quoteCounter++; // ascending in final results\n        promises.push(\n          withTimeout(\n            config.BROWSER_TIMEOUT,\n            fetch(url).then(res => res.text()),\n          )\n            .then(({ value: res, time }) => {\n              let state = this.newPageState();\n              state.url = new URL(url);\n              state.hostname = state.url.hostname;\n\n              try {\n                const html = res;\n                const dom = new JSDOM(html);\n                const title = dom.window.document.title;\n                state.title = title;\n                removeDenseLinks(dom.window.document);\n                let quoteText = this.transform(dom);\n                // remove consecutive newline\n                quoteText = quoteText.replace(/[\\r\\n]+/g, '\\n');\n                const quoteLines = quoteText.split('\\n');\n                state.lines = quoteLines;\n                const metadata = {\n                  type: 'webpage',\n                  title: title,\n                  url: url,\n                  lines: quoteLines,\n                };\n                const quoteMetadata = {\n                  type: 'webpage',\n                  title: title,\n                  url: url,\n                  text: quoteText,\n                };\n                state.line_source = {};\n                state.line_source[`0-${state.lines.length - 1}`] = metadata;\n                this.state.quotes[quoteIndex.toString()] = {\n                  text: quoteText,\n                  metadata: [metadata],\n                };\n\n                const returnContentType = 'quote_result';\n                return {\n                  contentType: returnContentType,\n                  roleMetadata: `${returnContentType} [${quoteIndex}†source]`,\n                  message: quoteText,\n                  metadataList: [quoteMetadata],\n                  metadata: {\n                    url,\n                  },\n                };\n              } catch (err) {\n                throw new Error(`parse error: ${err}`);\n              }\n            })\n            .catch(err => {\n              logger.error(err.message);\n              if (err.code === 'ECONNABORTED') {\n                throw new Error(`Timeout while loading page w/ URL: ${this.formatErrorUrl(url)}`);\n              }\n              throw new Error(`Failed to load page w/ URL: ${this.formatErrorUrl(url)}`);\n            })\n            .catch(err => {\n              // format error message\n              const returnContentType = 'system_error';\n              throw {\n                contentType: returnContentType,\n                roleMetadata: returnContentType,\n                message: `recorded='click(${id})' temporary=None permanent='${\n                  err.message\n                }' new_state=None final=None success=False feedback='Error fetching url ${this.formatErrorUrl(\n                  url,\n                )}' metadata={}`,\n                metadata: {\n                  failedURL: url,\n                },\n              } as ActionResult;\n            }),\n        );\n      }\n\n      return Promise.allSettled(promises).then(async results => {\n        const actionResults = results.map(r => {\n          if (r.status === 'fulfilled') {\n            return r.value;\n          } else {\n            logger.error(r.reason);\n            return r.reason as ActionResult;\n          }\n        });\n\n        if (results.filter(r => r.status === 'fulfilled').length === 0) {\n          // collect errors\n          const err_text = (results as PromiseRejectedResult[])\n            .map(r => (r.reason as ActionResult).message)\n            .join('\\n');\n          throw new Error(err_text);\n        } else {\n          return actionResults;\n        }\n      });\n    },\n  };\n\n  constructor() {\n    this.state =  {\n      pageStack: [],\n      quotes: {},\n      quoteCounter: 7,\n    };\n\n    this.turndownService.remove('script');\n    this.turndownService.remove('style');\n\n    // Add rules for turndown\n    this.turndownService.addRule('reference', {\n      filter: function (node, options: any): boolean {\n        return (\n          options.linkStyle === 'inlined' &&\n          node.nodeName === 'A' &&\n          node.getAttribute('href') !== undefined\n        );\n      },\n\n      replacement: (content, node, options): string => {\n        let state = this.state.pageStack[this.state.pageStack.length - 1];\n        if (!content || !('getAttribute' in node)) return '';\n        let href = undefined;\n        try {\n          if ('getAttribute' in node) {\n            const hostname = new URL(node.getAttribute('href')!).hostname;\n            // Do not append hostname when in the same domain\n            if (hostname === state.hostname || !hostname) {\n              href = '';\n            } else {\n              href = '†' + hostname;\n            }\n          }\n        } catch (e) {\n          // To prevent displaying links like '/foo/bar'\n          href = '';\n        }\n        if (href === undefined) return '';\n\n        const url = node.getAttribute('href')!;\n        let linkId = state.links.findIndex(link => link === url);\n        if (linkId === -1) {\n          linkId = state.aCounter++;\n          // logger.debug(`New link[${linkId}]: ${url}`);\n          state.links_meta.push({\n            type: 'webpage',\n            title: node.textContent!,\n            url: href,\n            text: node.textContent!,\n          });\n          state.links.push(url);\n        }\n        return `【${linkId}†${node.textContent}${href}】`;\n      },\n    });\n    this.turndownService.addRule('img', {\n      filter: 'img',\n\n      replacement: (content, node, options): string => {\n        let state = this.state.pageStack[this.state.pageStack.length - 1];\n        return `[Image ${state.imgCounter++}]`;\n      },\n    });\n    // Just to change indentation, wondering why this isn't exposed as an option\n    this.turndownService.addRule('list', {\n      filter: 'li',\n\n      replacement: function (content, node, options) {\n        content = content\n          .replace(/^\\n+/, '') // remove leading newlines\n          .replace(/\\n+$/, '\\n') // replace trailing newlines with just a single one\n          .replace(/\\n/gm, '\\n  '); // indent\n\n        let prefix = options.bulletListMarker + ' ';\n        const parent = node.parentNode! as Element;\n        if (parent.nodeName === 'OL') {\n          const start = parent.getAttribute('start');\n          const index = Array.prototype.indexOf.call(parent.children, node);\n          prefix = (start ? Number(start) + index : index + 1) + '.  ';\n        }\n        return '  ' + prefix + content + (node.nextSibling && !/\\n$/.test(content) ? '\\n' : '');\n      },\n    });\n    // Remove bold; remove() doesn't work on this, I don't know why\n    this.turndownService.addRule('emph', {\n      filter: ['strong', 'b'],\n\n      replacement: function (content, node, options) {\n        if (!content.trim()) return '';\n        return content;\n      },\n    });\n  }\n\n  abstract actionLine(content: string): Promise<ActionResult | ActionResult[]>;\n\n  async action(content: string): Promise<ToolObservation[]> {\n    const lines = content.split('\\n');\n    let results: ActionResult[] = [];\n    for (const line of lines) {\n      logger.info(`Action line: ${line}`)\n      try {\n        const lineActionResult = await this.actionLine(line);\n        logger.debug(`Action line result: ${JSON.stringify(lineActionResult, null, 2)}`);\n        if (Array.isArray(lineActionResult)) {\n          results = results.concat(lineActionResult);\n        } else {\n          results.push(lineActionResult);\n        }\n      } catch (err) {\n        const returnContentType = 'system_error';\n        results.push({\n          contentType: returnContentType,\n          roleMetadata: returnContentType,\n          message: `Error when executing command ${line}\\n${err}`,\n          metadata: {\n            failedCommand: line,\n          },\n        });\n      }\n    }\n    const observations: ToolObservation[] = [];\n    for (const result of results) {\n      const observation: ToolObservation = {\n        contentType: result.contentType,\n        result: result.message,\n        roleMetadata: result.roleMetadata,\n        metadata: result.metadata ?? {},\n      };\n\n      if (result.metadataList) {\n        observation.metadata.metadata_list = result.metadataList;\n      }\n      observations.push(observation);\n    }\n    return observations;\n  }\n\n  postProcess(message: Message, metadata: any) {\n    const quotePattern = /【(.+?)†(.*?)】/g;\n    const content = message.content;\n    let match;\n    let citations: Citation[] = [];\n    const citation_format_type = 'tether_og';\n    while ((match = quotePattern.exec(content))) {\n      logger.debug(`Citation match: ${match[0]}`);\n      const start_ix = match.index;\n      const end_ix = match.index + match[0].length;\n\n      let invalid_reason = undefined;\n      let metadata: TetherQuoteMetadata;\n      try {\n        let cited_message_idx = parseInt(match[1]);\n        let evidence_text = match[2];\n        let quote = this.state.quotes[cited_message_idx.toString()];\n        if (quote === undefined) {\n          invalid_reason = `'Referenced message ${cited_message_idx} in citation 【${cited_message_idx}†${evidence_text}】 is not a quote or tether browsing display.'`;\n          logger.error(`Triggered citation error with quote undefined: ${invalid_reason}`);\n          citations.push({\n            citation_format_type,\n            start_ix,\n            end_ix,\n            invalid_reason,\n          });\n        } else {\n          let extra: TetherQuoteExtra = {\n            cited_message_idx,\n            evidence_text,\n          };\n          const quote_metadata = quote.metadata[0];\n          metadata = {\n            type: 'webpage',\n            title: quote_metadata.title,\n            url: quote_metadata.url,\n            text: quote_metadata.lines.join('\\n'),\n            extra,\n          };\n          citations.push({\n            citation_format_type,\n            start_ix,\n            end_ix,\n            metadata,\n          });\n        }\n      } catch (err) {\n        logger.error(`Triggered citation error: ${err}`);\n        invalid_reason = `Citation Error: ${err}`;\n        citations.push({\n          start_ix,\n          end_ix,\n          citation_format_type,\n          invalid_reason,\n        });\n      }\n    }\n    metadata.citations = citations;\n  }\n\n  getState() {\n    return this.state;\n  }\n}\n\nexport class SimpleBrowser extends BaseBrowser {\n  public description = 'SimpleBrowser';\n\n  constructor() {\n    super();\n  }\n\n  async actionLine(content: string): Promise<ActionResult | ActionResult[]> {\n    const regex = /(\\w+)\\(([^)]*)\\)/;\n    const matches = content.match(regex);\n\n    if (matches) {\n      const functionName = matches[1];\n      let args_string = matches[2];\n      if (functionName === 'mclick') {\n        args_string = args_string.trim().slice(1, -1); // remove '[' and ']'\n      }\n\n      const args = args_string.split(',').map(arg => arg.trim());\n\n      let result;\n      switch (functionName) {\n        case 'search':\n          logger.debug(`SimpleBrowser action search ${args[0].slice(1, -1)}`);\n          const recency_days = /(^|\\D)(\\d+)($|\\D)/.exec(args[1])?.[2] as undefined | `${number}`;\n          result = await this.functions.search(\n            args[0].slice(1, -1), // slice quote \"query\"\n            recency_days && Number(recency_days),\n          );\n          break;\n        case 'open_url':\n          logger.debug(`SimpleBrowser action open_url ${args[0].slice(1, -1)}`);\n          result = await this.functions.open_url(args[0].slice(1, -1));\n          break;\n        case 'mclick':\n          logger.debug(`SimpleBrowser action mclick ${args}`);\n          result = await this.functions.mclick(args.map(x => parseInt(x)));\n          break;\n        default:\n          throw new Error(`Parse Error: ${content}`);\n      }\n\n      return result;\n    } else {\n      throw new Error('Parse Error');\n    }\n  }\n}\n\nif (require.main === module) {\n  (async () => {\n    let browser = new SimpleBrowser();\n    let demo = async (action: string) => {\n      logger.info(` ------ Begin of Action: ${action} ------`);\n      let results = await browser.action(action);\n      for (const [idx, result] of results.entries()) {\n        logger.info(`[Result ${idx}] contentType: ${result.contentType}`);\n        logger.info(`[Result ${idx}] roleMetadata: ${result.roleMetadata}`);\n        logger.info(`[Result ${idx}] result: ${result.result}`);\n        logger.info(`[Result ${idx}] metadata: ${JSON.stringify(result.metadata, null, 2)}`);\n      }\n      logger.info(` ------ End of Action: ${action} ------\\n\\n`);\n    };\n\n    await demo(\"search('Apple Latest News')\");\n    await demo('mclick([0, 1, 5, 6])');\n    await demo('mclick([1, 999999])');\n    await demo(\"open_url('https://chatglm.cn')\");\n    await demo(\"search('zhipu latest News')\");\n    await demo('mclick([0, 1, 5, 6])');\n  })();\n}\n"
  },
  {
    "path": "demo/composite_demo/browser/src/config.ts",
    "content": "export default {\n    LOG_LEVEL: 'debug',\n    BROWSER_TIMEOUT: 10000,\n    BING_SEARCH_API_URL: 'https://api.bing.microsoft.com/v7.0/custom/',\n    BING_SEARCH_API_KEY: 'YOUR_BING_SEARCH_API_KEY',\n    CUSTOM_CONFIG_ID :  'YOUR_CUSTOM_CONFIG_ID', //将您的Custom Configuration ID放在此处\n    HOST: 'localhost',\n    PORT: 3000,\n};\n"
  },
  {
    "path": "demo/composite_demo/browser/src/server.ts",
    "content": "import express, { Express, Request, Response } from 'express';\n\nimport { SimpleBrowser } from './browser';\nimport config from './config';\nimport { logger } from './utils';\n\nconst session_history: Record<string, SimpleBrowser> = {};\n\nconst app: Express = express();\n\napp.use(express.json());\n\napp.post('/', async (req: Request, res: Response) => {\n  const {\n    session_id,\n    action,\n  }: {\n    session_id: string;\n    action: string;\n  } = req.body;\n  logger.info(`session_id: ${session_id}`);\n  logger.info(`action: ${action}`);\n\n  if (!session_history[session_id]) {\n    session_history[session_id] = new SimpleBrowser();\n  }\n\n  const browser = session_history[session_id];\n\n  try {\n    res.json(await browser.action(action));\n  } catch (err) {\n    logger.error(err);\n    res.status(400).json(err);\n  }\n})\n\nprocess.on('SIGINT', () => {\n  process.exit(0);\n});\n\nprocess.on('uncaughtException', e => {\n  logger.error(e);\n});\n\nconst { HOST, PORT } = config;\n\n(async () => {\n  app.listen(PORT, HOST, () => {\n    logger.info(`⚡️[server]: Server is running at http://${HOST}:${PORT}`);\n    try {\n      (<any>process).send('ready');\n    } catch (err) {}\n  });\n})();\n"
  },
  {
    "path": "demo/composite_demo/browser/src/types.ts",
    "content": "export interface File {\n  id: string;\n  name: string;\n  size: number;\n}\n\nexport interface Metadata {\n  files?: File[];\n  reference?: string;\n}\n\nexport interface Message {\n  role: 'user' | 'assistant' | 'system' | 'observation';\n  metadata: string;\n  content: string;\n  request_metadata?: Metadata;\n}\n\nexport interface ToolObservation {\n  contentType: string;\n  result: string;\n  text?: string;\n  roleMetadata?: string; // metadata for <|observation|>${metadata}\n  metadata: any; // metadata for response\n}\n"
  },
  {
    "path": "demo/composite_demo/browser/src/utils.ts",
    "content": "import winston from 'winston';\n\nimport config from './config';\n\nexport class TimeoutError extends Error {}\n\nconst logLevel = config.LOG_LEVEL;\n\nexport const logger = winston.createLogger({\n  level: logLevel,\n  format: winston.format.combine(\n    winston.format.colorize(),\n    winston.format.printf(info => {\n      return `${info.level}: ${info.message}`;\n    }),\n  ),\n  transports: [new winston.transports.Console()],\n});\n\nconsole.log('LOG_LEVEL', logLevel);\n\nexport const parseHrtimeToMillisecond = (hrtime: [number, number]): number => {\n    return (hrtime[0] + hrtime[1] / 1e9) * 1000;\n  };\n\nexport const promiseWithTime = <T>(\n    promise: Promise<T>\n  ): Promise<{\n    value: T;\n    time: number;\n  }> => {\n    return new Promise((resolve, reject) => {\n      const startTime = process.hrtime();\n      promise\n        .then(value => {\n          resolve({\n            value: value,\n            time: parseHrtimeToMillisecond(process.hrtime(startTime))\n          });\n        })\n        .catch(err => reject(err));\n    });\n  };\n\nexport const withTimeout = <T>(\n    millis: number,\n    promise: Promise<T>\n  ): Promise<{\n    value: T;\n    time: number;\n  }> => {\n    const timeout = new Promise<{ value: T; time: number }>((_, reject) =>\n      setTimeout(() => reject(new TimeoutError()), millis)\n    );\n    return Promise.race([promiseWithTime(promise), timeout]);\n  };\n"
  },
  {
    "path": "demo/composite_demo/browser/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2022\",\n    \"lib\": [\"es2022\", \"dom\"],\n    \"module\": \"commonjs\",\n    \"rootDir\": \"./\",\n    \"outDir\": \"./dist\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n  },\n  \"ts-node\": {\n    \"transpileOnly\": true\n  }\n}\n"
  },
  {
    "path": "demo/composite_demo/requirements.txt",
    "content": "# Please install the requirments.txt in inference first!\n\nipykernel>=6.26.0\nipython>=8.18.1\njupyter_client>=8.6.0\nlangchain>=0.2.12\nlangchain-community>=0.2.11\nmatplotlib>=3.9.1\npymupdf>=1.24.9\npython-docx>=1.1.2\npython-pptx>=0.6.23\npyyaml>=6.0.1\nrequests>=2.31.0\nstreamlit>=1.37.1\nzhipuai>=2.1.4\n"
  },
  {
    "path": "demo/composite_demo/src/client.py",
    "content": "\"\"\"\n\nThis is a client part of composite_demo.\nWe provide two clients, HFClient and VLLMClient, which are used to interact with the model.\nThe HFClient is used to interact with the  transformers backend, and the VLLMClient is used to interact with the VLLM model.\n\n\"\"\"\n\nimport json\nfrom collections.abc import Generator\nfrom copy import deepcopy\nfrom enum import Enum, auto\nfrom typing import Protocol\n\nimport streamlit as st\nfrom conversation import Conversation, build_system_prompt\nfrom tools.tool_registry import ALL_TOOLS\n\n\nclass ClientType(Enum):\n    HF = auto()\n    VLLM = auto()\n    API = auto()\n\n\nclass Client(Protocol):\n    def __init__(self, model_path: str): ...\n\n    def generate_stream(\n        self,\n        tools: list[dict],\n        history: list[Conversation],\n        **parameters,\n    ) -> Generator[tuple[str | dict, list[dict]]]: ...\n\n\ndef process_input(history: list[dict], tools: list[dict], role_name_replace: dict = None) -> list[dict]:\n    chat_history = []\n    # if len(tools) > 0:\n    chat_history.append({\"role\": \"system\", \"content\": build_system_prompt(list(ALL_TOOLS), tools)})\n\n    for conversation in history:\n        role = str(conversation.role).removeprefix(\"<|\").removesuffix(\"|>\")\n        if role_name_replace:\n            role = role_name_replace.get(role, role)\n        item = {\n            \"role\": role,\n            \"content\": conversation.content,\n        }\n        if conversation.metadata:\n            item[\"metadata\"] = conversation.metadata\n        # Only append image for user\n        if role == \"user\" and conversation.image:\n            item[\"image\"] = conversation.image\n        chat_history.append(item)\n\n    return chat_history\n\n\ndef process_response(output, history):\n    content = \"\"\n    history = deepcopy(history)\n    for response in output.split(\"<|assistant|>\"):\n        if \"\\n\" in response:\n            metadata, content = response.split(\"\\n\", maxsplit=1)\n        else:\n            metadata, content = \"\", response\n        if not metadata.strip():\n            content = content.strip()\n            history.append({\"role\": \"assistant\", \"metadata\": metadata, \"content\": content})\n            content = content.replace(\"[[训练时间]]\", \"2023年\")\n        else:\n            history.append({\"role\": \"assistant\", \"metadata\": metadata, \"content\": content})\n            if history[0][\"role\"] == \"system\" and \"tools\" in history[0]:\n                parameters = json.loads(content)\n                content = {\"name\": metadata.strip(), \"parameters\": parameters}\n            else:\n                content = {\"name\": metadata.strip(), \"content\": content}\n    return content, history\n\n\n# glm-4v-9b is not available in vLLM backend, use HFClient instead.\n@st.cache_resource(max_entries=1, show_spinner=\"Loading model...\")\ndef get_client(model_path, typ: ClientType) -> Client:\n    match typ:\n        case ClientType.HF:\n            from clients.hf import HFClient\n\n            return HFClient(model_path)\n        case ClientType.VLLM:\n            try:\n                from clients.vllm import VLLMClient\n            except ImportError as e:\n                e.msg += \"; did you forget to install vLLM?\"\n                raise\n            return VLLMClient(model_path)\n        case ClientType.API:\n            from clients.openai import APIClient\n\n            return APIClient(model_path)\n\n    raise NotImplementedError(f\"Client type {typ} is not supported.\")\n"
  },
  {
    "path": "demo/composite_demo/src/clients/hf.py",
    "content": "\"\"\"\nHuggingFace client.\n\"\"\"\n\nfrom collections.abc import Generator\nfrom threading import Thread\n\nimport torch\nfrom client import Client, process_input, process_response\nfrom conversation import Conversation\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n\n\nclass HFClient(Client):\n    def __init__(self, model_path: str):\n        self.tokenizer = AutoTokenizer.from_pretrained(\n            model_path,\n            trust_remote_code=True,\n        )\n        self.model = AutoModelForCausalLM.from_pretrained(\n            model_path,\n            torch_dtype=torch.bfloat16,\n            device_map=\"cuda\",\n        ).eval()\n\n    def generate_stream(\n        self,\n        tools: list[dict],\n        history: list[Conversation],\n        **parameters,\n    ) -> Generator[tuple[str | dict, list[dict]]]:\n        chat_history = process_input(history, tools)\n        model_inputs = self.tokenizer.apply_chat_template(\n            chat_history,\n            add_generation_prompt=True,\n            tokenize=True,\n            return_tensors=\"pt\",\n            return_dict=True,\n        ).to(self.model.device)\n        streamer = TextIteratorStreamer(\n            tokenizer=self.tokenizer,\n            timeout=5,\n            skip_prompt=True,\n        )\n        generate_kwargs = {\n            **model_inputs,\n            \"streamer\": streamer,\n            \"eos_token_id\": [151329, 151336, 151338],\n            \"do_sample\": True,\n        }\n        generate_kwargs.update(parameters)\n        t = Thread(target=self.model.generate, kwargs=generate_kwargs)\n        t.start()\n        total_text = \"\"\n        for token_text in streamer:\n            total_text += token_text\n            yield process_response(total_text, chat_history)\n"
  },
  {
    "path": "demo/composite_demo/src/clients/openai.py",
    "content": "\"\"\"\nOpenAI API client.\n\"\"\"\n\nfrom collections.abc import Generator\n\nfrom client import Client, process_input, process_response\nfrom conversation import Conversation\nfrom openai import OpenAI\n\n\ndef format_openai_tool(origin_tools):\n    openai_tools = []\n    for tool in origin_tools:\n        openai_param = {}\n        for param in tool[\"params\"]:\n            openai_param[param[\"name\"]] = {}\n        openai_tool = {\n            \"type\": \"function\",\n            \"function\": {\n                \"name\": tool[\"name\"],\n                \"description\": tool[\"description\"],\n                \"parameters\": {\n                    \"type\": \"object\",\n                    \"properties\": {\n                        param[\"name\"]: {\"type\": param[\"type\"], \"description\": param[\"description\"]}\n                        for param in tool[\"params\"]\n                    },\n                    \"required\": [param[\"name\"] for param in tool[\"params\"] if param[\"required\"]],\n                },\n            },\n        }\n        openai_tools.append(openai_tool)\n    return openai_tools\n\n\nclass APIClient(Client):\n    def __init__(self, model_path: str):\n        base_url = \"http://127.0.0.1:8000/v1/\"\n        self.client = OpenAI(api_key=\"EMPTY\", base_url=base_url)\n        self.use_stream = False\n        self.role_name_replace = {\"observation\": \"tool\"}\n\n    def generate_stream(\n        self,\n        tools: list[dict],\n        history: list[Conversation],\n        **parameters,\n    ) -> Generator[tuple[str | dict, list[dict]]]:\n        chat_history = process_input(history, \"\", role_name_replace=self.role_name_replace)\n        # messages = process_input(history, '', role_name_replace=self.role_name_replace)\n        openai_tools = format_openai_tool(tools)\n        response = self.client.chat.completions.create(\n            model=\"glm-4\",\n            messages=chat_history,\n            tools=openai_tools,\n            stream=self.use_stream,\n            max_tokens=parameters[\"max_new_tokens\"],\n            temperature=parameters[\"temperature\"],\n            presence_penalty=1.2,\n            top_p=parameters[\"top_p\"],\n            tool_choice=\"auto\",\n        )\n        output = response.choices[0].message\n        if output.tool_calls:\n            glm4_output = output.tool_calls[0].function.name + \"\\n\" + output.tool_calls[0].function.arguments\n        else:\n            glm4_output = output.content\n        yield process_response(glm4_output, chat_history)\n"
  },
  {
    "path": "demo/composite_demo/src/clients/vllm.py",
    "content": "\"\"\"\nvLLM client.\n\nPlease install [vLLM](https://github.com/vllm-project/vllm) according to its\ninstallation guide before running this client.\n\"\"\"\n\nimport time\nfrom collections.abc import Generator\n\nfrom client import Client, process_input, process_response\nfrom conversation import Conversation\nfrom transformers import AutoTokenizer\nfrom vllm import EngineArgs, LLMEngine, SamplingParams\n\n\nclass VLLMClient(Client):\n    def __init__(self, model_path: str):\n        self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)\n        self.engine_args = EngineArgs(\n            model=model_path,\n            tensor_parallel_size=1,\n            dtype=\"bfloat16\",  # torch.bfloat16 is needed.\n            gpu_memory_utilization=0.6,\n            enforce_eager=True,\n            worker_use_ray=False,\n        )\n        self.engine = LLMEngine.from_engine_args(self.engine_args)\n\n    def generate_stream(\n        self, tools: list[dict], history: list[Conversation], **parameters\n    ) -> Generator[tuple[str | dict, list[dict]]]:\n        chat_history = process_input(history, tools)\n        model_inputs = self.tokenizer.apply_chat_template(chat_history, add_generation_prompt=True, tokenize=False)\n        parameters[\"max_tokens\"] = parameters.pop(\"max_new_tokens\")\n        params_dict = {\n            \"n\": 1,\n            \"best_of\": 1,\n            \"top_p\": 1,\n            \"top_k\": -1,\n            \"length_penalty\": 1,\n            \"stop_token_ids\": [151329, 151336, 151338],\n        }\n        params_dict.update(parameters)\n        sampling_params = SamplingParams(**params_dict)\n\n        self.engine.add_request(request_id=str(time.time()), inputs=model_inputs, params=sampling_params)\n        while self.engine.has_unfinished_requests():\n            request_outputs = self.engine.step()\n            for request_output in request_outputs:\n                yield process_response(request_output.outputs[0].text, chat_history)\n"
  },
  {
    "path": "demo/composite_demo/src/conversation.py",
    "content": "import json\nimport re\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom enum import Enum, auto\n\nimport streamlit as st\nfrom PIL.Image import Image\nfrom streamlit.delta_generator import DeltaGenerator\nfrom tools.browser import Quote, quotes\n\n\nQUOTE_REGEX = re.compile(r\"【(\\d+)†(.+?)】\")\n\nSELFCOG_PROMPT = \"你是一个名为 GLM-4 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的，你的任务是针对用户的问题和要求提供适当的答复和支持。\"\nDATE_PROMPT = \"当前日期: %Y-%m-%d\"\nTOOL_SYSTEM_PROMPTS = {\n    \"python\": \"当你向 `python` 发送包含 Python 代码的消息时，该代码将会在一个有状态的 Jupyter notebook 环境中执行。\\n`python` 返回代码执行的输出，或在执行 60 秒后返回超时。\\n`/mnt/data` 将会持久化存储你的文件。在此会话中，`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用，这些在线内容的访问将不会成功。\",\n    \"simple_browser\": \"你可以使用 `simple_browser` 工具。该工具支持以下函数：\\n`search(query: str, recency_days: int)`：使用搜索引擎进行查询并显示结果，可以使用 `recency_days` 参数控制搜索内容的时效性。\\n`mclick(ids: list[int])`：获取一系列指定 id 的页面内容。每次调用时，须选择3-10个页面。选择多个角度的页面，同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的，你也可以多打开一些可能有用的页面而不用担心内容过多。\\n`open_url(url: str)`：打开指定的 URL。\\n\\n使用 `【{引用 id}†{引用文本}】` 来引用内容。\\n\\n操作步骤：1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。\\n 如果用户提供了 URL，也可以用 `open_url` 直接打开页面。\\n如果初次搜索结果没有找到合适的信息，也可以再次使用 `search` 进行搜索。\",\n    \"cogview\": \"如果用户的请求中包含了对图像的描述，你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述，规则：\\n- 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。\\n- 应当尽可能详细地描述图像生成的需求，需求描述约 100 英文单词。\\n- 保持用户原始描述的意图。不要虚构内容或者没见过的人物。\\n- 如无特殊说明，所在地为中国，持有中国立场并遵循中国社会主义价值观。\",\n}\n\nFILE_TEMPLATE = \"[File Name]\\n{file_name}\\n[File Content]\\n{file_content}\"\n\n\ndef build_system_prompt(\n    enabled_tools: list[str],\n    functions: list[dict],\n):\n    value = SELFCOG_PROMPT\n    value += \"\\n\\n\" + datetime.now().strftime(DATE_PROMPT)\n    if enabled_tools or functions:\n        value += \"\\n\\n# 可用工具\"\n    contents = []\n    for tool in enabled_tools:\n        contents.append(f\"\\n\\n## {tool}\\n\\n{TOOL_SYSTEM_PROMPTS[tool]}\")\n    for function in functions:\n        content = f\"\\n\\n## {function['name']}\\n\\n{json.dumps(function, ensure_ascii=False, indent=4)}\"\n        content += \"\\n在调用上述函数时，请使用 Json 格式表示调用的参数。\"\n        contents.append(content)\n    value += \"\".join(contents)\n    return value\n\n\ndef response_to_str(response: str | dict[str, str]) -> str:\n    \"\"\"\n    Convert response to string.\n    \"\"\"\n    if isinstance(response, dict):\n        return response.get(\"name\", \"\") + response.get(\"content\", \"\")\n    return response\n\n\nclass Role(Enum):\n    SYSTEM = auto()\n    USER = auto()\n    ASSISTANT = auto()\n    TOOL = auto()\n    OBSERVATION = auto()\n\n    def __str__(self):\n        match self:\n            case Role.SYSTEM:\n                return \"<|system|>\"\n            case Role.USER:\n                return \"<|user|>\"\n            case Role.ASSISTANT | Role.TOOL:\n                return \"<|assistant|>\"\n            case Role.OBSERVATION:\n                return \"<|observation|>\"\n\n    # Get the message block for the given role\n    def get_message(self):\n        # Compare by value here, because the enum object in the session state\n        # is not the same as the enum cases here, due to streamlit's rerunning\n        # behavior.\n        match self.value:\n            case Role.SYSTEM.value:\n                return\n            case Role.USER.value:\n                return st.chat_message(name=\"user\", avatar=\"user\")\n            case Role.ASSISTANT.value:\n                return st.chat_message(name=\"assistant\", avatar=\"assistant\")\n            case Role.TOOL.value:\n                return st.chat_message(name=\"tool\", avatar=\"assistant\")\n            case Role.OBSERVATION.value:\n                return st.chat_message(name=\"observation\", avatar=\"assistant\")\n            case _:\n                st.error(f\"Unexpected role: {self}\")\n\n\n@dataclass\nclass Conversation:\n    role: Role\n    content: str | dict\n    # Processed content\n    saved_content: str | None = None\n    metadata: str | None = None\n    image: str | Image | None = None\n\n    def __str__(self) -> str:\n        metadata_str = self.metadata if self.metadata else \"\"\n        return f\"{self.role}{metadata_str}\\n{self.content}\"\n\n    # Human readable format\n    def get_text(self) -> str:\n        text = self.saved_content or self.content\n        match self.role.value:\n            case Role.TOOL.value:\n                text = f\"Calling tool `{self.metadata}`:\\n\\n```python\\n{text}\\n```\"\n            case Role.OBSERVATION.value:\n                text = f\"```python\\n{text}\\n```\"\n        return text\n\n    # Display as a markdown block\n    def show(self, placeholder: DeltaGenerator | None = None) -> str:\n        if placeholder:\n            message = placeholder\n        else:\n            message = self.role.get_message()\n\n        if self.image:\n            message.image(self.image, width=512)\n\n        if self.role == Role.OBSERVATION:\n            metadata_str = f\"from {self.metadata}\" if self.metadata else \"\"\n            message = message.expander(f\"Observation {metadata_str}\")\n\n        text = self.get_text()\n        if self.role != Role.USER:\n            show_text = text\n        else:\n            splitted = text.split(\"files uploaded.\\n\")\n            if len(splitted) == 1:\n                show_text = text\n            else:\n                # Show expander for document content\n                doc = splitted[0]\n                show_text = splitted[-1]\n                expander = message.expander(\"File Content\")\n                expander.markdown(doc)\n        message.markdown(show_text)\n\n\ndef postprocess_text(text: str, replace_quote: bool) -> str:\n    text = text.replace(r\"\\(\", \"$\")\n    text = text.replace(r\"\\)\", \"$\")\n    text = text.replace(r\"\\[\", \"$$\")\n    text = text.replace(r\"\\]\", \"$$\")\n    text = text.replace(\"<|assistant|>\", \"\")\n    text = text.replace(\"<|observation|>\", \"\")\n    text = text.replace(\"<|system|>\", \"\")\n    text = text.replace(\"<|user|>\", \"\")\n    text = text.replace(\"<|endoftext|>\", \"\")\n\n    # Replace quotes\n    if replace_quote:\n        for match in QUOTE_REGEX.finditer(text):\n            quote_id = match.group(1)\n            quote = quotes.get(quote_id, Quote(\"未找到引用内容\", \"\"))\n            text = text.replace(match.group(0), f\" (来源：[{quote.title}]({quote.url})) \")\n\n    return text.strip()\n"
  },
  {
    "path": "demo/composite_demo/src/main.py",
    "content": "\"\"\"\n\nThis demo show the All tools and Long Context chat Capabilities of GLM-4.\nPlease follow the Readme.md to run the demo.\n\n\"\"\"\n\nimport os\nimport traceback\nfrom enum import Enum\nfrom io import BytesIO\nfrom uuid import uuid4\n\nimport streamlit as st\nfrom client import Client, ClientType, get_client\nfrom conversation import (\n    FILE_TEMPLATE,\n    Conversation,\n    Role,\n    postprocess_text,\n    response_to_str,\n)\nfrom PIL import Image\nfrom streamlit.delta_generator import DeltaGenerator\nfrom tools.tool_registry import dispatch_tool, get_tools\nfrom utils import extract_docx, extract_pdf, extract_pptx, extract_text\n\n\nCHAT_MODEL_PATH = os.environ.get(\"CHAT_MODEL_PATH\", \"THUDM/glm-4-9b-chat\")\nVLM_MODEL_PATH = os.environ.get(\"VLM_MODEL_PATH\", \"THUDM/glm-4v-9b\")\n\nUSE_VLLM = os.environ.get(\"USE_VLLM\", \"0\") == \"1\"\nUSE_API = os.environ.get(\"USE_API\", \"0\") == \"1\"\n\n\nclass Mode(str, Enum):\n    ALL_TOOLS = \"🛠️ All Tools\"\n    LONG_CTX = \"📝 文档解读\"\n    VLM = \"🖼️ 多模态\"\n\n\ndef append_conversation(\n    conversation: Conversation,\n    history: list[Conversation],\n    placeholder: DeltaGenerator | None = None,\n) -> None:\n    \"\"\"\n    Append a conversation piece into history, meanwhile show it in a new markdown block\n    \"\"\"\n    history.append(conversation)\n    conversation.show(placeholder)\n\n\nst.set_page_config(\n    page_title=\"GLM-4 Demo\",\n    page_icon=\":robot:\",\n    layout=\"centered\",\n    initial_sidebar_state=\"expanded\",\n)\n\nst.title(\"GLM-4 Demo\")\nst.markdown(\n    \"<sub>智谱AI 公开在线技术文档: https://zhipu-ai.feishu.cn/wiki/RuMswanpkiRh3Ok4z5acOABBnjf </sub> \\n\\n <sub> 更多 GLM-4 开源模型的使用方法请参考文档。</sub>\",\n    unsafe_allow_html=True,\n)\n\nwith st.sidebar:\n    top_p = st.slider(\"top_p\", 0.0, 1.0, 0.8, step=0.01)\n    top_k = st.slider(\"top_k\", 1, 20, 10, step=1, key=\"top_k\")\n    temperature = st.slider(\"temperature\", 0.0, 1.5, 0.95, step=0.01)\n    repetition_penalty = st.slider(\"repetition_penalty\", 0.0, 2.0, 1.0, step=0.01)\n    max_new_tokens = st.slider(\"max_new_tokens\", 1, 4096, 2048, step=1)\n    cols = st.columns(2)\n    export_btn = cols[0]\n    clear_history = cols[1].button(\"Clear\", use_container_width=True)\n    retry = export_btn.button(\"Retry\", use_container_width=True)\n\nif clear_history:\n    page = st.session_state.page\n    client = st.session_state.client\n    st.session_state.clear()\n    st.session_state.page = page\n    st.session_state.client = client\n    st.session_state.files_uploaded = False\n    st.session_state.uploaded_texts = \"\"\n    st.session_state.uploaded_file_nums = 0\n    st.session_state.history = []\n\nif \"files_uploaded\" not in st.session_state:\n    st.session_state.files_uploaded = False\n\nif \"session_id\" not in st.session_state:\n    st.session_state.session_id = uuid4()\n\nif \"history\" not in st.session_state:\n    st.session_state.history = []\n\nfirst_round = len(st.session_state.history) == 0\n\n\ndef build_client(mode: Mode) -> Client:\n    match mode:\n        case Mode.ALL_TOOLS:\n            st.session_state.top_k = 10\n            typ = ClientType.VLLM if USE_VLLM else ClientType.HF\n            typ = ClientType.API if USE_API else typ\n            return get_client(CHAT_MODEL_PATH, typ)\n        case Mode.LONG_CTX:\n            st.session_state.top_k = 10\n            typ = ClientType.VLLM if USE_VLLM else ClientType.HF\n            return get_client(CHAT_MODEL_PATH, typ)\n        case Mode.VLM:\n            st.session_state.top_k = 1\n            # vLLM is not available for VLM mode\n            return get_client(VLM_MODEL_PATH, ClientType.HF)\n\n\n# Callback function for page change\ndef page_changed() -> None:\n    global client\n    new_page: str = st.session_state.page\n    st.session_state.history.clear()\n    st.session_state.client = build_client(Mode(new_page))\n\n\npage = st.radio(\n    \"选择功能\",\n    [mode.value for mode in Mode],\n    key=\"page\",\n    horizontal=True,\n    index=None,\n    label_visibility=\"hidden\",\n    on_change=page_changed,\n)\n\nHELP = \"\"\"\n### 🎉 欢迎使用 GLM-4!\n\n请在上方选取一个功能。每次切换功能时，将会重新加载模型并清空对话历史。\n\n文档解读模式与 VLM 模式仅支持在第一轮传入文档或图像。\n\"\"\".strip()\n\nif page is None:\n    st.markdown(HELP)\n    exit()\n\nif page == Mode.LONG_CTX:\n    if first_round:\n        uploaded_files = st.file_uploader(\n            \"上传文件\",\n            type=[\"pdf\", \"txt\", \"py\", \"docx\", \"pptx\", \"json\", \"cpp\", \"md\"],\n            accept_multiple_files=True,\n        )\n        if uploaded_files and not st.session_state.files_uploaded:\n            uploaded_texts = []\n            for uploaded_file in uploaded_files:\n                file_name: str = uploaded_file.name\n                random_file_name = str(uuid4())\n                file_extension = os.path.splitext(file_name)[1]\n                file_path = os.path.join(\"/tmp\", random_file_name + file_extension)\n                with open(file_path, \"wb\") as f:\n                    f.write(uploaded_file.getbuffer())\n                if file_name.endswith(\".pdf\"):\n                    content = extract_pdf(file_path)\n                elif file_name.endswith(\".docx\"):\n                    content = extract_docx(file_path)\n                elif file_name.endswith(\".pptx\"):\n                    content = extract_pptx(file_path)\n                else:\n                    content = extract_text(file_path)\n                uploaded_texts.append(FILE_TEMPLATE.format(file_name=file_name, file_content=content))\n                os.remove(file_path)\n            st.session_state.uploaded_texts = \"\\n\\n\".join(uploaded_texts)\n            st.session_state.uploaded_file_nums = len(uploaded_files)\n        else:\n            st.session_state.uploaded_texts = \"\"\n            st.session_state.uploaded_file_nums = 0\nelif page == Mode.VLM:\n    if first_round:\n        uploaded_image = st.file_uploader(\n            \"上传图片\",\n            type=[\"png\", \"jpg\", \"jpeg\", \"bmp\", \"tiff\", \"webp\"],\n            accept_multiple_files=False,\n        )\n        if uploaded_image:\n            data: bytes = uploaded_image.read()\n            image = Image.open(BytesIO(data)).convert(\"RGB\")\n            st.session_state.uploaded_image = image\n        else:\n            st.session_state.uploaded_image = None\n\nprompt_text = st.chat_input(\"Chat with GLM-4!\", key=\"chat_input\")\n\nif prompt_text == \"\" and retry == False:\n    print(\"\\n== Clean ==\\n\")\n    st.session_state.history = []\n    exit()\n\nhistory: list[Conversation] = st.session_state.history\n\nif retry:\n    print(\"\\n== Retry ==\\n\")\n    last_user_conversation_idx = None\n    for idx, conversation in enumerate(history):\n        if conversation.role.value == Role.USER.value:\n            last_user_conversation_idx = idx\n    if last_user_conversation_idx is not None:\n        prompt_text = history[last_user_conversation_idx].content\n        print(f\"New prompt: {prompt_text}, idx = {last_user_conversation_idx}\")\n        del history[last_user_conversation_idx:]\n\nfor conversation in history:\n    conversation.show()\n\ntools = get_tools() if page == Mode.ALL_TOOLS else []\n\nclient: Client = st.session_state.client\n\n\ndef main(prompt_text: str):\n    global client\n    assert client is not None\n\n    if prompt_text:\n        prompt_text = prompt_text.strip()\n\n        # Append uploaded files\n        uploaded_texts = st.session_state.get(\"uploaded_texts\")\n        if page == Mode.LONG_CTX and uploaded_texts and first_round:\n            meta_msg = \"{} files uploaded.\\n\".format(st.session_state.uploaded_file_nums)\n            prompt_text = uploaded_texts + \"\\n\\n\\n\" + meta_msg + prompt_text\n            # Clear after first use\n            st.session_state.files_uploaded = True\n            st.session_state.uploaded_texts = \"\"\n            st.session_state.uploaded_file_nums = 0\n\n        image = st.session_state.get(\"uploaded_image\")\n        if page == Mode.VLM and image and first_round:\n            st.session_state.uploaded_image = None\n\n        role = Role.USER\n        append_conversation(Conversation(role, prompt_text, image=image), history)\n\n        placeholder = st.container()\n        message_placeholder = placeholder.chat_message(name=\"assistant\", avatar=\"assistant\")\n        markdown_placeholder = message_placeholder.empty()\n\n        def add_new_block():\n            nonlocal message_placeholder, markdown_placeholder\n            message_placeholder = placeholder.chat_message(name=\"assistant\", avatar=\"assistant\")\n            markdown_placeholder = message_placeholder.empty()\n\n        def commit_conversation(\n            role: Role,\n            text: str,\n            metadata: str | None = None,\n            image: str | None = None,\n            new: bool = False,\n        ):\n            processed_text = postprocess_text(text, role.value == Role.ASSISTANT.value)\n            conversation = Conversation(role, text, processed_text, metadata, image)\n\n            # Use different placeholder for new block\n            placeholder = message_placeholder if new else markdown_placeholder\n\n            append_conversation(\n                conversation,\n                history,\n                placeholder,\n            )\n\n        response = \"\"\n        for _ in range(10):\n            last_response = None\n            history_len = None\n\n            try:\n                for response, chat_history in client.generate_stream(\n                    tools=tools,\n                    history=history,\n                    temperature=temperature,\n                    top_p=top_p,\n                    top_k=top_k,\n                    repetition_penalty=repetition_penalty,\n                    max_new_tokens=max_new_tokens,\n                ):\n                    if history_len is None:\n                        history_len = len(chat_history)\n                    elif history_len != len(chat_history):\n                        commit_conversation(Role.ASSISTANT, last_response)\n                        add_new_block()\n                        history_len = len(chat_history)\n                    last_response = response\n                    replace_quote = chat_history[-1][\"role\"] == \"assistant\"\n                    markdown_placeholder.markdown(postprocess_text(str(response) + \"●\", replace_quote=replace_quote))\n                else:\n                    metadata = page == Mode.ALL_TOOLS and isinstance(response, dict) and response.get(\"name\") or None\n                    role = Role.TOOL if metadata else Role.ASSISTANT\n                    text = response.get(\"content\") if metadata else response_to_str(response)\n                    commit_conversation(role, text, metadata)\n                    if metadata:\n                        add_new_block()\n                        try:\n                            with markdown_placeholder:\n                                with st.spinner(f\"Calling tool {metadata}...\"):\n                                    observations = dispatch_tool(metadata, text, str(st.session_state.session_id))\n                        except Exception as e:\n                            traceback.print_exc()\n                            st.error(f'Uncaught exception in `\"{metadata}\"`: {e}')\n                            break\n\n                        for observation in observations:\n                            observation.text = observation.text\n                            commit_conversation(\n                                Role.OBSERVATION,\n                                observation.text,\n                                observation.role_metadata,\n                                observation.image_url,\n                                new=True,\n                            )\n                            add_new_block()\n                        continue\n                    else:\n                        break\n            except Exception:\n                traceback.print_exc()\n                st.error(f\"Uncaught exception: {traceback.format_exc()}\")\n        else:\n            st.error(\"Too many chaining function calls!\")\n\n\nmain(prompt_text)\n"
  },
  {
    "path": "demo/composite_demo/src/tools/browser.py",
    "content": "\"\"\"\nSimple browser tool.\n\n# Usage\n\nPlease start the backend browser server according to the instructions in the README.\n\"\"\"\n\nimport re\nfrom dataclasses import dataclass\nfrom pprint import pprint\n\nimport requests\nimport streamlit as st\n\nfrom .config import BROWSER_SERVER_URL\nfrom .interface import ToolObservation\n\n\nQUOTE_REGEX = re.compile(r\"\\[(\\d+)†(.+?)\\]\")\n\n\n@dataclass\nclass Quote:\n    title: str\n    url: str\n\n\n# Quotes for displaying reference\nif \"quotes\" not in st.session_state:\n    st.session_state.quotes = {}\n\nquotes: dict[str, Quote] = st.session_state.quotes\n\n\ndef map_response(response: dict) -> ToolObservation:\n    # Save quotes for reference\n    print(\"===BROWSER_RESPONSE===\")\n    pprint(response)\n    role_metadata = response.get(\"roleMetadata\")\n    metadata = response.get(\"metadata\")\n\n    if role_metadata.split()[0] == \"quote_result\" and metadata:\n        quote_id = QUOTE_REGEX.search(role_metadata.split()[1]).group(1)\n        quote: dict[str, str] = metadata[\"metadata_list\"][0]\n        quotes[quote_id] = Quote(quote[\"title\"], quote[\"url\"])\n    elif role_metadata == \"browser_result\" and metadata:\n        for i, quote in enumerate(metadata[\"metadata_list\"]):\n            quotes[str(i)] = Quote(quote[\"title\"], quote[\"url\"])\n\n    return ToolObservation(\n        content_type=response.get(\"contentType\"),\n        text=response.get(\"result\"),\n        role_metadata=role_metadata,\n        metadata=metadata,\n    )\n\n\ndef tool_call(code: str, session_id: str) -> list[ToolObservation]:\n    request = {\n        \"session_id\": session_id,\n        \"action\": code,\n    }\n    response = requests.post(BROWSER_SERVER_URL, json=request).json()\n    return list(map(map_response, response))\n"
  },
  {
    "path": "demo/composite_demo/src/tools/cogview.py",
    "content": "import streamlit as st\nfrom zhipuai import ZhipuAI\nfrom zhipuai.types.image import GeneratedImage\n\nfrom .config import COGVIEW_MODEL, ZHIPU_AI_KEY\nfrom .interface import ToolObservation\n\n\n@st.cache_resource\ndef get_zhipu_client():\n    return ZhipuAI(api_key=ZHIPU_AI_KEY)\n\n\ndef map_response(img: GeneratedImage):\n    return ToolObservation(\n        content_type=\"image\",\n        text=\"CogView 已经生成并向用户展示了生成的图片。\",\n        image_url=img.url,\n        role_metadata=\"cogview_result\",\n    )\n\n\ndef tool_call(prompt: str, session_id: str) -> list[ToolObservation]:\n    client = get_zhipu_client()\n    response = client.images.generations(model=COGVIEW_MODEL, prompt=prompt).data\n    return list(map(map_response, response))\n"
  },
  {
    "path": "demo/composite_demo/src/tools/config.py",
    "content": "BROWSER_SERVER_URL = \"http://localhost:3000\"\n\nIPYKERNEL = \"glm-4-demo\"\n\nZHIPU_AI_KEY = \"\"\nCOGVIEW_MODEL = \"cogview-3\"\n"
  },
  {
    "path": "demo/composite_demo/src/tools/interface.py",
    "content": "from dataclasses import dataclass\nfrom typing import Any\n\n\n@dataclass\nclass ToolObservation:\n    content_type: str\n    text: str\n    image_url: str | None = None\n    role_metadata: str | None = None\n    metadata: Any = None\n"
  },
  {
    "path": "demo/composite_demo/src/tools/python.py",
    "content": "import queue\nimport re\nfrom pprint import pprint\nfrom subprocess import PIPE\nfrom typing import Literal\n\nimport jupyter_client\nimport streamlit as st\n\nfrom .config import IPYKERNEL\nfrom .interface import ToolObservation\n\n\nANSI_ESCAPE = re.compile(r\"(\\x9B|\\x1B\\[|\\u001b\\[)[0-?]*[ -/]*[@-~]\")\nCODE = re.compile(r\"```([^\\n]*)\\n(.*?)```\")\n\n\nclass CodeKernel:\n    def __init__(\n        self,\n        kernel_name=\"kernel\",\n        kernel_id=None,\n        kernel_config_path=\"\",\n        python_path=None,\n        ipython_path=None,\n        init_file_path=\"./startup.py\",\n        verbose=1,\n    ):\n        self.kernel_name = kernel_name\n        self.kernel_id = kernel_id\n        self.kernel_config_path = kernel_config_path\n        self.python_path = python_path\n        self.ipython_path = ipython_path\n        self.init_file_path = init_file_path\n        self.verbose = verbose\n\n        if python_path is None and ipython_path is None:\n            env = None\n        else:\n            env = {\"PATH\": self.python_path + \":$PATH\", \"PYTHONPATH\": self.python_path}\n\n        # Initialize the backend kernel\n        self.kernel_manager = jupyter_client.KernelManager(\n            kernel_name=IPYKERNEL, connection_file=self.kernel_config_path, exec_files=[self.init_file_path], env=env\n        )\n        if self.kernel_config_path:\n            self.kernel_manager.load_connection_file()\n            self.kernel_manager.start_kernel(stdout=PIPE, stderr=PIPE)\n            print(\"Backend kernel started with the configuration: {}\".format(self.kernel_config_path))\n        else:\n            self.kernel_manager.start_kernel(stdout=PIPE, stderr=PIPE)\n            print(\"Backend kernel started with the configuration: {}\".format(self.kernel_manager.connection_file))\n\n        if verbose:\n            pprint(self.kernel_manager.get_connection_info())\n\n        # Initialize the code kernel\n        self.kernel = self.kernel_manager.blocking_client()\n        # self.kernel.load_connection_file()\n        self.kernel.start_channels()\n        print(\"Code kernel started.\")\n\n    def execute(self, code):\n        self.kernel.execute(code)\n        try:\n            shell_msg = self.kernel.get_shell_msg(timeout=30)\n            io_msg_content = self.kernel.get_iopub_msg(timeout=30)[\"content\"]\n            while True:\n                msg_out = io_msg_content\n                ### Poll the message\n                try:\n                    io_msg_content = self.kernel.get_iopub_msg(timeout=30)[\"content\"]\n                    if \"execution_state\" in io_msg_content and io_msg_content[\"execution_state\"] == \"idle\":\n                        break\n                except queue.Empty:\n                    break\n\n            return shell_msg, msg_out\n        except Exception as e:\n            print(e)\n            return None\n\n    def execute_interactive(self, code, verbose=False):\n        shell_msg = self.kernel.execute_interactive(code)\n        if shell_msg is queue.Empty:\n            if verbose:\n                print(\"Timeout waiting for shell message.\")\n        self.check_msg(shell_msg, verbose=verbose)\n\n        return shell_msg\n\n    def inspect(self, code, verbose=False):\n        msg_id = self.kernel.inspect(code)\n        shell_msg = self.kernel.get_shell_msg(timeout=30)\n        if shell_msg is queue.Empty:\n            if verbose:\n                print(\"Timeout waiting for shell message.\")\n        self.check_msg(shell_msg, verbose=verbose)\n\n        return shell_msg\n\n    def get_error_msg(self, msg, verbose=False) -> str | None:\n        if msg[\"content\"][\"status\"] == \"error\":\n            try:\n                error_msg = msg[\"content\"][\"traceback\"]\n            except:\n                try:\n                    error_msg = msg[\"content\"][\"traceback\"][-1].strip()\n                except:\n                    error_msg = \"Traceback Error\"\n            if verbose:\n                print(\"Error: \", error_msg)\n            return error_msg\n        return None\n\n    def check_msg(self, msg, verbose=False):\n        status = msg[\"content\"][\"status\"]\n        if status == \"ok\":\n            if verbose:\n                print(\"Execution succeeded.\")\n        elif status == \"error\":\n            for line in msg[\"content\"][\"traceback\"]:\n                if verbose:\n                    print(line)\n\n    def shutdown(self):\n        # Shutdown the backend kernel\n        self.kernel_manager.shutdown_kernel()\n        print(\"Backend kernel shutdown.\")\n        # Shutdown the code kernel\n        self.kernel.shutdown()\n        print(\"Code kernel shutdown.\")\n\n    def restart(self):\n        # Restart the backend kernel\n        self.kernel_manager.restart_kernel()\n        # print(\"Backend kernel restarted.\")\n\n    def interrupt(self):\n        # Interrupt the backend kernel\n        self.kernel_manager.interrupt_kernel()\n        # print(\"Backend kernel interrupted.\")\n\n    def is_alive(self):\n        return self.kernel.is_alive()\n\n\ndef clean_ansi_codes(input_string):\n    return ANSI_ESCAPE.sub(\"\", input_string)\n\n\ndef extract_code(text: str) -> str:\n    matches = CODE.findall(text, re.DOTALL)\n    return matches[-1][1]\n\n\ndef execute(code: str, kernel: CodeKernel) -> tuple[Literal[\"text\", \"image\"] | None, str]:\n    res = \"\"\n    res_type = None\n    code = code.replace(\"<|observation|>\", \"\")\n    code = code.replace(\"<|assistant|>python\", \"\")\n    code = code.replace(\"<|assistant|>\", \"\")\n    code = code.replace(\"<|user|>\", \"\")\n    code = code.replace(\"<|system|>\", \"\")\n    msg, output = kernel.execute(code)\n\n    if msg[\"metadata\"][\"status\"] == \"timeout\":\n        return res_type, \"Timed out\"\n    elif msg[\"metadata\"][\"status\"] == \"error\":\n        return res_type, clean_ansi_codes(\"\\n\".join(kernel.get_error_msg(msg, verbose=True)))\n\n    if \"text\" in output:\n        res_type = \"text\"\n        res = output[\"text\"]\n    elif \"data\" in output:\n        for key in output[\"data\"]:\n            if \"text/plain\" in key:\n                res_type = \"text\"\n                res = output[\"data\"][key]\n            elif \"image/png\" in key:\n                res_type = \"image\"\n                res = output[\"data\"][key]\n                break\n\n    return res_type, res\n\n\n@st.cache_resource\ndef get_kernel() -> CodeKernel:\n    return CodeKernel()\n\n\ndef tool_call(code: str, session_id: str) -> list[ToolObservation]:\n    kernel = get_kernel()\n    res_type, res = execute(code, kernel)\n\n    # Convert base64 to data uri\n    text = \"[Image]\" if res_type == \"image\" else res\n    image = f\"data:image/png;base64,{res}\" if res_type == \"image\" else None\n\n    return [ToolObservation(res_type, text, image)]\n"
  },
  {
    "path": "demo/composite_demo/src/tools/tool_registry.py",
    "content": "\"\"\"\nThis code is the tool registration part. By registering the tool, the model can call the tool.\nThis code provides extended functionality to the model, enabling it to call and interact with a variety of utilities\nthrough defined interfaces.\n\"\"\"\n\nimport copy\nimport inspect\nimport json\nimport subprocess\nimport traceback\nfrom collections.abc import Callable\nfrom types import GenericAlias\nfrom typing import Annotated, get_origin\n\nfrom .browser import tool_call as browser\nfrom .cogview import tool_call as cogview\nfrom .interface import ToolObservation\nfrom .python import tool_call as python\n\n\nALL_TOOLS = {\n    \"simple_browser\": browser,\n    \"python\": python,\n    \"cogview\": cogview,\n}\n\n_TOOL_HOOKS = {}\n_TOOL_DESCRIPTIONS = []\n\n\ndef register_tool(func: Callable):\n    tool_name = func.__name__\n    tool_description = inspect.getdoc(func).strip()\n    python_params = inspect.signature(func).parameters\n    tool_params = []\n    for name, param in python_params.items():\n        annotation = param.annotation\n        if annotation is inspect.Parameter.empty:\n            raise TypeError(f\"Parameter `{name}` missing type annotation\")\n        if get_origin(annotation) != Annotated:\n            raise TypeError(f\"Annotation type for `{name}` must be typing.Annotated\")\n\n        typ, (description, required) = annotation.__origin__, annotation.__metadata__\n        typ: str = str(typ) if isinstance(typ, GenericAlias) else typ.__name__\n        if not isinstance(description, str):\n            raise TypeError(f\"Description for `{name}` must be a string\")\n        if not isinstance(required, bool):\n            raise TypeError(f\"Required for `{name}` must be a bool\")\n\n        tool_params.append(\n            {\n                \"name\": name,\n                \"description\": description,\n                \"type\": typ,\n                \"required\": required,\n            }\n        )\n    tool_def = {\n        \"name\": tool_name,\n        \"description\": tool_description,\n        \"params\": tool_params,\n    }\n    # print(\"[registered tool] \" + pformat(tool_def))\n    _TOOL_HOOKS[tool_name] = func\n    _TOOL_DESCRIPTIONS.append(tool_def)\n\n    return func\n\n\ndef dispatch_tool(tool_name: str, code: str, session_id: str) -> list[ToolObservation]:\n    # Dispatch predefined tools\n    if tool_name in ALL_TOOLS:\n        return ALL_TOOLS[tool_name](code, session_id)\n\n    code = code.strip().rstrip(\"<|observation|>\").strip()\n\n    # Dispatch custom tools\n    try:\n        tool_params = json.loads(code)\n    except json.JSONDecodeError as e:\n        err = f\"Error decoding JSON: {e}\"\n        return [ToolObservation(\"system_error\", err)]\n\n    if tool_name not in _TOOL_HOOKS:\n        err = f\"Tool `{tool_name}` not found. Please use a provided tool.\"\n        return [ToolObservation(\"system_error\", err)]\n\n    tool_hook = _TOOL_HOOKS[tool_name]\n    try:\n        ret: str = tool_hook(**tool_params)\n        return [ToolObservation(tool_name, str(ret))]\n    except:\n        err = traceback.format_exc()\n        return [ToolObservation(\"system_error\", err)]\n\n\ndef get_tools() -> list[dict]:\n    return copy.deepcopy(_TOOL_DESCRIPTIONS)\n\n\n# Tool Definitions\n\n\n@register_tool\ndef random_number_generator(\n    seed: Annotated[int, \"The random seed used by the generator\", True],\n    range: Annotated[tuple[int, int], \"The range of the generated numbers\", True],\n) -> int:\n    \"\"\"\n    Generates a random number x, s.t. range[0] <= x < range[1]\n    \"\"\"\n    if not isinstance(seed, int):\n        raise TypeError(\"Seed must be an integer\")\n    if not isinstance(range, tuple):\n        raise TypeError(\"Range must be a tuple\")\n    if not isinstance(range[0], int) or not isinstance(range[1], int):\n        raise TypeError(\"Range must be a tuple of integers\")\n\n    import random\n\n    return random.Random(seed).randint(*range)\n\n\n@register_tool\ndef get_weather(\n    city_name: Annotated[str, \"The name of the city to be queried\", True],\n) -> str:\n    \"\"\"\n    Get the current weather for `city_name`\n    \"\"\"\n\n    if not isinstance(city_name, str):\n        raise TypeError(\"City name must be a string\")\n\n    key_selection = {\n        \"current_condition\": [\n            \"temp_C\",\n            \"FeelsLikeC\",\n            \"humidity\",\n            \"weatherDesc\",\n            \"observation_time\",\n        ],\n    }\n    import requests\n\n    try:\n        resp = requests.get(f\"https://wttr.in/{city_name}?format=j1\")\n        resp.raise_for_status()\n        resp = resp.json()\n        ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()}\n    except:\n        import traceback\n\n        ret = \"Error encountered while fetching weather data!\\n\" + traceback.format_exc()\n\n    return str(ret)\n\n\n@register_tool\ndef get_shell(\n    query: Annotated[str, \"The command should run in Linux shell\", True],\n) -> str:\n    \"\"\"\n    Use shell to run command\n    \"\"\"\n    if not isinstance(query, str):\n        raise TypeError(\"Command must be a string\")\n    try:\n        result = subprocess.run(\n            query,\n            shell=True,\n            check=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            text=True,\n        )\n        return result.stdout\n    except subprocess.CalledProcessError as e:\n        return e.stderr\n\n\nif __name__ == \"__main__\":\n    # print(dispatch_tool(\"get_shell\", {\"query\": \"pwd\"}))\n    print(get_tools())\n"
  },
  {
    "path": "demo/composite_demo/src/utils.py",
    "content": "import docx\nfrom langchain_community.document_loaders import PyMuPDFLoader\nfrom pptx import Presentation\n\n\ndef extract_text(path):\n    return open(path, \"r\").read()\n\n\ndef extract_pdf(path):\n    loader = PyMuPDFLoader(path)\n    data = loader.load()\n    data = [x.page_content for x in data]\n    content = \"\\n\\n\".join(data)\n    return content\n\n\ndef extract_docx(path):\n    doc = docx.Document(path)\n    data = []\n    for paragraph in doc.paragraphs:\n        data.append(paragraph.text)\n    content = \"\\n\\n\".join(data)\n    return content\n\n\ndef extract_pptx(path):\n    prs = Presentation(path)\n    text = \"\"\n    for slide in prs.slides:\n        for shape in slide.shapes:\n            if hasattr(shape, \"text\"):\n                text += shape.text + \"\\n\"\n    return text\n"
  },
  {
    "path": "demo/intel_device_demo/itrex/README.md",
    "content": "# 使用 Intel® Extension for Transformers 推理 GLM-4-9B-Chat 模型\n\n本示例介绍如何使用 Intel® Extension for Transformers 推理 GLM-4-9B-Chat 模型。\n\n## 设备和依赖检查\n\n### 相关推理测试数据\n\n**本文档的数据均在以下硬件环境测试,实际运行环境需求和运行占用的显存略有不同，请以实际运行环境为准。**\n\n测试硬件信息:\n\n+ OS: Ubuntu 22.04 (本教程一定需要在Linux环境下执行)\n+ Memory: 512GB\n+ Python: 3.10.12\n+ CPU: Intel(R) Xeon(R) Platinum 8358 CPU / 12th Gen Intel i5-12400\n\n## 安装依赖\n\n在开始推理之前，请你先安装`inference`中的依赖，同时您需要安装本目录下的依赖项：\n```shell\npip install -r requirements.txt\n```\n\n## 运行模型推理\n\n```shell\npython itrex_cli_demo.py\n```\n\n如果您是第一次推理，会有一次模型转换权重的过程，转换后的模型权重存放在`runtime_outputs`文件夹下，这大概会消耗`60G`的硬盘空间。\n转换完成后，文件夹下有两个文件：\n+ ne_chatglm2_f32.bin 52G(如果您不使用FP32进行推理，可以删掉这个文件)\n+ ne_chatglm2_q_nf4_bestla_cfp32_sym_sfp32_g32.bin 8.1G\n\n如果您不是第一次推理，则会跳过这个步骤，直接开始对话，推理效果如下：\n```shell\nWelcome to the CLI chat. Type your messages below.\n\nUser: 你好\nAVX:1 AVX2:1 AVX512F:1 AVX512BW:1 AVX_VNNI:0 AVX512_VNNI:1 AMX_INT8:0 AMX_BF16:0 AVX512_BF16:0 AVX512_FP16:0\nbeam_size: 1, do_sample: 1, top_k: 40, top_p: 0.900, continuous_batching: 0, max_request_num: 1, early_stopping: 0, scratch_size_ratio: 1.000\nmodel_file_loader: loading model from runtime_outs/ne_chatglm2_q_nf4_bestla_cfp32_sym_sfp32_g32.bin\nLoading the bin file with NE format...\nload_ne_hparams  0.hparams.n_vocab = 151552\nload_ne_hparams  1.hparams.n_embd = 4096\nload_ne_hparams  2.hparams.n_mult = 0\nload_ne_hparams  3.hparams.n_head = 32\nload_ne_hparams  4.hparams.n_head_kv = 0\nload_ne_hparams  5.hparams.n_layer = 40\nload_ne_hparams  6.hparams.n_rot = 0\nload_ne_hparams  7.hparams.ftype = 0\nload_ne_hparams  8.hparams.max_seq_len = 131072\nload_ne_hparams  9.hparams.alibi_bias_max = 0.000\nload_ne_hparams  10.hparams.clip_qkv = 0.000\nload_ne_hparams  11.hparams.par_res = 0\nload_ne_hparams  12.hparams.word_embed_proj_dim = 0\nload_ne_hparams  13.hparams.do_layer_norm_before = 0\nload_ne_hparams  14.hparams.multi_query_group_num = 2\nload_ne_hparams  15.hparams.ffn_hidden_size = 13696\nload_ne_hparams  16.hparams.inner_hidden_size = 0\nload_ne_hparams  17.hparams.n_experts = 0\nload_ne_hparams  18.hparams.n_experts_used = 0\nload_ne_hparams  19.hparams.n_embd_head_k = 0\nload_ne_hparams  20.hparams.norm_eps = 0.000000\nload_ne_hparams  21.hparams.freq_base = 5000000.000\nload_ne_hparams  22.hparams.freq_scale = 1.000\nload_ne_hparams  23.hparams.rope_scaling_factor = 0.000\nload_ne_hparams  24.hparams.original_max_position_embeddings = 0\nload_ne_hparams  25.hparams.use_yarn = 0\nload_ne_vocab    26.vocab.bos_token_id = 1\nload_ne_vocab    27.vocab.eos_token_id = 151329\nload_ne_vocab    28.vocab.pad_token_id = 151329\nload_ne_vocab    29.vocab.sep_token_id = -1\ninit: hparams.n_vocab         = 151552\ninit: hparams.n_embd          = 4096\ninit: hparams.n_mult          = 0\ninit: hparams.n_head          = 32\ninit: hparams.n_layer         = 40\ninit: hparams.n_rot           = 0\ninit: hparams.ffn_hidden_size = 13696\ninit: n_parts    = 1\nload: ctx size   = 16528.38 MB\nload: layers[0].ffn_fusion    = 1\nload: scratch0   = 4096.00 MB\nload: scratch1   = 2048.00 MB\nload: scratch2   = 4096.00 MB\nload: mem required  = 26768.38 MB (+ memory per state)\n.............................................................................................\nmodel_init_from_file: support_bestla_kv = 1\nkv_cache_init: run_mha_reordered = 1\nmodel_init_from_file: kv self size =  690.00 MB\nAssistant:\n你好👋！我是人工智能助手，很高兴为你服务。有什么可以帮助你的吗？\n```\n"
  },
  {
    "path": "demo/intel_device_demo/itrex/README_en.md",
    "content": "\n# Using Intel® Extension for Transformers to Inference the GLM-4-9B-Chat Model\n\nThis example introduces how to use Intel® Extension for Transformers to inference the GLM-4-9B-Chat model.\n\n## Device and Dependency Check\n\n### Relevant Inference Test Data\n\n**The data in this document is tested on the following hardware environment. The actual running environment requirements and memory usage may vary slightly. Please refer to the actual running environment.**\n\nTest hardware information:\n\n+ OS: Ubuntu 22.04 (This tutorial must be executed in a Linux environment)\n+ Memory: 512GB\n+ Python: 3.10.12\n+ CPU: Intel(R) Xeon(R) Platinum 8358 CPU / 12th Gen Intel i5-12400\n\n## Installing Dependencies\n\nBefore starting the inference, please install the dependencies in `inference`, and you need to install the dependencies in this directory:\n```shell\npip install -r requirements.txt\n```\n\n## Running Model Inference\n\n```shell\npython itrex_cli_demo.py\n```\n\nIf this is your first inference, there will be a process of converting model weights. The converted model weights are stored in the `runtime_outputs` folder, which will consume about `60G` of disk space.\nAfter the conversion is completed, there are two files in the folder:\n+ ne_chatglm2_f32.bin 52G (If you do not use FP32 for inference, you can delete this file)\n+ ne_chatglm2_q_nf4_bestla_cfp32_sym_sfp32_g32.bin 8.1G\n\nIf this is not your first inference, this step will be skipped, and you will directly start the conversation. The inference result is as follows:\n```shell\nWelcome to the CLI chat. Type your messages below.\n\nUser: Hello\nAVX:1 AVX2:1 AVX512F:1 AVX512BW:1 AVX_VNNI:0 AVX512_VNNI:1 AMX_INT8:0 AMX_BF16:0 AVX512_BF16:0 AVX512_FP16:0\nbeam_size: 1, do_sample: 1, top_k: 40, top_p: 0.900, continuous_batching: 0, max_request_num: 1, early_stopping: 0, scratch_size_ratio: 1.000\nmodel_file_loader: loading model from runtime_outs/ne_chatglm2_q_nf4_bestla_cfp32_sym_sfp32_g32.bin\nLoading the bin file with NE format...\nload_ne_hparams  0.hparams.n_vocab = 151552\nload_ne_hparams  1.hparams.n_embd = 4096\nload_ne_hparams  2.hparams.n_mult = 0\nload_ne_hparams  3.hparams.n_head = 32\nload_ne_hparams  4.hparams.n_head_kv = 0\nload_ne_hparams  5.hparams.n_layer = 40\nload_ne_hparams  6.hparams.n_rot = 0\nload_ne_hparams  7.hparams.ftype = 0\nload_ne_hparams  8.hparams.max_seq_len = 131072\nload_ne_hparams  9.hparams.alibi_bias_max = 0.000\nload_ne_hparams  10.hparams.clip_qkv = 0.000\nload_ne_hparams  11.hparams.multi_query_group_num = 2\nload_ne_hparams  12.hparams.ffn_hidden_size = 13696\nload_ne_hparams  13.hparams.inner_hidden_size = 0\nload_ne_hparams  14.hparams.n_experts = 0\nload_ne_hparams  15.hparams.n_experts_used = 0\nload_ne_hparams  16.hparams.n_embd_head_k = 0\nload_ne_hparams  17.hparams.norm_eps = 0.000000\nload_ne_hparams  18.hparams.freq_base = 5000000.000\nload_ne_hparams  19.hparams.freq_scale = 1.000\nload_ne_hparams  20.hparams.rope_scaling_factor = 0.000\nload_ne_hparams  21.hparams.original_max_position_embeddings = 0\nload_ne_hparams  22.hparams.use_yarn = 0\nload_ne_vocab    23.vocab.bos_token_id = 1\nload_ne_vocab    24.vocab.eos_token_id = 151329\nload_ne_vocab    25.vocab.pad_token_id = 151329\nload_ne_vocab    26.vocab.sep_token_id = -1\ninit: hparams.n_vocab         = 151552\ninit: hparams.n_embd          = 4096\ninit: hparams.n_mult          = 0\ninit: hparams.n_head          = 32\ninit: hparams.n_layer         = 40\ninit: hparams.n_rot           = 0\ninit: hparams.ffn_hidden_size = 13696\ninit: n_parts    = 1\nload: ctx size   = 16528.38 MB\nload: layers[0].ffn_fusion    = 1\nload: scratch0   = 4096.00 MB\nload: scratch1   = 2048.00 MB\nload: scratch2   = 4096.00 MB\nload: mem required  = 26768.38 MB (+ memory per state)\n.............................................................................................\nmodel_init_from_file: support_bestla_kv = 1\nkv_cache_init: run_mha_reordered = 1\nmodel_init_from_file: kv self size =  690.00 MB\nAssistant:\nHello👋! I am an AI assistant. How can I help you today?\n```\n"
  },
  {
    "path": "demo/intel_device_demo/itrex/itrex_cli_demo.py",
    "content": "\"\"\"\nThis script creates a CLI demo with transformers backend for the glm-4-9b model with Intel® Extension for Transformers\n\"\"\"\n\nimport os\n\n\nMODEL_PATH = os.environ.get(\"MODEL_PATH\", \"THUDM/GLM-4-9B-0414\")\n\nfrom threading import Thread\n\nimport torch\nfrom intel_extension_for_transformers.transformers import AutoModelForCausalLM\nfrom transformers import AutoTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer\n\n\nclass StopOnTokens(StoppingCriteria):\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        stop_ids = [151329, 151336, 151338]\n        for stop_id in stop_ids:\n            if input_ids[0][-1] == stop_id:\n                return True\n        return False\n\n\ndef initialize_model_and_tokenizer():\n    tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)\n    model = AutoModelForCausalLM.from_pretrained(\n        MODEL_PATH,\n        device_map=\"cpu\",  # Use Intel CPU for inference\n        trust_remote_code=True,\n        load_in_4bit=True,\n    )\n    return tokenizer, model\n\n\ndef get_user_input():\n    return input(\"\\nUser: \")\n\n\ndef main():\n    tokenizer, model = initialize_model_and_tokenizer()\n\n    history = []\n    max_length = 100\n    top_p = 0.9\n    temperature = 0.8\n    stop = StopOnTokens()\n\n    print(\"Welcome to the CLI chat. Type your messages below.\")\n    while True:\n        user_input = get_user_input()\n        if user_input.lower() in [\"exit\", \"quit\"]:\n            break\n        history.append([user_input, \"\"])\n\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"content\": model_msg})\n\n        model_inputs = tokenizer.apply_chat_template(\n            messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\"\n        )\n\n        streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True)\n\n        generate_kwargs = {\n            \"input_ids\": model_inputs,\n            \"streamer\": streamer,\n            \"max_new_tokens\": max_length,\n            \"do_sample\": True,\n            \"top_p\": top_p,\n            \"temperature\": temperature,\n            \"stopping_criteria\": StoppingCriteriaList([stop]),\n            \"repetition_penalty\": 1.2,\n            \"eos_token_id\": model.config.eos_token_id,\n        }\n\n        t = Thread(target=model.generate, kwargs=generate_kwargs)\n        t.start()\n        print(\"Assistant:\", end=\"\", flush=True)\n        for new_token in streamer:\n            if new_token:\n                print(new_token, end=\"\", flush=True)\n                history[-1][1] += new_token\n\n        history[-1][1] = history[-1][1].strip()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "demo/intel_device_demo/itrex/requirements.txt",
    "content": "cmake>=3.29.5.1\nhuggingface-hub>=0.23.4\ngit+https://github.com/intel/neural-speed.git@main#egg=neural-speed\nintel-extension-for-transformers>=1.4.2\n"
  },
  {
    "path": "demo/intel_device_demo/openvino/README.md",
    "content": "# 使用 OpenVINO 部署 GLM-4-9B-Chat 模型\n\nRead this in [English](README_en.md).\n\n[OpenVINO](https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/overview.html)\n是 Intel 为深度学习推理而设计的开源工具包。它可以帮助开发者优化模型，提高推理性能，减少模型的内存占用。\n本示例将展示如何使用 OpenVINO 部署 GLM-4-9B-Chat 模型。\n\n## 1. 环境配置\n\n首先，你需要安装依赖\n\n```bash\npip install -r requirements.txt\n```\n\n## 2. 转换模型\n\n由于需要将Huggingface模型转换为OpenVINO IR模型，因此您需要下载模型并转换。\n\n```\npython3 convert.py --model_id THUDM/glm-4-9b-chat --output {your_path}/glm-4-9b-chat-ov\n```\n\n### 可以选择的参数\n\n* `--model_id` - 模型所在目录的路径（绝对路径）。\n* `--output` - 转换后模型保存的地址。\n* `--precision` - 转换的精度。\n\n\n转换过程如下：\n```\n====Exporting IR=====\nFramework not specified. Using pt to export the model.\nLoading checkpoint shards: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:04<00:00,  2.14it/s]\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nUsing framework PyTorch: 2.3.1+cu121\nMixed-Precision assignment ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 160/160 • 0:01:45 • 0:00:00\nINFO:nncf:Statistics of the bitwidth distribution:\n┍━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┑\n│   Num bits (N) │ % all parameters (layers)   │ % ratio-defining parameters (layers)   │\n┝━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┥\n│              8 │ 31% (76 / 163)              │ 20% (73 / 160)                         │\n├────────────────┼─────────────────────────────┼────────────────────────────────────────┤\n│              4 │ 69% (87 / 163)              │ 80% (87 / 160)                         │\n┕━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┙\nApplying Weight Compression ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 163/163 • 0:03:46 • 0:00:00\nConfiguration saved in glm-4-9b-ov/openvino_config.json\n====Exporting tokenizer=====\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n```\n## 3. 运行 GLM-4-9B-Chat 模型\n\n```\npython3 chat.py --model_path {your_path}/glm-4-9b-chat-ov --max_sequence_length 4096 --device CPU\n```\n\n### 可以选择的参数\n\n* `--model_path` - OpenVINO IR 模型所在目录的路径。\n* `--max_sequence_length` - 输出标记的最大大小。\n* `--device` - 运行推理的设备。\n\n### 参考代码\n\n本代码参考 [OpenVINO 官方示例](https://github.com/OpenVINO-dev-contest/chatglm3.openvino) 进行修改。\n"
  },
  {
    "path": "demo/intel_device_demo/openvino/README_en.md",
    "content": "# Deploy the GLM-4-9B-Chat model using OpenVINO\n\n[OpenVINO](https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/overview.html)\nis an open source toolkit designed by Intel for deep learning inference. It can help developers optimize models, improve inference performance, and reduce model memory usage.\nThis example will show how to deploy the GLM-4-9B-Chat model using OpenVINO.\n\n## 1. Environment configuration\n\nFirst, you need to install the dependencies\n\n```bash\npip install -r requirements.txt\n```\n\n## 2. Convert the model\n\nSince the Huggingface model needs to be converted to an OpenVINO IR model, you need to download the model and convert it.\n\n```\npython3 convert.py --model_id THUDM/glm-4-9b-chat --output {your_path}/glm-4-9b-chat-ov\n```\nThe conversion process is as follows:\n```\n====Exporting IR=====\nFramework not specified. Using pt to export the model.\nLoading checkpoint shards: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:04<00:00,  2.14it/s]\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\nUsing framework PyTorch: 2.3.1+cu121\nMixed-Precision assignment ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 160/160 • 0:01:45 • 0:00:00\nINFO:nncf:Statistics of the bitwidth distribution:\n┍━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┑\n│   Num bits (N) │ % all parameters (layers)   │ % ratio-defining parameters (layers)   │\n┝━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┥\n│              8 │ 31% (76 / 163)              │ 20% (73 / 160)                         │\n├────────────────┼─────────────────────────────┼────────────────────────────────────────┤\n│              4 │ 69% (87 / 163)              │ 80% (87 / 160)                         │\n┕━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┙\nApplying Weight Compression ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 163/163 • 0:03:46 • 0:00:00\nConfiguration saved in glm-4-9b-ov/openvino_config.json\n====Exporting tokenizer=====\nSpecial tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n```\n\n### Optional parameters\n\n* `--model_id` - Path to the directory where the model is located (absolute path).\n\n* `--output` - Path to where the converted model is saved.\n\n* `--precision` - Precision of the conversion.\n\n## 3. Run the GLM-4-9B-Chat model\n\n```\npython3 chat.py --model_path {your_path}glm-4-9b-chat-ov --max_sequence_length 4096 --device CPU\n```\n\n### Optional parameters\n\n* `--model_path` - Path to the directory where the OpenVINO IR model is located.\n\n* `--max_sequence_length` - Maximum size of the output token.\n* `--device` - the device to run inference on.\n\n### Reference code\n\nThis code is modified based on the [OpenVINO official example](https://github.com/OpenVINO-dev-contest/chatglm3.openvino).\n"
  },
  {
    "path": "demo/intel_device_demo/openvino/convert.py",
    "content": "\"\"\"\nThis script is used to convert the original model to OpenVINO IR format.\nThe Origin Code can check https://github.com/OpenVINO-dev-contest/chatglm3.openvino/blob/main/convert.py\n\"\"\"\n\nimport argparse\nimport os\nfrom pathlib import Path\n\nfrom optimum.intel import OVWeightQuantizationConfig\nfrom optimum.intel.openvino import OVModelForCausalLM\nfrom transformers import AutoConfig, AutoTokenizer\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(add_help=False)\n    parser.add_argument(\"-h\", \"--help\", action=\"help\", help=\"Show this help message and exit.\")\n    parser.add_argument(\n        \"-m\", \"--model_id\", default=\"THUDM/GLM-4-9B-0414\", required=False, type=str, help=\"orignal model path\"\n    )\n    parser.add_argument(\n        \"-p\",\n        \"--precision\",\n        required=False,\n        default=\"int4\",\n        type=str,\n        choices=[\"fp16\", \"int8\", \"int4\"],\n        help=\"fp16, int8 or int4\",\n    )\n    parser.add_argument(\n        \"-o\", \"--output\", default=\"./glm-4-9b-ov\", required=False, type=str, help=\"Required. path to save the ir model\"\n    )\n    args = parser.parse_args()\n\n    ir_model_path = Path(args.output)\n    if ir_model_path.exists() == False:\n        os.mkdir(ir_model_path)\n\n    model_kwargs = {\n        \"trust_remote_code\": True,\n        \"config\": AutoConfig.from_pretrained(args.model_id, trust_remote_code=True),\n    }\n    compression_configs = {\n        \"sym\": False,\n        \"group_size\": 128,\n        \"ratio\": 0.8,\n    }\n\n    print(\"====Exporting IR=====\")\n    if args.precision == \"int4\":\n        ov_model = OVModelForCausalLM.from_pretrained(\n            args.model_id,\n            export=True,\n            compile=False,\n            quantization_config=OVWeightQuantizationConfig(bits=4, **compression_configs),\n            **model_kwargs,\n        )\n    elif args.precision == \"int8\":\n        ov_model = OVModelForCausalLM.from_pretrained(\n            args.model_id, export=True, compile=False, load_in_8bit=True, **model_kwargs\n        )\n    else:\n        ov_model = OVModelForCausalLM.from_pretrained(\n            args.model_id, export=True, compile=False, load_in_8bit=False, **model_kwargs\n        )\n\n    ov_model.save_pretrained(ir_model_path)\n\n    print(\"====Exporting tokenizer=====\")\n    tokenizer = AutoTokenizer.from_pretrained(args.model_id, trust_remote_code=True)\n    tokenizer.save_pretrained(ir_model_path)\n"
  },
  {
    "path": "demo/intel_device_demo/openvino/openvino_cli_demo.py",
    "content": "import argparse\nfrom threading import Thread\nfrom typing import List, Tuple\n\nimport torch\nfrom optimum.intel.openvino import OVModelForCausalLM\nfrom transformers import AutoConfig, AutoTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer\n\n\nclass StopOnTokens(StoppingCriteria):\n    def __init__(self, token_ids):\n        self.token_ids = token_ids\n\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        for stop_id in self.token_ids:\n            if input_ids[0][-1] == stop_id:\n                return True\n        return False\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(add_help=False)\n    parser.add_argument(\"-h\", \"--help\", action=\"help\", help=\"Show this help message and exit.\")\n    parser.add_argument(\"-m\", \"--model_path\", required=True, type=str, help=\"Required. model path\")\n    parser.add_argument(\n        \"-l\", \"--max_sequence_length\", default=256, required=False, type=int, help=\"Required. maximun length of output\"\n    )\n    parser.add_argument(\n        \"-d\", \"--device\", default=\"CPU\", required=False, type=str, help=\"Required. device for inference\"\n    )\n    args = parser.parse_args()\n    model_dir = args.model_path\n\n    ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n\n    tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)\n\n    print(\"====Compiling model====\")\n    ov_model = OVModelForCausalLM.from_pretrained(\n        model_dir,\n        device=args.device,\n        ov_config=ov_config,\n        config=AutoConfig.from_pretrained(model_dir, trust_remote_code=True),\n        trust_remote_code=True,\n    )\n\n    streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)\n    stop_tokens = [StopOnTokens([151329, 151336, 151338])]\n\n    def convert_history_to_token(history: List[Tuple[str, str]]):\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"content\": model_msg})\n\n        model_inputs = tokenizer.apply_chat_template(\n            messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\"\n        )\n        return model_inputs\n\n    history = []\n    print(\"====Starting conversation====\")\n    while True:\n        input_text = input(\"用户: \")\n        if input_text.lower() == \"stop\":\n            break\n\n        if input_text.lower() == \"clear\":\n            history = []\n            print(\"AI助手: 对话历史已清空\")\n            continue\n\n        print(\"GLM-4-9B-OpenVINO:\", end=\" \")\n        history = history + [[input_text, \"\"]]\n        model_inputs = convert_history_to_token(history)\n        generate_kwargs = dict(\n            input_ids=model_inputs,\n            max_new_tokens=args.max_sequence_length,\n            temperature=0.1,\n            do_sample=True,\n            top_p=1.0,\n            top_k=50,\n            repetition_penalty=1.1,\n            streamer=streamer,\n            stopping_criteria=StoppingCriteriaList(stop_tokens),\n        )\n\n        t1 = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n        t1.start()\n\n        partial_text = \"\"\n        for new_text in streamer:\n            new_text = new_text\n            print(new_text, end=\"\", flush=True)\n            partial_text += new_text\n        print(\"\\n\")\n        history[-1][1] = partial_text\n"
  },
  {
    "path": "demo/intel_device_demo/openvino/requirements.txt",
    "content": "optimum>=1.20.0\noptimum-intel @ git+https://github.com/huggingface/optimum-intel.git@c1ee8ac0864e25e22ea56b5a37a35451531da0e6\n"
  },
  {
    "path": "finetune/.gitignore",
    "content": "output/\n"
  },
  {
    "path": "finetune/README.md",
    "content": "# GLM-4-9B Chat Fine-tuning\n\n[中文阅读](README_zh.md)\n\n## Hardware Check\n\nAll fine-tuning tests were performed in the following environment:\n\n> OS: Ubuntu 22.04\n>\n> Memory: 512GB\n>\n> Python: 3.12.3\n>\n> CUDA Version: 12.4\n>\n> GPU Driver: 535.104.05\n>\n> GPU: NVIDIA H100 80GB HBM3 (hereafter referred to as GPU)\n\n+ Fine-tuning based on Llama-Factory\n\n| Fine-tuning Model     | Fine-tuning solution | GPU memory usage             |\n|-----------------------|----------------------|------------------------------|\n| GLM-4-9B-0414     | lora                 | 22G (Each GPU, Need 1 GPU)   |\n| GLM-4-9B-0414     | SFT (Zero3 method)   | 55G (Each GPU, Need 4 GPUs)  |\n| GLM-4-9B-0414     | SFT                  | 80G (Each GPU, Need 8 GPUs)  |\n| GLM-4-32B-0414    | SFT (Zero3 method)   | 80G (Each GPU, Need 16 GPUs) |\n\n+ Fine-tuning based on this repository\n\n| Fine-tuning Model        | Fine-tuning solution               | GPU memory usage              |\n|--------------------------|------------------------------------|-------------------------------|\n| GLM-4V-9B                | lora (PEFT), Include EVA2CLIPModel | 75G (Each GPU, Need 1 GPU)    |\n| GLM-4-9B-Chat            | lora (PEFT)                        | 22G (Each GPU, Need 1 GPU)    |\n| GLM-4-9B-Chat            | SFT (Zero3 method)                 | 80G (Each GPU, Need 8 GPUs)   |\n\n\n## Preparation\n\nBefore starting fine-tuning, please install the dependencies in `inference`, ensure you have cloned the latest version of the model repository, and install the dependencies in this directory:\n\n```bash\npip install -r requirements.txt\n```\n\n## Multi-round dialogue format\n\nThe multi-round dialogue fine-tuning example uses the GLM-4 dialogue format convention, adding different `loss_mask` to\ndifferent roles to calculate `loss` for multiple rounds of replies in one calculation.\n\nFor data files, the sample uses the following format:\n\n```json\n[\n  {\n    \"messages\": [\n      {\n        \"role\": \"system\",\n        \"content\": \"<system prompt text>\",\n        \"tools\": [\n          {\n            \"name\": \"<tool name>\",\n            \"args\": {\n              \"<arg name>\": \"<arg value>\"\n            }\n          }\n          // Add more tools if needed\n        ]\n      },\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      },\n      // If Tool Using\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      },\n      {\n        \"role\": \"observation\",\n        \"content\": \"<observation prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response observation>\"\n      },\n      // Multi_turns\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      }\n    ]\n  }\n]\n```\n\nThis is a sample without tools:\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"类型#裤*材质#牛仔布*风格#性感\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"3x1的这款牛仔裤采用浅白的牛仔面料为裤身材质，其柔然的手感和细腻的质地，在穿着舒适的同时，透露着清纯甜美的个性气质。除此之外，流畅的裤身剪裁将性感的腿部曲线彰显的淋漓尽致，不失为一款随性出街的必备单品。\"\n    }\n  ]\n}\n```\n\nThis is a sample with tools:\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"\",\n      \"tools\": [\n        {\n          \"type\": \"function\",\n          \"function\": {\n            \"name\": \"get_recommended_books\",\n            \"description\": \"Get recommended books based on user's interests\",\n            \"parameters\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"interests\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"type\": \"string\"\n                  },\n                  \"description\": \"The interests to recommend books for\"\n                }\n              },\n              \"required\": [\n                \"interests\"\n              ]\n            }\n          }\n        }\n      ]\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"Hi, I am looking for some book recommendations. I am interested in history and science fiction.\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"{\\\"name\\\": \\\"get_recommended_books\\\", \\\"arguments\\\": {\\\"interests\\\": [\\\"history\\\", \\\"science fiction\\\"]}}\"\n    },\n    {\n      \"role\": \"observation\",\n      \"content\": \"{\\\"books\\\": [\\\"Sapiens: A Brief History of Humankind by Yuval Noah Harari\\\", \\\"A Brief History of Time by Stephen Hawking\\\", \\\"Dune by Frank Herbert\\\", \\\"The Martian by Andy Weir\\\"]}\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"Based on your interests in history and science fiction, I would recommend the following books: \\\"Sapiens: A Brief History of Humankind\\\" by Yuval Noah Harari, \\\"A Brief History of Time\\\" by Stephen Hawking, \\\"Dune\\\" by Frank Herbert, and \\\"The Martian\\\" by Andy Weir.\"\n    }\n  ]\n}\n```\n\nThis is a sample with VQA Task:\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"图片中的动物是什么？\",\n      \"image\": \"/root/images/0001.jpg\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"图片中有一只猫。\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"图片中的猫在做什么？\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"这只猫坐在或站在桌子上，桌上有很多食物。\"\n    }\n  ]\n}\n```\n\n- The `system` role is optional, but if it exists, it must appear before the `user` role, and the `system` role can only\n  appear once in a complete conversation (whether it is a single round or a multi-round conversation).\n- The `tools` field is optional, but if it exists, it must appear after the `system` role, and the `tools` field can\n  only appear once in a complete conversation (whether it is a single round or a multi-round conversation). When\n  the `tools` field exists, the `system` role must exist and the `content` field is empty.\n- `GLM-4V-9B` does not support the `tools` field and the `system` field. And `image` must be placed in the first\n  message. The `image` field needs to contain the `absolute path` of the image.\n\n## Configuration file\n\nThe fine-tuning configuration file is located in the `config` directory, including the following files:\n\n1. `ds_zereo_2 / ds_zereo_3.json`: deepspeed configuration file.\n\n2. `lora.yaml / ptuning_v2\n3. .yaml / sft.yaml`: Configuration files for different modes of models, including model parameters, optimizer\n   parameters, training parameters, etc. Some important parameters are explained as follows: + data_config section\n\n+ train_file: File path of training dataset.\n+ val_file: File path of validation dataset.\n+ test_file: File path of test dataset.\n+ num_proc: Number of processes to use when loading data.\n+ max_input_length: Maximum length of input sequence.\n+ max_output_length: Maximum length of output sequence.\n+ training_args section\n+ output_dir: Directory for saving model and other outputs.\n+ max_steps: Maximum number of training steps.\n+ per_device_train_batch_size: Training batch size per device (such as GPU).\n+ dataloader_num_workers: Number of worker threads to use when loading data.\n+ remove_unused_columns: Whether to remove unused columns in data.\n+ save_strategy: Model saving strategy (for example, how many steps to save).\n+ save_steps: How many steps to save the model.\n+ log_level: Log level (such as info).\n+ logging_strategy: logging strategy.\n+ logging_steps: how many steps to log at.\n+ per_device_eval_batch_size: per-device evaluation batch size.\n+ evaluation_strategy: evaluation strategy (e.g. how many steps to evaluate at).\n+ eval_steps: how many steps to evaluate at.\n+ predict_with_generate: whether to use generation mode for prediction.\n+ generation_config section\n+ max_new_tokens: maximum number of new tokens to generate.\n+ peft_config section\n+ peft_type: type of parameter tuning to use (supports LORA and PREFIX_TUNING).\n+ task_type: task type, here is causal language model (don't change).\n+ Lora parameters:\n+ r: rank of LoRA.\n+ lora_alpha: scaling factor of LoRA.\n+ lora_dropout: dropout probability to use in LoRA layer.\n+ P-TuningV2 parameters: + num_virtual_tokens: the number of virtual tokens.\n+ num_attention_heads: 2: the number of attention heads of P-TuningV2 (do not change).\n+ token_dim: 256: the token dimension of P-TuningV2 (do not change).\n\n## Start fine-tuning\n\nExecute **single machine multi-card/multi-machine multi-card** run through the following code, which uses `deepspeed` as\nthe acceleration solution, and you need to install `deepspeed`.\n\n```shell\nOMP_NUM_THREADS=1 torchrun --standalone --nnodes=1 --nproc_per_node=8  finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9b-0414  configs/lora.yaml # For Chat Fine-tune\nOMP_NUM_THREADS=1 torchrun --standalone --nnodes=1 --nproc_per_node=8  finetune_vision.py  data/CogVLM-311K/  THUDM/glm-4v-9b  configs/lora.yaml  # For VQA Fine-tune\n```\n\nExecute **single machine single card** run through the following code.\n\n```shell\npython finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml # For Chat Fine-tune\npython finetune_vision.py  data/CogVLM-311K/  THUDM/glm-4v-9b configs/lora.yaml # For VQA Fine-tune\n```\n\n## Log Visualization Support\n\nThe fine-tuning code supports using SwanLab to visualize and track training metrics. You can enable tracking by installing SwanLab:\n\n```shell\npip install swanlab\n```\n\nYou can visit the [SwanLab Visualization Dashboard](https://swanlab.cn/@ShaohonChen/GLM4-Finetune) to view the training logs of example fine-tuning scripts.\n\nIf prompted to log in, you can obtain an API Key by visiting [https://swanlab.cn/space/~/settings](https://swanlab.cn/space/~/settings).\n\nIf you only want to use the local dashboard, set `swanlab: local` in the configuration parameters and use the `swanlab watch` command to start the offline dashboard.\n\n## Fine-tune from a saved point\n\nIf you train as described above, each fine-tuning will start from the beginning. If you want to fine-tune from a\nhalf-trained model, you can add a fourth parameter, which can be passed in two ways:\n\n1. `yes`, automatically start training from the last saved Checkpoint\n\n2. `XX`, breakpoint number, for example `600`, start training from Checkpoint 600\n\nFor example, this is an example code to continue fine-tuning from the last saved point\n\n```shell\npython finetune.py data/AdvertiseGen/ THUDM/GLM-4-9B-0414 configs/lora.yaml yes\n```\n\n## Use the fine-tuned model\n\n### Use the fine-tuned model in other demos in this repository or external repositories\n\nYou can use our `LORA` and fully fine-tuned models in any demo. This requires you to modify the code yourself according\nto the following tutorial.\n\n1. Replace the way to read the model in the demo with the way to read the model in `finetune_demo/inference.py`.\n\n> Please note that for LORA and P-TuningV2, we did not merge the trained models, but recorded the fine-tuned path\n> in `adapter_config.json`\n> If the location of your original model changes, you should modify the path of `base_model_name_or_path`\n> in `adapter_config.json`.\n\n```python\ndef load_model_and_tokenizer(model_dir: Union[str, Path]) -> tuple[ModelType, TokenizerType]:\n    model_dir = _resolve_path(model_dir)\n    if (model_dir / \"adapter_config.json\").exists():\n        model = AutoPeftModelForCausalLM.from_pretrained(model_dir, device_map=\"auto\")\n        tokenizer_dir = model.peft_config[\"default\"].base_model_name_or_path\n    else:\n        model = AutoModelForCausalLM.from_pretrained(model_dir, device_map=\"auto\")\n        tokenizer_dir = model_dir\n    tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir)\n    return model, tokenizer\n```\n\n2. Read the fine-tuned model. Please note that you should use the location of the fine-tuned model. For example, if your\n   model location is `/path/to/finetune_adapter_model`\n   and the original model address is `path/to/base_model`, you should use `/path/to/finetune_adapter_model`\n   as `model_dir`.\n3. After completing the above operations, you can use the fine-tuned model normally. Other calling methods remain\n   unchanged.\n4. This fine-tuning script has not been tested on long texts of 128K or 1M tokens. Fine-tuning long texts requires GPU\n   devices with larger memory and more efficient fine-tuning solutions, which developers need to handle on their own.\n\n## Reference\n\n```\n@inproceedings{liu2022p,\ntitle={P-tuning: Prompt tuning can be comparable to fine-tuning across scales and tasks},\nauthor={Liu, Xiao and Ji, Kaixuan and Fu, Yicheng and Tam, Weng and Du, Zhengxiao and Yang, Zhilin and Tang, Jie},\nbooktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short\nPapers)},\npages={61--68},\nyear={2022}\n}\n\n@misc{tang2023toolalpaca,\ntitle={ToolAlpaca: Generalized Tool Learning for Language Models with 3000 Simulated Cases},\nauthor={Qiaoyu Tang and Ziliang Deng and Hongyu Lin and Xianpei Han and Qiao Liang and Le Sun},\nyear={2023},\neprint={2306.05301},\narchivePrefix={arXiv},\nprimaryClass={cs.CL}\n}\n```\n"
  },
  {
    "path": "finetune/README_zh.md",
    "content": "# GLM-4-9B Chat 对话模型微调\n\nRead this in [English](README)\n\n## 硬件检查\n\n所有微调测试均在以下环境和硬件下测试:\n\n> OS: Ubuntu 22.04\n>\n> Memory: 512GB\n>\n> Python: 3.12.3\n>\n> CUDA Version: 12.4\n>\n> GPU Driver: 535.104.05\n>\n> GPU: NVIDIA H100 80GB HBM3 (以下简称 GPU)\n\n\n+ 基于 Llama-Factory 进行微调\n\n| Fine-tuning Model     | Fine-tuning solution | GPU memory usage             |\n|-----------------------|----------------------|------------------------------|\n| GLM-4-9B-0414     | lora                 | 22G (Each GPU, Need 1 GPU)   |\n| GLM-4-9B-0414     | SFT (Zero3 method)   | 55G (Each GPU, Need 4 GPUs)  |\n| GLM-4-9B-0414     | lora                 | 80G (Each GPU, Need 8 GPUs)  |\n| GLM-4-32B-0414    | SFT (Zero3 method)   | 80G (Each GPU, Need 16 GPUs) |\n\n+ 基于本仓库代码微调\n\n| Fine-tuning Model        | Fine-tuning solution               | GPU memory usage              |\n|--------------------------|------------------------------------|-------------------------------|\n| GLM-4V-9B                | lora (PEFT), Include EVA2CLIPModel | 75G (Each GPU, Need 1 GPU)    |\n| GLM-4-9B-Chat            | lora (PEFT)                        | 22G (Each GPU, Need 1 GPU)    |\n| GLM-4-9B-Chat            | SFT (Zero3 method)                 | 80G (Each GPU, Need 8 GPUs)   |\n\n\n## 准备工作\n\n在开始微调之前，请你先安装 `inference` 中的依赖，并保证克隆了最新版本的模型仓库，同时您需要安装本目录下的依赖项：\n\n```bash\npip install -r requirements.txt\n```\n\n## 多轮对话格式\n\n多轮对话微调示例采用 GLM-4 对话格式约定，对不同角色添加不同 `loss_mask` 从而在一遍计算中为多轮回复计算 `loss`。\n\n对于数据文件，样例采用如下格式\n\n如果您仅希望微调模型的对话能力，而非工具能力，您应该按照以下格式整理数据。\n\n```json\n[\n  {\n    \"messages\": [\n      {\n        \"role\": \"system\",\n        \"content\": \"<system prompt text>\",\n        \"tools\": [\n          {\n            \"name\": \"<tool name>\",\n            \"args\": {\n              \"<arg name>\": \"<arg value>\"\n            }\n          }\n          // Add more tools if needed\n        ]\n      },\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      },\n      // If Tool Using\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      },\n      {\n        \"role\": \"observation\",\n        \"content\": \"<observation prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response observation>\"\n      },\n      // Multi_turns\n      {\n        \"role\": \"user\",\n        \"content\": \"<user prompt text>\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"content\": \"<assistant response text>\"\n      }\n    ]\n  }\n]\n```\n\n这里是一个不带有工具的例子:\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"类型#裤*材质#牛仔布*风格#性感\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"3x1的这款牛仔裤采用浅白的牛仔面料为裤身材质，其柔然的手感和细腻的质地，在穿着舒适的同时，透露着清纯甜美的个性气质。除此之外，流畅的裤身剪裁将性感的腿部曲线彰显的淋漓尽致，不失为一款随性出街的必备单品。\"\n    }\n  ]\n}\n```\n\n这是一个带有工具调用的例子:\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"\",\n      \"tools\": [\n        {\n          \"type\": \"function\",\n          \"function\": {\n            \"name\": \"get_recommended_books\",\n            \"description\": \"Get recommended books based on user's interests\",\n            \"parameters\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"interests\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"type\": \"string\"\n                  },\n                  \"description\": \"The interests to recommend books for\"\n                }\n              },\n              \"required\": [\n                \"interests\"\n              ]\n            }\n          }\n        }\n      ]\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"Hi, I am looking for some book recommendations. I am interested in history and science fiction.\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"{\\\"name\\\": \\\"get_recommended_books\\\", \\\"arguments\\\": {\\\"interests\\\": [\\\"history\\\", \\\"science fiction\\\"]}}\"\n    },\n    {\n      \"role\": \"observation\",\n      \"content\": \"{\\\"books\\\": [\\\"Sapiens: A Brief History of Humankind by Yuval Noah Harari\\\", \\\"A Brief History of Time by Stephen Hawking\\\", \\\"Dune by Frank Herbert\\\", \\\"The Martian by Andy Weir\\\"]}\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"Based on your interests in history and science fiction, I would recommend the following books: \\\"Sapiens: A Brief History of Humankind\\\" by Yuval Noah Harari, \\\"A Brief History of Time\\\" by Stephen Hawking, \\\"Dune\\\" by Frank Herbert, and \\\"The Martian\\\" by Andy Weir.\"\n    }\n  ]\n}\n```\n\n这是一个视觉VQA微调的例子：\n\n```json\n{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"图片中的动物是什么？\",\n      \"image\": \"/root/images/0001.jpg\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"图片中有一只猫。\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"图片中的猫在做什么？\"\n    },\n    {\n      \"role\": \"assistant\",\n      \"content\": \"这只猫坐在或站在桌子上，桌上有很多食物。\"\n    }\n  ]\n}\n```\n\n- `system` 角色为可选角色，但若存在 `system` 角色，其必须出现在 `user`\n  角色之前，且一个完整的对话数据（无论单轮或者多轮对话）只能出现一次 `system` 角色。\n- `tools` 字段为可选字段，若存在 `tools` 字段，其必须出现在 `system`\n  角色之后，且一个完整的对话数据（无论单轮或者多轮对话）只能出现一次 `tools` 字段。当 `tools` 字段存在时，`system`\n  角色必须存在并且 `content` 字段为空。\n- `GLM-4V-9B` 不支持 `tools` 字段和 `system` 字段。并且 `image` 必须放在第一条消息中。 `image`\n  字段需要放置置图片的 `绝对路径`。\n\n## 配置文件\n\n微调配置文件位于 `config` 目录下，包括以下文件：\n\n1. `ds_zereo_2 / ds_zereo_3.json`: deepspeed 配置文件。\n2. `lora.yaml\n3. .yaml / sft.yaml`: 模型不同方式的配置文件，包括模型参数、优化器参数、训练参数等。 部分重要参数解释如下：\n    + data_config 部分\n        + train_file: 训练数据集的文件路径。\n        + val_file: 验证数据集的文件路径。\n        + test_file: 测试数据集的文件路径。\n        + num_proc: 在加载数据时使用的进程数量。\n    + max_input_length: 输入序列的最大长度。\n    + max_output_length: 输出序列的最大长度。\n    + training_args 部分\n        + output_dir: 用于保存模型和其他输出的目录。\n        + max_steps: 训练的最大步数。\n        + per_device_train_batch_size: 每个设备（如 GPU）的训练批次大小。\n        + dataloader_num_workers: 加载数据时使用的工作线程数量。\n        + remove_unused_columns: 是否移除数据中未使用的列。\n        + save_strategy: 模型保存策略（例如，每隔多少步保存一次）。\n        + save_steps: 每隔多少步保存一次模型。\n        + log_level: 日志级别（如 info）。\n        + logging_strategy: 日志记录策略。\n        + logging_steps: 每隔多少步记录一次日志。\n        + per_device_eval_batch_size: 每个设备的评估批次大小。\n        + evaluation_strategy: 评估策略（例如，每隔多少步进行一次评估）。\n        + eval_steps: 每隔多少步进行一次评估。\n        + predict_with_generate: 是否使用生成模式进行预测。\n    + generation_config 部分\n        + max_new_tokens: 生成的最大新 token 数量。\n    + peft_config 部分\n        + peft_type: 使用的参数有效调整类型 (支持 LORA 和 PREFIX_TUNING)。\n        + task_type: 任务类型，这里是因果语言模型 (不要改动)。\n    + Lora 参数：\n        + r: LoRA 的秩。\n        + lora_alpha: LoRA 的缩放因子。\n        + lora_dropout: 在 LoRA 层使用的 dropout 概率。\n    + P-TuningV2 参数：\n        + num_virtual_tokens: 虚拟 token 的数量。\n        + num_attention_heads: 2: P-TuningV2 的注意力头数(不要改动)。\n        + token_dim: 256: P-TuningV2 的 token 维度(不要改动)。\n\n## 开始微调\n\n通过以下代码执行 **单机多卡/多机多卡** 运行，这是使用 `deepspeed` 作为加速方案的，您需要安装 `deepspeed`。接着，按照此命令运行：\n\n```shell\nOMP_NUM_THREADS=1 torchrun --standalone --nnodes=1 --nproc_per_node=8  finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml # For Chat Fine-tune\nOMP_NUM_THREADS=1 torchrun --standalone --nnodes=1 --nproc_per_node=8  finetune_vision.py  data/CogVLM-311K/  THUDM/glm-4v-9b  configs/lora.yaml  # For VQA Fine-tune\n```\n\n通过以下代码执行 **单机单卡** 运行。\n\n```shell\npython finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml # For Chat Fine-tune\npython finetune_vision.py  data/CogVLM-311K/  THUDM/glm-4v-9b configs/lora.yaml # For VQA Fine-tune\n```\n\n## 日志可视化支持\n\n微调代码支持使用SwanLab对训练指标进行可视化跟踪。可通过安装SwanLab开启跟踪：\n\n```shell\npip install swanlab\n```\n\n可以访问[SwanLab可视化看板](https://swanlab.cn/@ShaohonChen/GLM4-Finetune)获得案例微调脚本的训练日志。\n\n如果提示登录，可以通过访问[https://swanlab.cn/space/~/settings](https://swanlab.cn/space/~/settings)获取API Key。\n\n如果仅使用本地看板，可在配置参数中设置`swanlab: local`。并使用`swanlab watch`命令开启离线看板。\n\n## 从保存点进行微调\n\n如果按照上述方式进行训练，每次微调都会从头开始，如果你想从训练一半的模型开始微调，你可以加入第四个参数，这个参数有两种传入方式:\n\n1. `yes`, 自动从最后一个保存的 Checkpoint开始训练\n2. `XX`, 断点号数字 例 `600` 则从序号600 Checkpoint开始训练\n\n例如，这就是一个从最后一个保存点继续微调的示例代码\n\n```shell\npython finetune.py  data/AdvertiseGen/  THUDM/GLM-4-9B-0414  configs/lora.yaml yes\n```\n\n## 使用微调后的模型\n\n您可以在任何一个 demo 内使用我们的 `LORA` 和 全参微调的模型。这需要你自己按照以下教程进行修改代码。\n\n1. 使用`finetune_demo/inference.py`中读入模型的方式替换 demo 中读入模型的方式。\n\n> 请注意，对于 LORA 和 P-TuningV2 我们没有合并训练后的模型，而是在`adapter_config.json`\n> 中记录了微调型的路径，如果你的原始模型位置发生更改，则你应该修改`adapter_config.json`中`base_model_name_or_path`的路径。\n\n```python\ndef load_model_and_tokenizer(model_dir: Union[str, Path]) -> tuple[ModelType, TokenizerType]:\n    model_dir = _resolve_path(model_dir)\n    if (model_dir / \"adapter_config.json\").exists():\n        model = AutoPeftModelForCausalLM.from_pretrained(model_dir, device_map=\"auto\")\n        tokenizer_dir = model.peft_config[\"default\"].base_model_name_or_path\n    else:\n        model = AutoModelForCausalLM.from_pretrained(model_dir, device_map=\"auto\")\n        tokenizer_dir = model_dir\n    tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir)\n    return model, tokenizer\n```\n\n2. 读取微调的模型，请注意，你应该使用微调模型的位置，例如，若你的模型位置为`/path/to/finetune_adapter_model`\n   ，原始模型地址为`path/to/base_model`,则你应该使用`/path/to/finetune_adapter_model`作为`model_dir`。\n3. 完成上述操作后，就能正常使用微调的模型了，其他的调用方式没有变化。\n4. 本微调脚本没有测试过128K 1M等长文本的微调，长文本的微调需要更大显存的GPU设备，并且需要更高效的微调方案,需要开发者自行解决。\n\n## 参考文献\n\n```\n@inproceedings{liu2022p,\ntitle={P-tuning: Prompt tuning can be comparable to fine-tuning across scales and tasks},\nauthor={Liu, Xiao and Ji, Kaixuan and Fu, Yicheng and Tam, Weng and Du, Zhengxiao and Yang, Zhilin and Tang, Jie},\nbooktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short\nPapers)},\npages={61--68},\nyear={2022}\n}\n\n@misc{tang2023toolalpaca,\ntitle={ToolAlpaca: Generalized Tool Learning for Language Models with 3000 Simulated Cases},\nauthor={Qiaoyu Tang and Ziliang Deng and Hongyu Lin and Xianpei Han and Qiao Liang and Le Sun},\nyear={2023},\neprint={2306.05301},\narchivePrefix={arXiv},\nprimaryClass={cs.CL}\n}\n```\n"
  },
  {
    "path": "finetune/configs/ds_zero_2.json",
    "content": "{\n    \"fp16\": {\n        \"enabled\": \"auto\",\n        \"loss_scale\": 0,\n        \"loss_scale_window\": 1000,\n        \"initial_scale_power\": 16,\n        \"hysteresis\": 2,\n        \"min_loss_scale\": 1\n    },\n    \"bf16\": {\n        \"enabled\": \"auto\"\n    },\n    \"zero_optimization\": {\n        \"stage\": 2,\n        \"allgather_partitions\": true,\n        \"allgather_bucket_size\": 5e8,\n        \"overlap_comm\": true,\n        \"reduce_scatter\": true,\n        \"reduce_bucket_size\": 5e8,\n        \"contiguous_gradients\": true\n    },\n\n    \"gradient_accumulation_steps\": \"auto\",\n    \"gradient_clipping\": \"auto\",\n    \"steps_per_print\": 2000,\n    \"train_batch_size\": \"auto\",\n    \"train_micro_batch_size_per_gpu\": \"auto\",\n    \"wall_clock_breakdown\": false\n}\n"
  },
  {
    "path": "finetune/configs/ds_zero_3.json",
    "content": "{\n  \"train_micro_batch_size_per_gpu\": \"auto\",\n  \"zero_allow_untested_optimizer\": true,\n  \"bf16\": {\n    \"enabled\": \"auto\"\n  },\n  \"optimizer\": {\n    \"type\": \"AdamW\",\n    \"params\": {\n      \"lr\": \"auto\",\n      \"betas\": \"auto\",\n      \"eps\": \"auto\",\n      \"weight_decay\": \"auto\"\n    }\n  },\n  \"zero_optimization\": {\n    \"stage\": 3,\n    \"allgather_partitions\": true,\n    \"allgather_bucket_size\": 5e8,\n    \"reduce_scatter\": true,\n    \"contiguous_gradients\": true,\n    \"overlap_comm\": true,\n    \"sub_group_size\": 1e9,\n    \"reduce_bucket_size\": \"auto\",\n    \"stage3_prefetch_bucket_size\": \"auto\",\n    \"stage3_param_persistence_threshold\": \"auto\",\n    \"stage3_max_live_parameters\": 1e9,\n    \"stage3_max_reuse_distance\": 1e9,\n    \"stage3_gather_16bit_weights_on_model_save\": true\n  }\n}\n"
  },
  {
    "path": "finetune/configs/lora.yaml",
    "content": "data_config:\n  train_file: train.jsonl\n  val_file: dev.jsonl\n  test_file: dev.jsonl\n  num_proc: 1\n\ncombine: True\nfreezeV: True\nmax_input_length: 512\nmax_output_length: 512\n# swanlab: \"local\"  # set to local if don`t use cloud\n\ntraining_args:\n  # see `transformers.Seq2SeqTrainingArguments`\n  output_dir: ./output\n  max_steps: 3000\n  # needed to be fit for the dataset\n  learning_rate: 5e-4\n  # settings for data loading\n  per_device_train_batch_size: 1\n  dataloader_num_workers: 16\n  remove_unused_columns: false\n  # settings for saving checkpoints\n  save_strategy: steps\n  save_steps: 500\n  # settings for logging\n  log_level: info\n  logging_strategy: steps\n  logging_steps: 10\n  run_name: \"glm4-lora-finetune\"\n  # settings for evaluation\n  per_device_eval_batch_size: 4\n  eval_strategy: steps\n  eval_steps: 500\n  # settings for optimizer\n  # adam_epsilon: 1e-6\n  # uncomment the following line to detect nan or inf values\n  # debug: underflow_overflow\n  predict_with_generate: true\n  # see `transformers.GenerationConfig`\n  generation_config:\n    max_new_tokens: 512\n  # set your absolute deepspeed path here\n  # deepspeed: configs/ds_zero_3.json\n  deepspeed: configs/ds_zero_2.json\n\npeft_config:\n  peft_type: LORA\n  task_type: CAUSAL_LM\n  r: 8\n  lora_alpha: 32\n  lora_dropout: 0.1\n  target_modules: [\"q_proj\", \"k_proj\", \"v_proj\"]\n"
  },
  {
    "path": "finetune/configs/sft.yaml",
    "content": "data_config:\n  train_file: train.jsonl\n  val_file: dev.jsonl\n  test_file: dev.jsonl\n  num_proc: 1\n\ncombine: True\nfreezeV: True\nmax_input_length: 512\nmax_output_length: 512\n# swanlab: \"local\"  # set to local if don`t use cloud\n\ntraining_args:\n  # see `transformers.Seq2SeqTrainingArguments`\n  output_dir: ./output\n  max_steps: 3000\n  # needed to be fit for the dataset\n  learning_rate: 5e-5\n  # settings for data loading\n  per_device_train_batch_size: 1\n  dataloader_num_workers: 16\n  remove_unused_columns: false\n  # settings for saving checkpoints\n  save_strategy: steps\n  save_steps: 500\n  # settings for logging\n  log_level: info\n  logging_strategy: steps\n  logging_steps: 10\n  run_name: \"glm4-sft-finetune\"\n  # settings for evaluation\n  per_device_eval_batch_size: 16\n  eval_strategy: steps\n  eval_steps: 500\n  # settings for optimizer\n  # adam_epsilon: 1e-6\n  # uncomment the following line to detect nan or inf values\n  # debug: underflow_overflow\n  predict_with_generate: true\n  generation_config:\n    max_new_tokens: 512\n  # set your absolute deepspeed path here\n  deepspeed: configs/ds_zero_3.json\n"
  },
  {
    "path": "finetune/finetune.py",
    "content": "# -*- coding: utf-8 -*-\nimport dataclasses as dc\nimport functools\nimport os\nfrom collections.abc import Callable, Mapping, Sequence\nfrom pathlib import Path\nfrom typing import Annotated, Any, Optional, Union\n\nimport jieba\nimport numpy as np\nimport ruamel.yaml as yaml\nimport torch\nimport typer\nfrom datasets import Dataset, DatasetDict, NamedSplit, Split, load_dataset\nfrom nltk.translate.bleu_score import SmoothingFunction, sentence_bleu\nfrom peft import PeftConfig, get_peft_config, get_peft_model\nfrom rouge_chinese import Rouge\nfrom torch import nn\nfrom transformers import (\n    AutoModelForCausalLM,\n    AutoTokenizer,\n    EvalPrediction,\n    GenerationConfig,\n    PreTrainedTokenizer,\n    Seq2SeqTrainingArguments,\n)\nfrom transformers import DataCollatorForSeq2Seq as _DataCollatorForSeq2Seq\nfrom transformers import Seq2SeqTrainer as _Seq2SeqTrainer\n\n\n# For Ascend NPU, please add this\n# import torch_npu\n# from torch_npu.contrib import transfer_to_npu\n\napp = typer.Typer(pretty_exceptions_show_locals=False)\n\n\nclass DataCollatorForSeq2Seq(_DataCollatorForSeq2Seq):\n    def __call__(self, features, return_tensors=None):\n        output_ids = [feature[\"output_ids\"] for feature in features] if \"output_ids\" in features[0].keys() else None\n        if output_ids is not None:\n            max_output_length = max(len(out) for out in output_ids)\n            if self.pad_to_multiple_of is not None:\n                max_output_length = (\n                    (max_output_length + self.pad_to_multiple_of - 1)\n                    // self.pad_to_multiple_of\n                    * self.pad_to_multiple_of\n                )\n            for feature in features:\n                remainder = [self.tokenizer.pad_token_id] * (max_output_length - len(feature[\"output_ids\"]))\n                if isinstance(feature[\"output_ids\"], list):\n                    feature[\"output_ids\"] = feature[\"output_ids\"] + remainder\n                else:\n                    feature[\"output_ids\"] = np.concatenate([feature[\"output_ids\"], remainder]).astype(np.int64)\n        return super().__call__(features, return_tensors)\n\n\nclass Seq2SeqTrainer(_Seq2SeqTrainer):\n    def prediction_step(\n        self,\n        model: nn.Module,\n        inputs: dict[str, Any],\n        prediction_loss_only: bool,\n        ignore_keys=None,\n        **gen_kwargs,\n    ) -> tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:\n        with torch.no_grad():  # Ensure no gradient computation\n            if self.args.predict_with_generate:\n                output_ids = inputs.pop(\"output_ids\")\n            input_ids = inputs[\"input_ids\"]\n\n            del inputs[\"labels\"]\n            loss, generated_tokens, labels = super().prediction_step(\n                model, inputs, prediction_loss_only, ignore_keys, **gen_kwargs\n            )\n\n            generated_tokens = generated_tokens[:, input_ids.size()[1] :]\n            labels = output_ids\n\n            del inputs, input_ids, output_ids\n            torch.cuda.empty_cache()\n\n        return loss, generated_tokens, labels\n\n\n@dc.dataclass\nclass DataConfig(object):\n    train_file: Optional[str] = None\n    val_file: Optional[str] = None\n    test_file: Optional[str] = None\n    num_proc: Optional[int] = None\n\n    @property\n    def data_format(self) -> str:\n        return Path(self.train_file).suffix\n\n    @property\n    def data_files(self) -> dict[NamedSplit, str]:\n        return {\n            split: data_file\n            for split, data_file in zip(\n                [Split.TRAIN, Split.VALIDATION, Split.TEST],\n                [self.train_file, self.val_file, self.test_file],\n            )\n            if data_file is not None\n        }\n\n\n@dc.dataclass\nclass FinetuningConfig(object):\n    data_config: DataConfig\n\n    max_input_length: int\n    max_output_length: int\n    combine: bool\n    freezeV: bool\n\n    training_args: Seq2SeqTrainingArguments = dc.field(\n        default_factory=lambda: Seq2SeqTrainingArguments(output_dir=\"./output\")\n    )\n    peft_config: Optional[PeftConfig] = None\n    swanlab: Optional[str] = \"cloud\"\n\n    def __post_init__(self):\n        if not self.training_args.do_eval or self.data_config.val_file is None:\n            self.training_args.do_eval = False\n            self.training_args.evaluation_strategy = \"no\"\n            self.data_config.val_file = None\n        else:\n            self.training_args.per_device_eval_batch_size = (\n                self.training_args.per_device_eval_batch_size or self.training_args.per_device_train_batch_size\n            )\n        if self.swanlab != \"disabled\":\n            os.environ[\"SWANLAB_PROJ_NAME\"] = \"GLM4-Finetune\"\n        if self.swanlab == \"local\":\n            os.environ[\"SWANLAB_MODE\"] = \"local\"\n\n    @classmethod\n    def from_dict(cls, **kwargs) -> \"FinetuningConfig\":\n        training_args = kwargs.get(\"training_args\", None)\n        if training_args is not None and not isinstance(training_args, Seq2SeqTrainingArguments):\n            gen_config = training_args.get(\"generation_config\")\n            if not isinstance(gen_config, GenerationConfig):\n                training_args[\"generation_config\"] = GenerationConfig(**gen_config)\n            kwargs[\"training_args\"] = Seq2SeqTrainingArguments(**training_args)\n\n        data_config = kwargs.get(\"data_config\")\n        if not isinstance(data_config, DataConfig):\n            kwargs[\"data_config\"] = DataConfig(**data_config)\n\n        peft_config = kwargs.get(\"peft_config\", None)\n        if peft_config is not None and not isinstance(peft_config, PeftConfig):\n            kwargs[\"peft_config\"] = get_peft_config(config_dict=peft_config)\n        return cls(**kwargs)\n\n    @classmethod\n    def from_file(cls, path: Union[str, Path]) -> \"FinetuningConfig\":\n        path = Path(path)\n        parser = yaml.YAML(typ=\"safe\", pure=True)\n        parser.indent(mapping=2, offset=2, sequence=4)\n        parser.default_flow_style = False\n        kwargs = parser.load(path)\n        return cls.from_dict(**kwargs)\n\n\ndef _load_datasets(\n    data_dir: str,\n    data_format: str,\n    data_files: dict[NamedSplit, str],\n    num_proc: Optional[int],\n) -> DatasetDict:\n    if data_format == \".jsonl\":\n        dataset_dct = load_dataset(\n            data_dir,\n            data_files=data_files,\n            split=None,\n            num_proc=num_proc,\n        )\n    else:\n        raise NotImplementedError(f\"Cannot load dataset in the '{data_format}' format.\")\n    return dataset_dct\n\n\nclass DataManager(object):\n    def __init__(self, data_dir: str, data_config: DataConfig):\n        self._num_proc = data_config.num_proc\n\n        self._dataset_dct = _load_datasets(\n            data_dir,\n            data_config.data_format,\n            data_config.data_files,\n            self._num_proc,\n        )\n\n    def _get_dataset(self, split: NamedSplit) -> Optional[Dataset]:\n        return self._dataset_dct.get(split, None)\n\n    def get_dataset(\n        self,\n        split: NamedSplit,\n        process_fn: Callable[[dict[str, Any]], dict[str, Any]],\n        batched: bool = True,\n        remove_orig_columns: bool = True,\n    ) -> Optional[Dataset]:\n        orig_dataset = self._get_dataset(split)\n        if orig_dataset is None:\n            return\n\n        if remove_orig_columns:\n            remove_columns = orig_dataset.column_names\n        else:\n            remove_columns = None\n        return orig_dataset.map(\n            process_fn,\n            batched=batched,\n            remove_columns=remove_columns,\n            num_proc=self._num_proc,\n        )\n\n\ndef process_message(message):\n    if \"tools\" in message and message[\"role\"] == \"system\":\n        for tool in message[\"tools\"]:\n            parameters = tool[\"function\"][\"parameters\"][\"properties\"]\n            tool[\"function\"][\"parameters\"][\"properties\"] = {k: v for k, v in parameters.items() if v is not None}\n    elif \"tools\" in message:\n        del message[\"tools\"]\n    return message\n\n\ndef process_batch(\n    batch: Mapping[str, Sequence],\n    tokenizer: PreTrainedTokenizer,\n    max_input_length: int,\n    max_output_length: int,\n    combine: bool,\n) -> dict[str, list]:\n    batched_conv = batch[\"messages\"]\n    batched_input_ids = []\n    batched_labels = []\n    for conv in batched_conv:\n        input_ids = [151331, 151333]\n        loss_masks = [False, False]\n        if combine:\n            new_input_ids = tokenizer.apply_chat_template(conv, tokenize=True, return_dict=False)\n            input_ids = new_input_ids\n            loss_masks = [False] * len(input_ids)\n            last_assistant_index = len(input_ids) - input_ids[::-1].index(151337) - 1\n            for j in range(last_assistant_index + 1, len(input_ids)):\n                loss_masks[j] = True\n        else:\n            for message in conv:\n                message = process_message(message)\n                loss_mask_val = False if message[\"role\"] in (\"system\", \"user\", \"observation\") else True\n                new_input_ids = tokenizer.apply_chat_template([message], tokenize=True, return_dict=False)[2:]\n                input_ids += new_input_ids\n                loss_masks += [loss_mask_val] * len(new_input_ids)\n\n        input_ids.append(151336)  # EOS for chat\n        loss_masks = [False, *loss_masks]\n        labels = []\n        for input_id, mask in zip(input_ids, loss_masks):\n            if mask:\n                labels.append(input_id)\n            else:\n                labels.append(-100)\n        max_length = max_input_length + max_output_length + 1\n        batched_input_ids.append(input_ids[:max_length])\n        batched_labels.append(labels[:max_length])\n\n    del batched_conv, conv, input_ids, loss_masks, new_input_ids, labels\n    torch.cuda.empty_cache()\n\n    return {\"input_ids\": batched_input_ids, \"labels\": batched_labels}\n\n\ndef process_batch_eval(\n    batch: Mapping[str, Sequence],\n    tokenizer: PreTrainedTokenizer,\n    max_input_length: int,\n    max_output_length: int,\n    combine: bool,\n) -> dict[str, list]:\n    batched_conv = batch[\"messages\"]\n    batched_input_ids = []\n    batched_output_ids = []\n\n    for conv in batched_conv:\n        if combine:\n            new_input_ids = tokenizer.apply_chat_template(conv, tokenize=True, return_dict=False)\n            input_ids = new_input_ids\n            last_assistant_index = len(input_ids) - input_ids[::-1].index(151337) - 1\n            output_prompt, output_ids = (\n                input_ids[:1],\n                input_ids[last_assistant_index:],\n            )\n            output_ids.append(151336)\n            batched_input_ids.append(input_ids[:max_input_length] + output_prompt[:1])\n            batched_output_ids.append(output_ids[:max_output_length])\n        else:\n            input_ids = [151331, 151333]\n            for message in conv:\n                if len(input_ids) >= max_input_length:\n                    break\n                else:\n                    message = process_message(message)\n                    new_input_ids = tokenizer.apply_chat_template([message], tokenize=True, return_dict=False)[2:]\n                    if message[\"role\"] == \"assistant\":\n                        output_prompt, output_ids = (\n                            new_input_ids[:1],\n                            new_input_ids[1:],\n                        )\n                        output_ids.append(151336)\n                        batched_input_ids.append(input_ids[:max_input_length] + output_prompt[:1])\n                        batched_output_ids.append(output_ids[:max_output_length])\n                    input_ids += new_input_ids\n\n    del batched_conv, conv, input_ids, new_input_ids, output_prompt, output_ids\n    torch.cuda.empty_cache()\n\n    return {\"input_ids\": batched_input_ids, \"output_ids\": batched_output_ids}\n\n\ndef load_tokenizer_and_model(\n    model_dir: str,\n    peft_config: Optional[PeftConfig] = None,\n):\n    tokenizer = AutoTokenizer.from_pretrained(model_dir, padding_side=\"left\", trust_remote_code=True)\n    if peft_config is not None:\n        model = AutoModelForCausalLM.from_pretrained(\n            model_dir,\n            use_cache=False,\n            torch_dtype=torch.bfloat16,  # Must use BFloat 16\n        )\n        model = get_peft_model(model, peft_config)\n        model.print_trainable_parameters()\n    else:\n        model = AutoModelForCausalLM.from_pretrained(\n            model_dir,\n            use_cache=False,\n            torch_dtype=torch.bfloat16,\n        )\n    return tokenizer, model\n\n\ndef compute_metrics(eval_preds: EvalPrediction, tokenizer):\n    batched_pred_ids, batched_label_ids = eval_preds\n    batched_pred_ids[batched_pred_ids == -100] = tokenizer.pad_token_id\n    batched_label_ids[batched_label_ids == -100] = tokenizer.pad_token_id\n    metrics_dct = {\"rouge-1\": [], \"rouge-2\": [], \"rouge-l\": [], \"bleu-4\": []}\n    for pred_ids, label_ids in zip(batched_pred_ids, batched_label_ids):\n        pred_txt = tokenizer.decode(pred_ids).strip()\n        label_txt = tokenizer.decode(label_ids).strip()\n        pred_tokens = list(jieba.cut(pred_txt))\n        label_tokens = list(jieba.cut(label_txt))\n        rouge = Rouge()\n        scores = rouge.get_scores(\" \".join(pred_tokens), \" \".join(label_tokens))\n        for k, v in scores[0].items():\n            metrics_dct[k].append(round(v[\"f\"] * 100, 4))\n        metrics_dct[\"bleu-4\"].append(\n            sentence_bleu(\n                [label_tokens],\n                pred_tokens,\n                smoothing_function=SmoothingFunction().method3,\n            )\n        )\n    return {k: np.mean(v) for k, v in metrics_dct.items()}\n\n\n@app.command()\ndef main(\n    data_dir: Annotated[str, typer.Argument(help=\"\")],\n    model_dir: Annotated[\n        str,\n        typer.Argument(\n            help=\"A string that specifies the model id of a pretrained model configuration hosted on huggingface.co, or a path to a directory containing a model configuration file.\"\n        ),\n    ],\n    config_file: Annotated[str, typer.Argument(help=\"\")],\n    auto_resume_from_checkpoint: str = typer.Argument(\n        default=\"\",\n        help=\"If entered as yes, automatically use the latest save checkpoint. If it is a numerical example 12 15, use the corresponding save checkpoint. If the input is no, restart training\",\n    ),\n):\n    ft_config = FinetuningConfig.from_file(config_file)\n    tokenizer, model = load_tokenizer_and_model(model_dir, peft_config=ft_config.peft_config)\n    data_manager = DataManager(data_dir, ft_config.data_config)\n\n    train_dataset = data_manager.get_dataset(\n        Split.TRAIN,\n        functools.partial(\n            process_batch,\n            tokenizer=tokenizer,\n            combine=ft_config.combine,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n    print(\"train_dataset:\", train_dataset)\n    val_dataset = data_manager.get_dataset(\n        Split.VALIDATION,\n        functools.partial(\n            process_batch_eval,\n            tokenizer=tokenizer,\n            combine=ft_config.combine,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n    if val_dataset is not None:\n        print(\"val_dataset:\", val_dataset)\n    test_dataset = data_manager.get_dataset(\n        Split.TEST,\n        functools.partial(\n            process_batch_eval,\n            tokenizer=tokenizer,\n            combine=ft_config.combine,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n    if test_dataset is not None:\n        print(\"test_dataset:\", test_dataset)\n\n    ft_config.training_args.generation_config.pad_token_id = 151329\n    ft_config.training_args.generation_config.eos_token_id = [151329, 151336, 151338]\n\n    trainer = Seq2SeqTrainer(\n        model=model,\n        args=ft_config.training_args,\n        data_collator=DataCollatorForSeq2Seq(\n            tokenizer=tokenizer,\n            padding=\"longest\",\n            return_tensors=\"pt\",\n        ),\n        train_dataset=train_dataset,\n        eval_dataset=val_dataset,\n        compute_metrics=functools.partial(compute_metrics, tokenizer=tokenizer),\n    )\n\n    if auto_resume_from_checkpoint.upper() == \"\" or auto_resume_from_checkpoint is None:\n        trainer.train()\n    else:\n        output_dir = ft_config.training_args.output_dir\n        dirlist = os.listdir(output_dir)\n        checkpoint_sn = 0\n        for checkpoint_str in dirlist:\n            if checkpoint_str.find(\"eckpoint\") > 0 and checkpoint_str.find(\"tmp\") == -1:\n                checkpoint = int(checkpoint_str.replace(\"checkpoint-\", \"\"))\n                if checkpoint > checkpoint_sn:\n                    checkpoint_sn = checkpoint\n        if auto_resume_from_checkpoint.upper() == \"YES\":\n            if checkpoint_sn > 0:\n                model.gradient_checkpointing_enable()\n                model.enable_input_require_grads()\n                checkpoint_directory = os.path.join(output_dir, \"checkpoint-\" + str(checkpoint_sn))\n                print(\"resume checkpoint from checkpoint-\" + str(checkpoint_sn))\n                trainer.train(resume_from_checkpoint=checkpoint_directory)\n            else:\n                trainer.train()\n        else:\n            if auto_resume_from_checkpoint.isdigit():\n                if int(auto_resume_from_checkpoint) > 0:\n                    checkpoint_sn = int(auto_resume_from_checkpoint)\n                    model.gradient_checkpointing_enable()\n                    model.enable_input_require_grads()\n                    checkpoint_directory = os.path.join(output_dir, \"checkpoint-\" + str(checkpoint_sn))\n                    print(\"resume checkpoint from checkpoint-\" + str(checkpoint_sn))\n                    trainer.train(resume_from_checkpoint=checkpoint_directory)\n            else:\n                print(\n                    auto_resume_from_checkpoint,\n                    \"The specified checkpoint sn(\"\n                    + auto_resume_from_checkpoint\n                    + \") has not been saved. Please search for the correct checkpoint in the model output directory\",\n                )\n\n    if test_dataset is not None:\n        trainer.predict(test_dataset)\n\n\nif __name__ == \"__main__\":\n    app()\n"
  },
  {
    "path": "finetune/finetune_vision.py",
    "content": "# -*- coding: utf-8 -*-\nimport dataclasses as dc\nimport functools\nimport os\nfrom collections.abc import Callable, Mapping, Sequence\nfrom pathlib import Path\nfrom typing import Annotated, Any, Optional, Union\n\nimport jieba\nimport numpy as np\nimport ruamel.yaml as yaml\nimport torch\nimport typer\nfrom datasets import Dataset, DatasetDict, NamedSplit, Split, load_dataset\nfrom nltk.translate.bleu_score import SmoothingFunction, sentence_bleu\nfrom peft import PeftConfig, get_peft_config, get_peft_model\nfrom PIL import Image\nfrom rouge_chinese import Rouge\nfrom torch import nn\nfrom transformers import (\n    AutoModelForCausalLM,\n    AutoTokenizer,\n    EvalPrediction,\n    GenerationConfig,\n    PreTrainedTokenizer,\n    Seq2SeqTrainingArguments,\n)\nfrom transformers import DataCollatorForSeq2Seq as _DataCollatorForSeq2Seq\nfrom transformers import Seq2SeqTrainer as _Seq2SeqTrainer\n\n\n# For Ascend NPU, please add this\n# import torch_npu\n# from torch_npu.contrib import transfer_to_npu\n\napp = typer.Typer(pretty_exceptions_show_locals=False)\nimg = Image.new(\"L\", (224, 224), 0).convert(\"RGB\")\n\n\nclass DataCollatorForSeq2Seq(_DataCollatorForSeq2Seq):\n    def __call__(self, features, return_tensors=None):\n        output_ids = [feature[\"output_ids\"] for feature in features] if \"output_ids\" in features[0].keys() else None\n        if output_ids is not None:\n            max_output_length = max(len(out) for out in output_ids)\n            if self.pad_to_multiple_of is not None:\n                max_output_length = (\n                    (max_output_length + self.pad_to_multiple_of - 1)\n                    // self.pad_to_multiple_of\n                    * self.pad_to_multiple_of\n                )\n            for feature in features:\n                remainder = [self.tokenizer.pad_token_id] * (max_output_length - len(feature[\"output_ids\"]))\n                if isinstance(feature[\"output_ids\"], list):\n                    feature[\"output_ids\"] = feature[\"output_ids\"] + remainder\n                else:\n                    feature[\"output_ids\"] = np.concatenate([feature[\"output_ids\"], remainder]).astype(np.int64)\n        return super().__call__(features, return_tensors)\n\n\nclass Seq2SeqTrainer(_Seq2SeqTrainer):\n    def prediction_step(\n        self,\n        model: nn.Module,\n        inputs: dict,\n        prediction_loss_only: bool,\n        ignore_keys=None,\n        **gen_kwargs,\n    ) -> tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:\n        with torch.no_grad():\n            if self.args.predict_with_generate:\n                output_ids = inputs.pop(\"output_ids\", None)\n                del inputs[\"labels\"]\n            loss, generated_tokens, labels = super().prediction_step(\n                model=model,\n                inputs=inputs,\n                prediction_loss_only=prediction_loss_only,\n                ignore_keys=ignore_keys,\n                **gen_kwargs,\n            )\n\n            if generated_tokens is not None:\n                generated_tokens = generated_tokens[:, inputs[\"input_ids\"].size()[1] :]\n\n            if self.args.predict_with_generate:\n                labels = output_ids\n\n            del inputs, output_ids\n            torch.cuda.empty_cache()\n\n        return loss, generated_tokens, labels\n\n\n@dc.dataclass\nclass DataConfig(object):\n    train_file: Optional[str] = None\n    val_file: Optional[str] = None\n    test_file: Optional[str] = None\n    num_proc: Optional[int] = None\n\n    @property\n    def data_format(self) -> str:\n        return Path(self.train_file).suffix\n\n    @property\n    def data_files(self) -> dict[NamedSplit, str]:\n        return {\n            split: data_file\n            for split, data_file in zip(\n                [Split.TRAIN, Split.VALIDATION, Split.TEST],\n                [self.train_file, self.val_file, self.test_file],\n            )\n            if data_file is not None\n        }\n\n\n@dc.dataclass\nclass FinetuningConfig(object):\n    data_config: DataConfig\n\n    max_input_length: int\n    max_output_length: int\n    combine: bool\n    freezeV: bool\n    swanlab: Optional[str] = \"cloud\"\n\n    training_args: Seq2SeqTrainingArguments = dc.field(\n        default_factory=lambda: Seq2SeqTrainingArguments(output_dir=\"./output\")\n    )\n    peft_config: Optional[PeftConfig] = None\n\n    def __post_init__(self):\n        if not self.training_args.do_eval or self.data_config.val_file is None:\n            self.training_args.do_eval = False\n            self.training_args.evaluation_strategy = \"no\"\n            self.data_config.val_file = None\n        else:\n            self.training_args.per_device_eval_batch_size = (\n                self.training_args.per_device_eval_batch_size or self.training_args.per_device_train_batch_size\n            )\n        if self.swanlab != \"disabled\":\n            os.environ[\"SWANLAB_PROJ_NAME\"] = \"GLM4-Finetune\"\n        if self.swanlab == \"local\":\n            os.environ[\"SWANLAB_MODE\"] = \"local\"\n\n    @classmethod\n    def from_dict(cls, **kwargs) -> \"FinetuningConfig\":\n        training_args = kwargs.get(\"training_args\", None)\n        if training_args is not None and not isinstance(training_args, Seq2SeqTrainingArguments):\n            gen_config = training_args.get(\"generation_config\")\n            if not isinstance(gen_config, GenerationConfig):\n                training_args[\"generation_config\"] = GenerationConfig(**gen_config)\n            kwargs[\"training_args\"] = Seq2SeqTrainingArguments(**training_args)\n\n        data_config = kwargs.get(\"data_config\")\n        if not isinstance(data_config, DataConfig):\n            kwargs[\"data_config\"] = DataConfig(**data_config)\n\n        peft_config = kwargs.get(\"peft_config\", None)\n        if peft_config is not None and not isinstance(peft_config, PeftConfig):\n            kwargs[\"peft_config\"] = get_peft_config(config_dict=peft_config)\n        return cls(**kwargs)\n\n    @classmethod\n    def from_file(cls, path: Union[str, Path]) -> \"FinetuningConfig\":\n        path = Path(path)\n        parser = yaml.YAML(typ=\"safe\", pure=True)\n        parser.indent(mapping=2, offset=2, sequence=4)\n        parser.default_flow_style = False\n        kwargs = parser.load(path)\n        return cls.from_dict(**kwargs)\n\n\ndef _load_datasets(\n    data_dir: str,\n    data_format: str,\n    data_files: dict[NamedSplit, str],\n    num_proc: Optional[int],\n) -> DatasetDict:\n    if data_format == \".jsonl\":\n        dataset_dct = load_dataset(\n            data_dir,\n            data_files=data_files,\n            split=None,\n            num_proc=num_proc,\n        )\n    else:\n        raise NotImplementedError(f\"Cannot load dataset in the '{data_format}' format.\")\n    return dataset_dct\n\n\nclass DataManager(object):\n    def __init__(self, data_dir: str, data_config: DataConfig):\n        self._num_proc = data_config.num_proc\n\n        self._dataset_dct = _load_datasets(\n            data_dir,\n            data_config.data_format,\n            data_config.data_files,\n            self._num_proc,\n        )\n\n    def _get_dataset(self, split: NamedSplit) -> Optional[Dataset]:\n        return self._dataset_dct.get(split, None)\n\n    def get_dataset(\n        self,\n        split: NamedSplit,\n        process_fn: Callable[[dict[str, Any]], dict[str, Any]],\n        batched: bool = True,\n        remove_orig_columns: bool = True,\n    ) -> Optional[Dataset]:\n        orig_dataset = self._get_dataset(split)\n        if orig_dataset is None:\n            return\n        if remove_orig_columns:\n            remove_columns = orig_dataset.column_names\n        else:\n            remove_columns = None\n        return orig_dataset.map(\n            process_fn,\n            batched=batched,\n            remove_columns=remove_columns,\n            num_proc=self._num_proc,\n            # This is default params of  orig_dataset.map, and you can change it smaller\n            # https://github.com/THUDM/GLM-4/issues/277\n            writer_batch_size=1000,\n            batch_size=1000,\n        )\n\n\ndef process_batch(\n    batch: Mapping[str, Sequence],\n    tokenizer: PreTrainedTokenizer,\n    max_input_length: int,\n    max_output_length: int,\n    combine: bool,\n) -> dict[str, list]:\n    batched_conv = batch[\"messages\"]\n    batched_input_ids = []\n    batched_attention_mask = []\n    batched_position_ids = []\n    batched_labels = []\n    batched_images = []\n\n    max_length = max_input_length + max_output_length\n\n    for conv in batched_conv:\n        input_ids = [151331, 151333]\n        attention_mask = [1, 1]\n        position_ids = list(range(len(input_ids)))\n        loss_masks = [False, False]\n        images = []\n\n        if conv[0].get(\"image\"):\n            conv[0][\"image\"] = Image.open(conv[0][\"image\"]).convert(\"RGB\")\n        else:\n            conv[0][\"image\"] = img\n\n        for message in conv:\n            loss_mask_val = False if message[\"role\"] in (\"system\", \"user\", \"observation\") else True\n            new_input_ids_all = tokenizer.apply_chat_template([message], tokenize=True, return_dict=True, padding=True)\n            new_input_ids = new_input_ids_all[\"input_ids\"][0][2:]\n            new_attention_mask = new_input_ids_all[\"attention_mask\"][0][2:]\n            new_position_ids = list(range(position_ids[-1] + 1, position_ids[-1] + 1 + len(new_input_ids)))\n            if message.get(\"image\"):  # Only One Image\n                images.append(new_input_ids_all[\"images\"])\n\n            new_loss_masks = [loss_mask_val] * len(new_input_ids)\n            input_ids += new_input_ids\n            attention_mask += new_attention_mask\n            position_ids += new_position_ids\n            loss_masks += new_loss_masks\n\n        input_ids.append(151336)  # EOS\n        attention_mask.append(1)\n        position_ids.append(len(position_ids))\n        loss_masks.append(False)\n\n        labels = []\n        for input_id, mask in zip(input_ids, loss_masks):\n            if mask:\n                labels.append(input_id)\n            else:\n                labels.append(-100)\n\n        batched_input_ids.append(input_ids[:max_length])\n        batched_attention_mask.append(attention_mask[:max_length])\n        batched_position_ids.append(position_ids[:max_length])\n        batched_labels.append(labels[:max_length])\n        batched_images.append(images[0][0])\n\n    del (\n        batched_conv,\n        conv,\n        input_ids,\n        attention_mask,\n        position_ids,\n        loss_masks,\n        message,\n        new_input_ids,\n        new_loss_masks,\n        labels,\n        input_id,\n        mask,\n    )\n    torch.cuda.empty_cache()\n\n    return {\n        \"input_ids\": batched_input_ids,\n        \"attention_mask\": batched_attention_mask,\n        \"position_ids\": batched_position_ids,\n        \"labels\": batched_labels,\n        \"images\": batched_images,\n    }\n\n\ndef process_batch_eval(\n    batch: Mapping[str, Sequence],\n    tokenizer: PreTrainedTokenizer,\n    max_input_length: int,\n    max_output_length: int,\n    combine: bool,\n) -> dict[str, list]:\n    batched_conv = batch[\"messages\"]\n    batched_input_ids = []\n    batched_attention_mask = []\n    batched_position_ids = []\n    batched_output_ids = []\n    batched_images = []\n\n    for conv in batched_conv:\n        if conv[0].get(\"image\"):\n            image = Image.open(conv[0][\"image\"]).convert(\"RGB\")\n        else:\n            image = img\n\n        conv[0][\"image\"] = image\n        new_input_ids_all = tokenizer.apply_chat_template(conv, tokenize=True, return_dict=True, padding=True)\n\n        input_ids = new_input_ids_all[\"input_ids\"][0]\n        attention_mask = new_input_ids_all[\"attention_mask\"][0]\n        position_ids = list(range(len(input_ids)))\n\n        dialogue_parts = [0]\n        user_idx = []\n        for idx, token_id in enumerate(input_ids):\n            if token_id == 151337:\n                dialogue_parts.append(idx + 1)\n            elif token_id == 151336:\n                user_idx.append(idx)\n\n        if user_idx[-1] != len(input_ids):\n            user_idx.append(len(input_ids))\n\n        # Split the conversation into multiple dialogue segments\n        for end_idx in range(1, len(dialogue_parts)):\n            input_segment = input_ids[: dialogue_parts[end_idx]]\n            attention_segment = attention_mask[: dialogue_parts[end_idx]]\n            position_segment = position_ids[: dialogue_parts[end_idx]]\n            output_segment = input_ids[dialogue_parts[end_idx] : user_idx[end_idx]]\n            output_segment.append(151336)  # Add EOS token\n\n            batched_input_ids.append(input_segment[:max_input_length])\n            batched_attention_mask.append(attention_segment[:max_input_length])\n            batched_position_ids.append(position_segment[:max_input_length])\n            batched_output_ids.append(output_segment[:max_output_length])\n            batched_images.append(new_input_ids_all[\"images\"][0])\n\n    del (\n        batched_conv,\n        input_ids,\n        attention_mask,\n        position_ids,\n        new_input_ids_all,\n        output_segment,\n    )\n    torch.cuda.empty_cache()\n\n    return {\n        \"input_ids\": batched_input_ids,\n        \"attention_mask\": batched_attention_mask,\n        \"position_ids\": batched_position_ids,\n        \"output_ids\": batched_output_ids,\n        \"images\": batched_images,\n    }\n\n\ndef load_tokenizer_and_model(\n    model_dir: str,\n    peft_config: Optional[PeftConfig] = None,\n):\n    tokenizer = AutoTokenizer.from_pretrained(model_dir, padding_side=\"left\", trust_remote_code=True)\n    if peft_config is not None:\n        model = AutoModelForCausalLM.from_pretrained(\n            model_dir,\n            trust_remote_code=True,\n            use_cache=False,\n            torch_dtype=torch.bfloat16,  # Must use BFloat 16\n        )\n        model = get_peft_model(model, peft_config)\n        model.print_trainable_parameters()\n    else:\n        model = AutoModelForCausalLM.from_pretrained(\n            model_dir,\n            trust_remote_code=True,\n            use_cache=False,\n            torch_dtype=torch.bfloat16,\n        )\n    return tokenizer, model\n\n\ndef compute_metrics(eval_preds: EvalPrediction, tokenizer):\n    batched_pred_ids, batched_label_ids = eval_preds\n    batched_pred_ids[batched_pred_ids == -100] = tokenizer.pad_token_id\n    batched_label_ids[batched_label_ids == -100] = tokenizer.pad_token_id\n    metrics_dct = {\"rouge-1\": [], \"rouge-2\": [], \"rouge-l\": [], \"bleu-4\": []}\n    for pred_ids, label_ids in zip(batched_pred_ids, batched_label_ids):\n        pred_txt = tokenizer.decode(pred_ids).strip()\n        label_txt = tokenizer.decode(label_ids).strip()\n        pred_tokens = list(jieba.cut(pred_txt))\n        label_tokens = list(jieba.cut(label_txt))\n        rouge = Rouge()\n        scores = rouge.get_scores(\" \".join(pred_tokens), \" \".join(label_tokens))\n        for k, v in scores[0].items():\n            metrics_dct[k].append(round(v[\"f\"] * 100, 4))\n        metrics_dct[\"bleu-4\"].append(\n            sentence_bleu(\n                [label_tokens],\n                pred_tokens,\n                smoothing_function=SmoothingFunction().method3,\n            )\n        )\n    return {k: np.mean(v) for k, v in metrics_dct.items()}\n\n\n@app.command()\ndef main(\n    data_dir: Annotated[str, typer.Argument(help=\"\")],\n    model_dir: Annotated[\n        str,\n        typer.Argument(\n            help=\"A string that specifies the model id of a pretrained model configuration hosted on huggingface.co, or a path to a directory containing a model configuration file.\"\n        ),\n    ],\n    config_file: Annotated[str, typer.Argument(help=\"\")],\n    auto_resume_from_checkpoint: str = typer.Argument(\n        default=\"\",\n        help=\"If entered as yes, automatically use the latest save checkpoint. If it is a numerical example 12 15, use the corresponding save checkpoint. If the input is no, restart training\",\n    ),\n):\n    ft_config = FinetuningConfig.from_file(config_file)\n    tokenizer, model = load_tokenizer_and_model(model_dir, peft_config=ft_config.peft_config)\n\n    if ft_config.freezeV:\n        for param in model.transformer.vision.parameters():\n            param.requires_grad = False\n    data_manager = DataManager(data_dir, ft_config.data_config)\n\n    train_dataset = data_manager.get_dataset(\n        Split.TRAIN,\n        functools.partial(\n            process_batch,\n            combine=ft_config.combine,  # Not use now\n            tokenizer=tokenizer,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n    print(\"train_dataset:\", train_dataset)\n\n    val_dataset = data_manager.get_dataset(\n        Split.VALIDATION,\n        functools.partial(\n            process_batch_eval,\n            combine=ft_config.combine,\n            tokenizer=tokenizer,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n\n    if val_dataset is not None:\n        print(\"val_dataset:\", val_dataset)\n    test_dataset = data_manager.get_dataset(\n        Split.TEST,\n        functools.partial(\n            process_batch_eval,\n            combine=ft_config.combine,\n            tokenizer=tokenizer,\n            max_input_length=ft_config.max_input_length,\n            max_output_length=ft_config.max_output_length,\n        ),\n        batched=True,\n    )\n    if test_dataset is not None:\n        print(\"test_dataset:\", test_dataset)\n\n    ft_config.training_args.generation_config.pad_token_id = 151329\n    ft_config.training_args.generation_config.eos_token_id = [151329, 151336, 151338]\n\n    trainer = Seq2SeqTrainer(\n        model=model,\n        args=ft_config.training_args,\n        data_collator=DataCollatorForSeq2Seq(\n            tokenizer=tokenizer,\n            padding=\"longest\",\n            return_tensors=\"pt\",\n        ),\n        train_dataset=train_dataset,\n        eval_dataset=val_dataset,\n        compute_metrics=functools.partial(compute_metrics, tokenizer=tokenizer),\n    )\n\n    if auto_resume_from_checkpoint.upper() == \"\" or auto_resume_from_checkpoint is None:\n        trainer.train()\n    else:\n        output_dir = ft_config.training_args.output_dir\n        dirlist = os.listdir(output_dir)\n        checkpoint_sn = 0\n        for checkpoint_str in dirlist:\n            if checkpoint_str.find(\"eckpoint\") > 0 and checkpoint_str.find(\"tmp\") == -1:\n                checkpoint = int(checkpoint_str.replace(\"checkpoint-\", \"\"))\n                if checkpoint > checkpoint_sn:\n                    checkpoint_sn = checkpoint\n        if auto_resume_from_checkpoint.upper() == \"YES\":\n            if checkpoint_sn > 0:\n                model.gradient_checkpointing_enable()\n                model.enable_input_require_grads()\n                checkpoint_directory = os.path.join(output_dir, \"checkpoint-\" + str(checkpoint_sn))\n                print(\"resume checkpoint from checkpoint-\" + str(checkpoint_sn))\n                trainer.train(resume_from_checkpoint=checkpoint_directory)\n            else:\n                trainer.train()\n        else:\n            if auto_resume_from_checkpoint.isdigit():\n                if int(auto_resume_from_checkpoint) > 0:\n                    checkpoint_sn = int(auto_resume_from_checkpoint)\n                    model.gradient_checkpointing_enable()\n                    model.enable_input_require_grads()\n                    checkpoint_directory = os.path.join(output_dir, \"checkpoint-\" + str(checkpoint_sn))\n                    print(\"resume checkpoint from checkpoint-\" + str(checkpoint_sn))\n                    trainer.train(resume_from_checkpoint=checkpoint_directory)\n            else:\n                print(\n                    auto_resume_from_checkpoint,\n                    \"The specified checkpoint sn(\"\n                    + auto_resume_from_checkpoint\n                    + \") has not been saved. Please search for the correct checkpoint in the model output directory\",\n                )\n\n    if test_dataset is not None:\n        trainer.predict(test_dataset)\n\n\nif __name__ == \"__main__\":\n    app()\n"
  },
  {
    "path": "finetune/requirements.txt",
    "content": "jieba>=0.42.1\ndatasets>=2.20.0\npeft>=0.15.1\ndeepspeed>=0.16.5\nnltk==3.8.1\nrouge_chinese==1.0.3\nruamel.yaml>=0.18.6\ntyper>=0.13.0\ntqdm>=4.67.0\n"
  },
  {
    "path": "inference/README.md",
    "content": "# Inference\n\n[中文阅读](README_zh.md)\n\nPlease follow the steps in the document strictly to avoid unnecessary errors.\n\n## Device and dependency check\n\n### Install dependencies\n\n```shell\npip install -r requirements.txt\n```\n\n### Related Inference Benchmark Data\n\n**All benchmark data in this document was collected under the hardware environment listed below. Actual memory usage and runtime may vary depending on your deployment setup. Please refer to your actual environment.**\n\nTest Hardware:\n\n+ OS: Ubuntu 22.04\n+ Memory: 512GB\n+ Python: 3.12.3\n+ Cmake 3.23.0\n+ CUDA Version: 12.4\n+ GPU Driver: 535.104.05\n+ GPU: NVIDIA H100 80GB HBM3 * 8\n\nThe following stress test results show memory usage and latency during inference. If multiple GPUs are used, \"Memory Usage\" refers to the maximum usage on a single GPU.\n\n#### GLM-4-32B-0414\n\n| Precision   | #GPUs | Memory Usage  | First Token Latency | Token Output Speed | Input Tokens |\n|-------------|-------|---------------|---------------------|-------------------|--------------|\n| BF16        | 1     | 68 GB         | 0.16s               | 24.4 tokens/s     | 1000         |\n| BF16        | 1     | 72 GB         | 1.37s               | 16.9 tokens/s     | 8000         |\n| BF16        | 2     | 50 GB         | 6.75s               | 8.1 tokens/s      | 32000        |\n| BF16        | 4     | 55 GB         | 37.83s              | 3.0 tokens/s      | 100000       |\n\n#### GLM-4-9B-0414\n\n| Precision | #GPUs | Memory Usage | First Token Latency | Token Output Speed | Input Tokens |\n|-----------|-------|---------------|----------------------|---------------------|---------------|\n| BF16      | 1     | 19 GB         | 0.05s                | 44.4 tokens/s       | 1000          |\n| BF16      | 1     | 25 GB         | 0.39s                | 39.0 tokens/s       | 8000          |\n| BF16      | 1     | 31 GB         | 2.29s                | 18.7 tokens/s       | 32000         |\n| BF16      | 1     | 55 GB         | 6.80s                | 14.1 tokens/s       | 100000        |\n\n#### GLM-4-9B-Chat-1M\n\n| Precision | #GPUs | Memory Usage | First Token Latency | Token Output Speed | Input Tokens |\n|-----------|-------|---------------|----------------------|---------------------|---------------|\n| BF16      | 1     | 75 GB         | 98.4s                | 2.3 tokens/s        | 200000        |\n\n#### GLM-4V-9B\n\n| Precision | #GPUs | Memory Usage | First Token Latency | Token Output Speed | Input Tokens |\n|-----------|-------|---------------|----------------------|---------------------|---------------|\n| BF16      | 1     | 28 GB         | 0.1s                 | 33.4 tokens/s       | 1000          |\n| BF16      | 1     | 33 GB         | 0.7s                 | 39.2 tokens/s       | 8000          |\n\n| Precision | #GPUs | Memory Usage | First Token Latency | Token Output Speed | Input Tokens |\n|-----------|-------|---------------|----------------------|---------------------|---------------|\n| INT4      | 1     | 10 GB         | 0.1s                 | 28.7 tokens/s       | 1000          |\n| INT4      | 1     | 15 GB         | 0.8s                 | 24.2 tokens/s       | 8000          |\n\n## Quick Start\n\n### Use transformers backend code\n\n+ Use the command line to communicate with the GLM-4-9B model.\n\n```shell\npython trans_cli_demo.py # LLM Such as GLM-4-9B-0414\npython trans_cli_vision_demo.py # GLM-4V-9B\n```\n\n+ Use the Gradio web client to communicate with the  GLM-4-9B model.\n\n```shell\npython trans_web_demo.py  # LLM Such as GLM-4-9B-0414\npython trans_web_vision_demo.py # GLM-4V-9B\n```\n\n+ Use Batch inference.\n\n```shell\npython trans_batch_demo.py  # LLM Such as GLM-4-9B-0414\n```\n\n### Use vLLM backend code\n\n+ Use the command line to communicate with the GLM-4-9B-Chat model.\n\n```shell\npython vllm_cli_demo.py  # LLM Such as GLM-4-9B-0414\n```\n\n+ Launch an OpenAI-compatible API service.\n\n```shell\nvllm serve THUDM/GLM-4-9B-0414 --tensor_parallel_size 2\n```\n\n### Use glm-4v to build an OpenAI-compatible service\n\nStart the server:\n\n```shell\npython glm4v_server.py THUDM/glm-4v-9b\n```\n\nClient request:\n\n```shell\npython glm4v_api_request.py\n```\n\n## Stress test\n\nUsers can use this code to test the generation speed of the model on the transformers backend on their own devices:\n\n```shell\npython trans_stress_test.py\n```\n\nThe stress test script supports enabling **SwanLab** to track the stress testing process and record metrics:\n\n```shell\n# The API Key can be obtained by logging in to https://swanlab.cn/\npython trans_stress_test.py --swanlab_api_key \"Your SwanLab API Key\"\n```\n\nUsing the --swanlab_api_key local parameter enables SwanLab's local mode.\n\n## Use Ascend card to run code\n\nUsers can run the above code in the Ascend hardware environment. They only need to change the transformers to openmind and the cuda device in device to npu.\n\n```shell\n#from transformers import AutoModelForCausalLM, AutoTokenizer\nfrom openmind import AutoModelForCausalLM, AutoTokenizer\n\n#device = 'cuda'\ndevice = 'npu'\n```\n"
  },
  {
    "path": "inference/README_zh.md",
    "content": "# Inference\n\nRead this in [English](README.md)\n\n请严格按照文档的步骤进行操作，以避免不必要的错误。\n\n## 设备和依赖检查\n\n### 安装依赖\n\n```shell\npip install -r requirements.txt\n```\n\n### 相关推理测试数据\n\n**本文档的数据均在以下硬件环境测试,实际运行环境需求和运行占用的显存略有不同，请以实际运行环境为准。**\n\n测试硬件信息:\n\n+ OS: Ubuntu 22.04\n+ Memory: 512GB\n+ Python: 3.12.3\n+ CUDA Version:  12.4\n+ Cmake 3.23.0\n+ GPU Driver: 535.104.05\n+ GPU: NVIDIA H100 80GB HBM3 * 8\n\n推理的压力测试数据如下，如有多张显卡，则显存占用代表显存占用最大一张显卡的显存消耗。\n\n#### GLM-4-32B-0414\n\n| 精度   | 显卡数量 | 显存占用  | 首 Token 延迟 | Token 输出速度    | 输入token数 |\n|------|------|-------|------------|---------------|----------|\n| BF16 | 1    | 68 GB | 0.16s      | 24.4 tokens/s | 1000     |\n| BF16 | 1    | 72 GB | 1.37s      | 16.9 tokens/s | 8000     |\n| BF16 | 2    | 50 GB | 6.75s      | 8.1 tokens/s  | 32000    |\n| BF16 | 4    | 55 GB | 37.83s     | 3.0 tokens/s  | 100000   |\n\n#### GLM-4-9B-0414\n\n| 精度   | 显卡数量 | 显存占用  | 首 Token 延迟 | Token 输出速度    | 输入token数 |\n|------|------|-------|------------|---------------|---------|\n| BF16 | 1    | 19 GB | 0.05s      | 44.4 tokens/s | 1000    |\n| BF16 | 1    | 25 GB | 0.39s      | 39.0 tokens/s | 8000    |\n| BF16 | 1    | 31 GB | 2.29s      | 18.7 tokens/s | 32000   |\n| BF16 | 1    | 55 GB | 6.80s      | 14.1 tokens/s  | 100000  |\n\n\n#### GLM-4-9B-Chat-1M\n\n| 精度     | 显卡数量 | 显存占用  | 首 Token 延迟 | Token 输出速度    | 输入token数 |\n|--------|------|------|------------|--------------|-------------|\n| BF16 | 1    | 75 GB | 98.4s      | 2.3 tokens/s | 200000 |\n\n#### GLM-4V-9B\n\n| 精度     | 显卡数量 | 显存占用  | 首 Token 延迟 | Token 输出速度    | 输入token数 |\n|--------|------|------|------------|--------------|-------------|\n| BF16 | 1    | 28 GB | 0.1s       | 33.4 tokens/s | 1000 |\n| BF16 | 1    | 33 GB | 0.7s       | 39.2 tokens/s | 8000 |\n\n| 精度     | 显卡数量  | 显存占用   | 首 Token 延迟 | Token 输出速度    | 输入token数 |\n|--------|-------|--------|------------|--------------|-------------|\n| INT4 | 1     | 10 GB  | 0.1s       | 28.7 tokens/s |  1000 |\n| INT4 | 1     | 15 GB  | 0.8s       | 24.2 tokens/s |  8000 |\n\n## 快速开始\n\n### 使用 transformers 后端代码\n\n+ 使用命令行与 GLM-4-9B 模型进行对话。\n\n```shell\npython trans_cli_demo.py # LLM Such as GLM-4-9B-0414\npython trans_cli_vision_demo.py # GLM-4V-9B\n```\n\n+ 使用 Gradio 网页端与 GLM-4-9B 模型进行对话。\n\n```shell\npython trans_web_demo.py  # LLM Such as GLM-4-9B-0414\npython trans_web_vision_demo.py # GLM-4V-9B\n```\n\n+ 使用 Batch 推理。\n\n```shell\npython trans_batch_demo.py\n```\n\n### 使用 vLLM 后端代码\n\n+ 使用命令行与 GLM-4-9B-Chat 模型进行对话。\n\n```shell\npython vllm_cli_demo.py # LLM Such as GLM-4-9B-0414\n```\n\n+ 构建 OpenAI 类 API 服务。\n```shell\nvllm serve THUDM/GLM-4-9B-0414 --tensor_parallel_size 2\n```\n\n### 使用 glm-4v 构建 OpenAI 服务\n\n启动服务端\n\n```shell\npython glm4v_server.py THUDM/glm-4v-9b\n```\n\n客户端请求：\n\n```shell\npython glm4v_api_request.py\n```\n\n## 压力测试\n\n用户可以在自己的设备上使用本代码测试模型在 transformers后端的生成速度:\n\n```shell\npython trans_stress_test.py\n```\n\n## 压力测试\n\n用户可以在自己的设备上使用本代码测试模型在 transformers后端的生成速度:\n\n```shell\npython trans_stress_test.py\n```\n\n压力测试脚本支持开启**SwanLab**来跟踪压力测试过程和记录指标：\n\n```shell\n# API Key 可通过登录https://swanlab.cn/获取\npython trans_stress_test.py --swanlab_api_key \"SwanLab的API Key\"\n\n```\n使用`--swanlab_api_key local`参数可开启SwanLab本地模式\n\n## 使用昇腾NPU运行代码\n\n用户可以在昇腾硬件环境下运行以上代码，只需将transformers修改为openmind，将device中的cuda设备修改为npu：\n\n```shell\n#from transformers import AutoModelForCausalLM, AutoTokenizer\nfrom openmind import AutoModelForCausalLM, AutoTokenizer\n\n#device = 'cuda'\ndevice = 'npu'\n```\n"
  },
  {
    "path": "inference/glm4v_api_request.py",
    "content": "\"\"\"\nThis script creates a OpenAI Request demo for the glm-4v-9b model, just Use OpenAI API to interact with the model.\nFor LLM such as GLM-4-9B-0414, using with vLLM OpenAI Server.\n\nvllm serve THUDM/GLM-4-32B-0414 --tensor_parallel_size 4\n\n\"\"\"\n\nimport base64\n\nfrom openai import OpenAI\n\n\nbase_url = \"http://127.0.0.1:8000/v1/\"\nclient = OpenAI(api_key=\"EMPTY\", base_url=base_url)\n\n\ndef create_chat_completion(messages, use_stream=False):\n    response = client.chat.completions.create(\n        model=\"glm-4v\",\n        messages=messages,\n        stream=use_stream,\n        max_tokens=256,\n        temperature=0.4,\n        presence_penalty=1.2,\n        top_p=0.8,\n    )\n    if response:\n        if use_stream:\n            for chunk in response:\n                print(chunk)\n        else:\n            print(response)\n    else:\n        print(\"Error:\", response.status_code)\n\n\ndef encode_image(image_path):\n    \"\"\"\n    Encodes an image file into a base64 string.\n    Args:\n        image_path (str): The path to the image file.\n\n    This function opens the specified image file, reads its content, and encodes it into a base64 string.\n    The base64 encoding is used to send images over HTTP as text.\n    \"\"\"\n\n    with open(image_path, \"rb\") as image_file:\n        return base64.b64encode(image_file.read()).decode(\"utf-8\")\n\n\ndef glm4v_simple_image_chat(use_stream=False, img_path=None):\n    \"\"\"\n    Facilitates a simple chat interaction involving an image.\n\n    Args:\n        use_stream (bool): Specifies whether to use streaming for chat responses.\n        img_path (str): Path to the image file to be included in the chat.\n\n    This function encodes the specified image and constructs a predefined conversation involving the image.\n    It then calls `create_chat_completion` to generate a response from the model.\n    The conversation includes asking about the content of the image and a follow-up question.\n    \"\"\"\n\n    img_url = f\"data:image/jpeg;base64,{encode_image(img_path)}\"\n    messages = [\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"text\",\n                    \"text\": \"What’s in this image?\",\n                },\n                {\n                    \"type\": \"image_url\",\n                    \"image_url\": {\"url\": img_url},\n                },\n            ],\n        },\n        {\n            \"role\": \"assistant\",\n            \"content\": \"The image displays a wooden boardwalk extending through a vibrant green grassy wetland. The sky is partly cloudy with soft, wispy clouds, indicating nice weather. Vegetation is seen on either side of the boardwalk, and trees are present in the background, suggesting that this area might be a natural reserve or park designed for ecological preservation and outdoor recreation. The boardwalk allows visitors to explore the area without disturbing the natural habitat.\",\n        },\n        {\"role\": \"user\", \"content\": \"Do you think this is a spring or winter photo?\"},\n    ]\n    create_chat_completion(messages=messages, use_stream=use_stream)\n\n\nif __name__ == \"__main__\":\n    glm4v_simple_image_chat(use_stream=False, img_path=\"demo.jpg\")\n"
  },
  {
    "path": "inference/glm4v_server.py",
    "content": "import base64\nimport gc\nimport sys\nimport threading\nimport time\nfrom contextlib import asynccontextmanager\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import List, Literal, Optional, Tuple, Union\n\nimport requests\nimport torch\nimport uvicorn\nfrom fastapi import FastAPI, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom peft import PeftModelForCausalLM\nfrom PIL import Image\nfrom pydantic import BaseModel, Field\nfrom sse_starlette.sse import EventSourceResponse\nfrom transformers import AutoModel, AutoTokenizer, TextIteratorStreamer\n\n\nTORCH_TYPE = (\n    torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16\n)\n\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    \"\"\"\n    An asynchronous context manager for managing the lifecycle of the FastAPI app.\n    It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.\n    \"\"\"\n    yield\n    if torch.cuda.is_available():\n        torch.cuda.empty_cache()\n        torch.cuda.ipc_collect()\n\n\napp = FastAPI(lifespan=lifespan)\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"*\"],\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\n\nclass ModelCard(BaseModel):\n    \"\"\"\n    A Pydantic model representing a model card, which provides metadata about a machine learning model.\n    It includes fields like model ID, owner, and creation time.\n    \"\"\"\n\n    id: str\n    object: str = \"model\"\n    created: int = Field(default_factory=lambda: int(time.time()))\n    owned_by: str = \"owner\"\n    root: Optional[str] = None\n    parent: Optional[str] = None\n    permission: Optional[list] = None\n\n\nclass ModelList(BaseModel):\n    object: str = \"list\"\n    data: List[ModelCard] = []\n\n\nclass ImageUrl(BaseModel):\n    url: str\n\n\nclass TextContent(BaseModel):\n    type: Literal[\"text\"]\n    text: str\n\n\nclass ImageUrlContent(BaseModel):\n    type: Literal[\"image_url\"]\n    image_url: ImageUrl\n\n\nContentItem = Union[TextContent, ImageUrlContent]\n\n\nclass ChatMessageInput(BaseModel):\n    role: Literal[\"user\", \"assistant\", \"system\"]\n    content: Union[str, List[ContentItem]]\n    name: Optional[str] = None\n\n\nclass ChatMessageResponse(BaseModel):\n    role: Literal[\"assistant\"]\n    content: str = None\n    name: Optional[str] = None\n\n\nclass DeltaMessage(BaseModel):\n    role: Optional[Literal[\"user\", \"assistant\", \"system\"]] = None\n    content: Optional[str] = None\n\n\nclass ChatCompletionRequest(BaseModel):\n    model: str\n    messages: List[ChatMessageInput]\n    temperature: Optional[float] = 0.8\n    top_p: Optional[float] = 0.8\n    max_tokens: Optional[int] = None\n    stream: Optional[bool] = False\n    # Additional parameters\n    repetition_penalty: Optional[float] = 1.0\n\n\nclass ChatCompletionResponseChoice(BaseModel):\n    index: int\n    message: ChatMessageResponse\n\n\nclass ChatCompletionResponseStreamChoice(BaseModel):\n    index: int\n    delta: DeltaMessage\n\n\nclass UsageInfo(BaseModel):\n    prompt_tokens: int = 0\n    total_tokens: int = 0\n    completion_tokens: Optional[int] = 0\n\n\nclass ChatCompletionResponse(BaseModel):\n    model: str\n    object: Literal[\"chat.completion\", \"chat.completion.chunk\"]\n    choices: List[Union[ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice]]\n    created: Optional[int] = Field(default_factory=lambda: int(time.time()))\n    usage: Optional[UsageInfo] = None\n\n\n@app.get(\"/v1/models\", response_model=ModelList)\nasync def list_models():\n    \"\"\"\n    An endpoint to list available models. It returns a list of model cards.\n    This is useful for clients to query and understand what models are available for use.\n    \"\"\"\n    model_card = ModelCard(id=\"GLM-4v-9b\")\n    return ModelList(data=[model_card])\n\n\n@app.post(\"/v1/chat/completions\", response_model=ChatCompletionResponse)\nasync def create_chat_completion(request: ChatCompletionRequest):\n    global model, tokenizer\n\n    if len(request.messages) < 1 or request.messages[-1].role == \"assistant\":\n        raise HTTPException(status_code=400, detail=\"Invalid request\")\n\n    gen_params = dict(\n        messages=request.messages,\n        temperature=request.temperature,\n        top_p=request.top_p,\n        max_tokens=request.max_tokens or 1024,\n        echo=False,\n        stream=request.stream,\n        repetition_penalty=request.repetition_penalty,\n    )\n\n    if request.stream:\n        generate = predict(request.model, gen_params)\n        return EventSourceResponse(generate, media_type=\"text/event-stream\")\n    response = generate_glm4v(model, tokenizer, gen_params)\n\n    usage = UsageInfo()\n\n    message = ChatMessageResponse(\n        role=\"assistant\",\n        content=response[\"text\"],\n    )\n    choice_data = ChatCompletionResponseChoice(\n        index=0,\n        message=message,\n    )\n    task_usage = UsageInfo.model_validate(response[\"usage\"])\n    for usage_key, usage_value in task_usage.model_dump().items():\n        setattr(usage, usage_key, getattr(usage, usage_key) + usage_value)\n    return ChatCompletionResponse(model=request.model, choices=[choice_data], object=\"chat.completion\", usage=usage)\n\n\ndef predict(model_id: str, params: dict):\n    global model, tokenizer\n\n    choice_data = ChatCompletionResponseStreamChoice(index=0, delta=DeltaMessage(role=\"assistant\"), finish_reason=None)\n    chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object=\"chat.completion.chunk\")\n    yield \"{}\".format(chunk.model_dump_json(exclude_unset=True))\n\n    previous_text = \"\"\n    for new_response in generate_stream_glm4v(model, tokenizer, params):\n        decoded_unicode = new_response[\"text\"]\n        delta_text = decoded_unicode[len(previous_text) :]\n        previous_text = decoded_unicode\n        delta = DeltaMessage(content=delta_text, role=\"assistant\")\n        choice_data = ChatCompletionResponseStreamChoice(index=0, delta=delta)\n        chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object=\"chat.completion.chunk\")\n        yield \"{}\".format(chunk.model_dump_json(exclude_unset=True))\n\n    choice_data = ChatCompletionResponseStreamChoice(index=0, delta=DeltaMessage())\n    chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object=\"chat.completion.chunk\")\n    yield \"{}\".format(chunk.model_dump_json(exclude_unset=True))\n\n\ndef generate_glm4v(model: AutoModel, tokenizer: AutoTokenizer, params: dict):\n    \"\"\"\n    Generates a response using the GLM-4v-9b model. It processes the chat history and image data, if any,\n    and then invokes the model to generate a response.\n    \"\"\"\n\n    response = None\n\n    for response in generate_stream_glm4v(model, tokenizer, params):\n        pass\n    return response\n\n\ndef process_history_and_images(\n    messages: List[ChatMessageInput],\n) -> Tuple[Optional[str], Optional[List[Tuple[str, str]]], Optional[List[Image.Image]]]:\n    \"\"\"\n    Process history messages to extract text, identify the last user query,\n    and convert base64 encoded image URLs to PIL images.\n\n    Args:\n        messages(List[ChatMessageInput]): List of ChatMessageInput objects.\n    return: A tuple of three elements:\n             - The last user query as a string.\n             - Text history formatted as a list of tuples for the model.\n             - List of PIL Image objects extracted from the messages.\n    \"\"\"\n\n    formatted_history = []\n    image_list = []\n    last_user_query = \"\"\n\n    for i, message in enumerate(messages):\n        role = message.role\n        content = message.content\n\n        if isinstance(content, list):  # text\n            text_content = \" \".join(item.text for item in content if isinstance(item, TextContent))\n        else:\n            text_content = content\n\n        if isinstance(content, list):  # image\n            for item in content:\n                if isinstance(item, ImageUrlContent):\n                    image_url = item.image_url.url\n                    if image_url.startswith(\"data:image/jpeg;base64,\"):\n                        base64_encoded_image = image_url.split(\"data:image/jpeg;base64,\")[1]\n                        image_data = base64.b64decode(base64_encoded_image)\n                        image = Image.open(BytesIO(image_data)).convert(\"RGB\")\n                    else:\n                        response = requests.get(image_url, verify=False)\n                        image = Image.open(BytesIO(response.content)).convert(\"RGB\")\n                    image_list.append(image)\n\n        if role == \"user\":\n            if i == len(messages) - 1:  # 最后一条用户消息\n                last_user_query = text_content\n            else:\n                formatted_history.append((text_content, \"\"))\n        elif role == \"assistant\":\n            if formatted_history:\n                if formatted_history[-1][1] != \"\":\n                    assert False, f\"the last query is answered. answer again. {formatted_history[-1][0]}, {formatted_history[-1][1]}, {text_content}\"\n                formatted_history[-1] = (formatted_history[-1][0], text_content)\n            else:\n                assert False, \"assistant reply before user\"\n        else:\n            assert False, f\"unrecognized role: {role}\"\n\n    return last_user_query, formatted_history, image_list\n\n\n@torch.inference_mode()\ndef generate_stream_glm4v(model: AutoModel, tokenizer: AutoTokenizer, params: dict):\n    uploaded = False\n    messages = params[\"messages\"]\n    temperature = float(params.get(\"temperature\", 1.0))\n    repetition_penalty = float(params.get(\"repetition_penalty\", 1.0))\n    top_p = float(params.get(\"top_p\", 1.0))\n    max_new_tokens = int(params.get(\"max_tokens\", 256))\n    query, history, image_list = process_history_and_images(messages)\n\n    inputs = []\n    for idx, (user_msg, model_msg) in enumerate(history):\n        if idx == len(history) - 1 and not model_msg:\n            inputs.append({\"role\": \"user\", \"content\": user_msg})\n            if image_list and not uploaded:\n                inputs[-1].update({\"image\": image_list[0]})\n                uploaded = True\n            break\n        if user_msg:\n            inputs.append({\"role\": \"user\", \"content\": user_msg})\n        if model_msg:\n            inputs.append({\"role\": \"assistant\", \"content\": model_msg})\n    if len(image_list) >= 1:\n        inputs.append({\"role\": \"user\", \"content\": query, \"image\": image_list[0]})\n    else:\n        inputs.append({\"role\": \"user\", \"content\": query})\n\n    model_inputs = tokenizer.apply_chat_template(\n        inputs, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n    ).to(next(model.parameters()).device)\n\n    input_echo_len = len(model_inputs[\"input_ids\"][0])\n    streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)\n    gen_kwargs = {\n        \"repetition_penalty\": repetition_penalty,\n        \"max_new_tokens\": max_new_tokens,\n        \"do_sample\": True if temperature > 1e-5 else False,\n        \"top_p\": top_p if temperature > 1e-5 else 0,\n        \"top_k\": 1,\n        \"streamer\": streamer,\n        \"eos_token_id\": [151329, 151336, 151338],\n    }\n    if temperature > 1e-5:\n        gen_kwargs[\"temperature\"] = temperature\n\n    generated_text = \"\"\n\n    def generate_text():\n        with torch.no_grad():\n            model.generate(**model_inputs, **gen_kwargs)\n\n    generation_thread = threading.Thread(target=generate_text)\n    generation_thread.start()\n\n    total_len = input_echo_len\n    for next_text in streamer:\n        generated_text += next_text\n        total_len = len(tokenizer.encode(generated_text))\n        yield {\n            \"text\": generated_text,\n            \"usage\": {\n                \"prompt_tokens\": input_echo_len,\n                \"completion_tokens\": total_len - input_echo_len,\n                \"total_tokens\": total_len,\n            },\n        }\n    generation_thread.join()\n    print(\"\\033[91m--generated_text\\033[0m\", generated_text)\n    yield {\n        \"text\": generated_text,\n        \"usage\": {\n            \"prompt_tokens\": input_echo_len,\n            \"completion_tokens\": total_len - input_echo_len,\n            \"total_tokens\": total_len,\n        },\n    }\n\n\ngc.collect()\ntorch.cuda.empty_cache()\n\nif __name__ == \"__main__\":\n    MODEL_PATH = sys.argv[1]\n    model_dir = Path(MODEL_PATH).expanduser().resolve()\n    if (model_dir / \"adapter_config.json\").exists():\n        import json\n\n        with open(model_dir / \"adapter_config.json\", \"r\", encoding=\"utf-8\") as file:\n            config = json.load(file)\n        model = AutoModel.from_pretrained(\n            config.get(\"base_model_name_or_path\"), device_map=\"auto\", torch_dtype=TORCH_TYPE\n        )\n        model = PeftModelForCausalLM.from_pretrained(\n            model=model,\n            model_id=model_dir,\n        )\n        tokenizer = AutoTokenizer.from_pretrained(config.get(\"base_model_name_or_path\"), encode_special_tokens=True)\n        model.eval()\n    else:\n        tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, encode_special_tokens=True)\n        model = AutoModel.from_pretrained(\n            MODEL_PATH,\n            torch_dtype=TORCH_TYPE,\n            device_map=\"auto\",\n        ).eval()\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000, workers=1)\n"
  },
  {
    "path": "inference/requirements.txt",
    "content": "torch>=2.6.0\ntorchvision>=0.21.0\ntransformers>=4.51.3\nsentencepiece>=0.2.0\njinja2>=3.1.4\npydantic>=2.11.1\ntimm>=1.0.15\ntiktoken>=0.9.0\nnumpy<2\naccelerate>=1.6.0\nsentence_transformers>=3.1.1\ngradio>=5.23.3\nopenai>=1.70.0\neinops>=0.8.0\npillow>=10.4.0\nsse-starlette>=2.1.3\nbitsandbytes>=0.44.1 # INT4 Loading, Not support for NPU\npeft>=0.15.0 # Using with finetune model\nswanlab>=0.5.5\n\n# git+https://github.com/vllm-project/vllm.git For vLLM\n"
  },
  {
    "path": "inference/trans_batch_demo.py",
    "content": "\"\"\"\n\nHere is an example of using batch request GLM-4-0414 Models and glm-4-9b-chat-hf models with the transformers library.,\nhere you need to build the conversation format yourself and then call the batch function to make batch requests.\nPlease note that in this demo, the memory consumption is significantly higher.\n\n\"\"\"\n\nfrom typing import Union\n\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, LogitsProcessorList\n\n\nMODEL_PATH = \"THUDM/GLM-4-9B-0414\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)\nmodel = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map=\"auto\").eval()\n\n\ndef process_model_outputs(inputs, outputs, tokenizer):\n    responses = []\n    for input_ids, output_ids in zip(inputs.input_ids, outputs):\n        response = tokenizer.decode(output_ids[len(input_ids) :], skip_special_tokens=True).strip()\n        responses.append(response)\n    return responses\n\n\ndef batch(\n    model,\n    tokenizer,\n    messages: Union[str, list[str]],\n    max_input_tokens: int = 8192,\n    max_new_tokens: int = 8192,\n    num_beams: int = 1,\n    do_sample: bool = True,\n    top_p: float = 0.8,\n    temperature: float = 0.8,\n    logits_processor=None,\n):\n    if logits_processor is None:\n        logits_processor = LogitsProcessorList()\n    messages = [messages] if isinstance(messages, str) else messages\n    batched_inputs = tokenizer(\n        messages, return_tensors=\"pt\", padding=\"max_length\", truncation=True, max_length=max_input_tokens\n    ).to(model.device)\n\n    gen_kwargs = {\n        \"max_new_tokens\": max_new_tokens,\n        \"num_beams\": num_beams,\n        \"do_sample\": do_sample,\n        \"top_p\": top_p,\n        \"temperature\": temperature,\n        \"logits_processor\": logits_processor,\n        \"eos_token_id\": model.config.eos_token_id,\n    }\n    batched_outputs = model.generate(**batched_inputs, **gen_kwargs)\n    batched_response = process_model_outputs(batched_inputs, batched_outputs, tokenizer)\n    return batched_response\n\n\nif __name__ == \"__main__\":\n    batch_message = [\n        [\n            {\"role\": \"user\", \"content\": \"我的爸爸和妈妈结婚为什么不能带我去\"},\n            {\"role\": \"assistant\", \"content\": \"因为他们结婚时你还没有出生\"},\n            {\"role\": \"user\", \"content\": \"我刚才的提问是\"},\n        ],\n        [{\"role\": \"user\", \"content\": \"你好，你是谁\"}],\n    ]\n\n    batch_inputs = []\n    max_input_tokens = 128\n    for i, messages in enumerate(batch_message):\n        new_batch_input = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)[12:]\n        max_input_tokens = max(max_input_tokens, len(new_batch_input))\n        batch_inputs.append(new_batch_input)\n    gen_kwargs = {\n        \"max_input_tokens\": max_input_tokens,\n        \"max_new_tokens\": 256,\n        \"do_sample\": True,\n        \"top_p\": 0.8,\n        \"temperature\": 0.8,\n        \"num_beams\": 1,\n    }\n\n    batch_responses = batch(model, tokenizer, batch_inputs, **gen_kwargs)\n    for response in batch_responses:\n        print(\"=\" * 10)\n        print(response)\n"
  },
  {
    "path": "inference/trans_cli_demo.py",
    "content": "\"\"\"\nThis script creates a CLI demo with transformers backend for the glm-4-9b-chat model,\nallowing users to interact with the model through a command-line interface.\n\nUsage:\n- Run the script to start the CLI demo.\n- Interact with the model by typing questions and receiving responses.\n\nNote: The script includes a modification to handle markdown to plain text conversion,\nensuring that the CLI interface displays formatted text correctly.\n\nIf you use flash attention, you should install the flash-attn and  add attn_implementation=\"flash_attention_2\" in model loading.\n\n\"\"\"\n\nfrom threading import Thread\n\nimport torch\nfrom transformers import (\n    AutoModelForCausalLM,\n    AutoTokenizer,\n    StoppingCriteria,\n    StoppingCriteriaList,\n    TextIteratorStreamer,\n)\n\n\nMODEL_PATH = \"THUDM/GLM-4-9B-0414\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    MODEL_PATH,\n    torch_dtype=torch.bfloat16,\n    device_map=\"auto\",\n).eval()\n\n\nclass StopOnTokens(StoppingCriteria):\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        stop_ids = model.config.eos_token_id\n        for stop_id in stop_ids:\n            if input_ids[0][-1] == stop_id:\n                return True\n        return False\n\n\nif __name__ == \"__main__\":\n    history = []\n    max_length = 8192\n    top_p = 0.8\n    temperature = 0.6\n    stop = StopOnTokens()\n\n    print(\"Welcome to the GLM-4-9B CLI chat. Type your messages below.\")\n    while True:\n        user_input = input(\"\\nYou: \")\n        if user_input.lower() in [\"exit\", \"quit\"]:\n            break\n        history.append([user_input, \"\"])\n\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"content\": model_msg})\n        model_inputs = tokenizer.apply_chat_template(\n            messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors=\"pt\"\n        ).to(model.device)\n        streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True)\n        generate_kwargs = {\n            \"input_ids\": model_inputs[\"input_ids\"],\n            \"attention_mask\": model_inputs[\"attention_mask\"],\n            \"streamer\": streamer,\n            \"max_new_tokens\": max_length,\n            \"do_sample\": True,\n            \"top_p\": top_p,\n            \"temperature\": temperature,\n            \"stopping_criteria\": StoppingCriteriaList([stop]),\n            \"repetition_penalty\": 1.2,\n            \"eos_token_id\": model.config.eos_token_id,\n        }\n        t = Thread(target=model.generate, kwargs=generate_kwargs)\n        t.start()\n        print(\"GLM-4:\", end=\"\", flush=True)\n        for new_token in streamer:\n            if new_token:\n                print(new_token, end=\"\", flush=True)\n                history[-1][1] += new_token\n\n        history[-1][1] = history[-1][1].strip()\n"
  },
  {
    "path": "inference/trans_cli_vision_demo.py",
    "content": "\"\"\"\nThis script creates a CLI demo with transformers backend for the glm-4v-9b model,\nallowing users to interact with the model through a command-line interface.\n\nUsage:\n- Run the script to start the CLI demo.\n- Interact with the model by typing questions and receiving responses.\n\nNote: The script includes a modification to handle markdown to plain text conversion,\nensuring that the CLI interface displays formatted text correctly.\n\"\"\"\n\nfrom threading import Thread\n\nimport torch\nfrom PIL import Image\nfrom transformers import (\n    AutoModel,\n    AutoTokenizer,\n    StoppingCriteria,\n    StoppingCriteriaList,\n    TextIteratorStreamer,\n)\n\n\nMODEL_PATH = \"THUDM/glm-4v-9b\"\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True, encode_special_tokens=True)\n\n## For BF16 inference\nmodel = AutoModel.from_pretrained(\n    MODEL_PATH,\n    trust_remote_code=True,\n    torch_dtype=torch.bfloat16,\n    device_map=\"auto\",\n).eval()\n\n## For INT4 inference\n# model = AutoModel.from_pretrained(\n#     MODEL_PATH,\n#     trust_remote_code=True,\n#     quantization_config=BitsAndBytesConfig(load_in_4bit=True),\n#     torch_dtype=torch.bfloat16,\n#     low_cpu_mem_usage=True\n# ).eval()\n\n\nclass StopOnTokens(StoppingCriteria):\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        stop_ids = model.config.eos_token_id\n        for stop_id in stop_ids:\n            if input_ids[0][-1] == stop_id:\n                return True\n        return False\n\n\nif __name__ == \"__main__\":\n    history = []\n    max_length = 1024\n    top_p = 0.8\n    temperature = 0.6\n    stop = StopOnTokens()\n    uploaded = False\n    image = None\n    print(\"Welcome to the GLM-4-9B CLI chat. Type your messages below.\")\n    image_path = input(\"Image Path:\")\n    try:\n        image = Image.open(image_path).convert(\"RGB\")\n    except:\n        print(\"Invalid image path. Continuing with text conversation.\")\n    while True:\n        user_input = input(\"\\nYou: \")\n        if user_input.lower() in [\"exit\", \"quit\"]:\n            break\n        history.append([user_input, \"\"])\n\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n                if image and not uploaded:\n                    messages[-1].update({\"image\": image})\n                    uploaded = True\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"content\": model_msg})\n        model_inputs = tokenizer.apply_chat_template(\n            messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n        ).to(next(model.parameters()).device)\n        streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True)\n        generate_kwargs = {\n            **model_inputs,\n            \"streamer\": streamer,\n            \"max_new_tokens\": max_length,\n            \"do_sample\": True,\n            \"top_p\": top_p,\n            \"temperature\": temperature,\n            \"stopping_criteria\": StoppingCriteriaList([stop]),\n            \"repetition_penalty\": 1.2,\n            \"eos_token_id\": [151329, 151336, 151338],\n        }\n        t = Thread(target=model.generate, kwargs=generate_kwargs)\n        t.start()\n        print(\"GLM-4V:\", end=\"\", flush=True)\n        for new_token in streamer:\n            if new_token:\n                print(new_token, end=\"\", flush=True)\n                history[-1][1] += new_token\n\n        history[-1][1] = history[-1][1].strip()\n"
  },
  {
    "path": "inference/trans_stress_test.py",
    "content": "import argparse\nimport datetime\nimport time\nfrom threading import Thread\n\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n\n\nMODEL_PATH = \"THUDM/GLM-4-9B-0414\"\n\n\ndef stress_test(run_name, input_token_len, n, output_token_len, swanlab_api_key):\n    tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, paddsing_side=\"left\")\n    model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, torch_dtype=torch.bfloat16, device_map=\"auto\").eval()\n    device = model.device\n\n    # Use INT4 weight infer\n    # model = AutoModelForCausalLM.from_pretrained(\n    #     MODEL_PATH,\n    #     trust_remote_code=True,\n    #     quantization_config=BitsAndBytesConfig(load_in_4bit=True),\n    #     low_cpu_mem_usage=True,\n    # ).eval()\n\n    # Enable SwanLab if swanlab_api_key available\n    if swanlab_api_key:\n        import swanlab\n\n        print(\"Enable swanlab logging...\")\n        if not args.swanlab_api_key == \"local\":\n            swanlab.login(api_key=args.swanlab_api_key)\n        current_time = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n        run_name = run_name if run_name else f'{MODEL_PATH.split(\"/\")[-1]}_{current_time}'\n        config = {\n            \"model\": model.config.to_dict(),\n            \"generation_config\": model.generation_config.to_dict(),\n            \"input_token_len\": input_token_len,\n            \"n\": n,\n            \"output_token_len\": output_token_len,\n            \"device\": str(model.device),\n        }\n        swanlab.init(\n            project=\"glm-stress-test\",\n            name=run_name,\n            config=config,\n            mode=\"local\" if args.swanlab_api_key == \"local\" else None,\n        )\n\n    times = []\n    decode_times = []\n\n    print(\"Warming up...\")\n    vocab_size = tokenizer.vocab_size\n    warmup_token_len = 20\n    random_token_ids = torch.randint(3, vocab_size - 200, (warmup_token_len - 5,), dtype=torch.long)\n    start_tokens = [151331, 151333, 151336, 198]\n    end_tokens = [151337]\n    input_ids = (\n        torch.tensor(start_tokens + random_token_ids.tolist() + end_tokens, dtype=torch.long).unsqueeze(0).to(device)\n    )\n    attention_mask = torch.ones_like(input_ids, dtype=torch.bfloat16).to(device)\n    position_ids = torch.arange(len(input_ids[0]), dtype=torch.bfloat16).unsqueeze(0).to(device)\n    warmup_inputs = {\"input_ids\": input_ids, \"attention_mask\": attention_mask, \"position_ids\": position_ids}\n    with torch.no_grad():\n        _ = model.generate(\n            input_ids=warmup_inputs[\"input_ids\"],\n            attention_mask=warmup_inputs[\"attention_mask\"],\n            max_new_tokens=512,\n            do_sample=False,\n            repetition_penalty=0.1,\n            eos_token_id=[151329, 151336, 151338],\n        )\n    print(\"Warming up complete. Starting stress test...\")\n\n    for i in range(n):\n        random_token_ids = torch.randint(3, vocab_size - 200, (input_token_len - 5,), dtype=torch.long)\n        input_ids = (\n            torch.tensor(start_tokens + random_token_ids.tolist() + end_tokens, dtype=torch.long)\n            .unsqueeze(0)\n            .to(device)\n        )\n        attention_mask = torch.ones_like(input_ids, dtype=torch.bfloat16).to(device)\n        position_ids = torch.arange(len(input_ids[0]), dtype=torch.bfloat16).unsqueeze(0).to(device)\n        test_inputs = {\"input_ids\": input_ids, \"attention_mask\": attention_mask, \"position_ids\": position_ids}\n\n        streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=36000, skip_prompt=True, skip_special_tokens=True)\n\n        generate_kwargs = {\n            \"input_ids\": test_inputs[\"input_ids\"],\n            \"attention_mask\": test_inputs[\"attention_mask\"],\n            \"max_new_tokens\": output_token_len,\n            \"do_sample\": False,\n            \"repetition_penalty\": 0.1,  # For generate more tokens for test.\n            \"eos_token_id\": [151329, 151336, 151338],\n            \"streamer\": streamer,\n        }\n\n        start_time = time.time()\n        t = Thread(target=model.generate, kwargs=generate_kwargs)\n        t.start()\n\n        first_token_time = None\n        all_token_times = []\n\n        for token in streamer:\n            current_time = time.time()\n            if first_token_time is None:\n                first_token_time = current_time\n                times.append(first_token_time - start_time)\n            all_token_times.append(current_time)\n\n        t.join()\n        end_time = time.time()\n\n        avg_decode_time_per_token = len(all_token_times) / (end_time - first_token_time) if all_token_times else 0\n        decode_times.append(avg_decode_time_per_token)\n        print(\n            f\"Iteration {i + 1}/{n} - Prefilling Time: {times[-1]:.4f} seconds - Average Decode Time: {avg_decode_time_per_token:.4f} tokens/second\"\n        )\n        if swanlab_api_key:\n            swanlab.log(\n                {\n                    \"Iteration\": i + 1,\n                    \"Iteration/Prefilling Time (seconds)\": times[-1],\n                    \"Iteration/Decode Time (tokens per second)\": avg_decode_time_per_token,\n                    \"Iteration/Input token Len\": len(test_inputs[\"input_ids\"][0]),\n                    \"Iteration/Output token Len\": len(all_token_times),\n                    \"Average First Token Time (seconds)\": sum(times) / (i + 1),\n                    \"Average Decode Time (tokens per second)\": sum(decode_times) / (i + 1),\n                }\n            )\n        torch.cuda.empty_cache()\n\n    avg_first_token_time = sum(times) / n\n    avg_decode_time = sum(decode_times) / n\n    print(f\"\\nAverage First Token Time over {n} iterations: {avg_first_token_time:.4f} seconds\")\n    print(f\"Average Decode Time per Token over {n} iterations: {avg_decode_time:.4f} tokens/second\")\n    return times, avg_first_token_time, decode_times, avg_decode_time\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Stress test for model inference\")\n    parser.add_argument(\"--run_name\", type=str, default=None, help=\"Number of tokens for each test\")\n    parser.add_argument(\"--input_token_len\", type=int, default=100000, help=\"Number of tokens for each test\")\n    parser.add_argument(\"--output_token_len\", type=int, default=128, help=\"Number of output tokens for each test\")\n    parser.add_argument(\"--n\", type=int, default=3, help=\"Number of iterations for the stress test\")\n    parser.add_argument(\"--swanlab_api_key\", type=str, default=None, help=\"Enable swanlab logging if API key provided\")\n    args = parser.parse_args()\n    stress_test(args.run_name, args.input_token_len, args.n, args.output_token_len, args.swanlab_api_key)\n"
  },
  {
    "path": "inference/trans_web_demo.py",
    "content": "from threading import Thread\n\nimport gradio as gr\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n\n\nMODEL_PATH = \"THUDM/GLM-4-9B-0414\"\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)\nmodel = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map=\"auto\")\n\n\ndef preprocess_messages(history, system_prompt):\n    messages = []\n\n    if system_prompt:\n        messages.append({\"role\": \"system\", \"content\": system_prompt})\n\n    for idx, (user_msg, model_msg) in enumerate(history):\n        if idx == len(history) - 1 and not model_msg:\n            messages.append({\"role\": \"user\", \"content\": user_msg})\n            break\n        if user_msg:\n            messages.append({\"role\": \"user\", \"content\": user_msg})\n        if model_msg:\n            messages.append({\"role\": \"assistant\", \"content\": model_msg})\n\n    return messages\n\n\ndef predict(history, system_prompt, max_length, top_p, top_k, temperature):\n    messages = preprocess_messages(history, system_prompt)\n    model_inputs = tokenizer.apply_chat_template(\n        messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n    ).to(model.device)\n    streamer = TextIteratorStreamer(tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True)\n    generate_kwargs = {\n        \"input_ids\": model_inputs[\"input_ids\"],\n        \"attention_mask\": model_inputs[\"attention_mask\"],\n        \"streamer\": streamer,\n        \"max_new_tokens\": max_length,\n        \"do_sample\": True,\n        \"top_p\": top_p,\n        \"top_k\": top_k,\n        \"temperature\": temperature,\n        \"repetition_penalty\": 1.2,\n    }\n\n    generate_kwargs[\"eos_token_id\"] = tokenizer.encode(\"<|user|>\")\n\n    t = Thread(target=model.generate, kwargs=generate_kwargs)\n    t.start()\n    for new_token in streamer:\n        if new_token:\n            history[-1][1] += new_token\n        yield history\n\n\ndef main():\n    with gr.Blocks() as demo:\n        gr.HTML(\"\"\"<h1 align=\"center\">GLM-4-0414 Gradio Demo</h1>\"\"\")\n\n        with gr.Row():\n            with gr.Column(scale=3):\n                system_prompt = gr.Textbox(\n                    show_label=True, placeholder=\"Enter system prompt here...\", label=\"System Prompt\", lines=2\n                )\n\n        with gr.Row():\n            with gr.Column(scale=3):\n                chatbot = gr.Chatbot()\n\n        with gr.Row():\n            with gr.Column(scale=2):\n                user_input = gr.Textbox(show_label=True, placeholder=\"Input...\", label=\"User Input\")\n                submitBtn = gr.Button(\"Submit\")\n                emptyBtn = gr.Button(\"Clear History\")\n            with gr.Column(scale=1):\n                max_length = gr.Slider(0, 8192, value=4096, step=1.0, label=\"Maximum length\", interactive=True)\n                top_p = gr.Slider(0, 1, value=0.8, step=0.01, label=\"Top P\", interactive=True)\n                top_k = gr.Slider(0, 100, value=50, step=1, label=\"Top K\", interactive=True)\n                temperature = gr.Slider(0.01, 1, value=0.6, step=0.01, label=\"Temperature\", interactive=True)\n\n        def user(query, history):\n            return \"\", history + [[query, \"\"]]\n\n        def clear_history():\n            return None\n\n        submitBtn.click(user, [user_input, chatbot], [user_input, chatbot], queue=False).then(\n            predict, [chatbot, system_prompt, max_length, top_p, top_k, temperature], chatbot\n        )\n        emptyBtn.click(clear_history, None, [chatbot], queue=False)\n\n    demo.queue()\n    demo.launch()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "inference/trans_web_vision_demo.py",
    "content": "\"\"\"\nThis script creates a Gradio demo with a Transformers backend for the glm-4v-9b model, allowing users to interact with the model through a Gradio web UI.\n\nUsage:\n- Run the script to start the Gradio server.\n- Interact with the model via the web UI.\n\nRequirements:\n- Gradio package\n  - Type `pip install gradio==4.44.1` to install Gradio.\n\"\"\"\n\nimport os\nfrom io import BytesIO\nfrom threading import Thread\n\nimport gradio as gr\nimport requests\nimport torch\nfrom PIL import Image\nfrom transformers import AutoModel, AutoTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer\n\n\nMODEL_PATH = os.environ.get(\"MODEL_PATH\", \"THUDM/glm-4v-9b\")\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True, encode_special_tokens=True)\nmodel = AutoModel.from_pretrained(\n    MODEL_PATH, trust_remote_code=True, device_map=\"auto\", torch_dtype=torch.bfloat16\n).eval()\n\n\nclass StopOnTokens(StoppingCriteria):\n    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n        stop_ids = model.config.eos_token_id\n        for stop_id in stop_ids:\n            if input_ids[0][-1] == stop_id:\n                return True\n        return False\n\n\ndef get_image(image_path=None, image_url=None):\n    if image_path:\n        return Image.open(image_path).convert(\"RGB\")\n    elif image_url:\n        response = requests.get(image_url)\n        return Image.open(BytesIO(response.content)).convert(\"RGB\")\n    return None\n\n\ndef chatbot(image_path=None, image_url=None, assistant_prompt=\"\"):\n    image = get_image(image_path, image_url)\n\n    messages = [{\"role\": \"assistant\", \"content\": assistant_prompt}, {\"role\": \"user\", \"content\": \"\", \"image\": image}]\n\n    model_inputs = tokenizer.apply_chat_template(\n        messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n    ).to(next(model.parameters()).device)\n\n    streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True)\n\n    generate_kwargs = {\n        **model_inputs,\n        \"streamer\": streamer,\n        \"max_new_tokens\": 1024,\n        \"do_sample\": True,\n        \"top_p\": 0.8,\n        \"temperature\": 0.6,\n        \"stopping_criteria\": StoppingCriteriaList([StopOnTokens()]),\n        \"repetition_penalty\": 1.2,\n        \"eos_token_id\": [151329, 151336, 151338],\n    }\n\n    t = Thread(target=model.generate, kwargs=generate_kwargs)\n    t.start()\n\n    response = \"\"\n    for new_token in streamer:\n        if new_token:\n            response += new_token\n\n    return image, response.strip()\n\n\nwith gr.Blocks() as demo:\n    demo.title = \"GLM-4V-9B Image Recognition Demo\"\n    demo.description = \"\"\"\n    This demo uses the GLM-4V-9B model to got image infomation.\n    \"\"\"\n    with gr.Row():\n        with gr.Column():\n            image_path_input = gr.File(label=\"Upload Image (High-Priority)\", type=\"filepath\")\n            image_url_input = gr.Textbox(label=\"Image URL (Low-Priority)\")\n            assistant_prompt_input = gr.Textbox(label=\"Assistant Prompt (You Can Change It)\", value=\"这是什么？\")\n            submit_button = gr.Button(\"Submit\")\n        with gr.Column():\n            chatbot_output = gr.Textbox(label=\"GLM-4V-9B Model Response\")\n            image_output = gr.Image(label=\"Image Preview\")\n\n    submit_button.click(\n        chatbot,\n        inputs=[image_path_input, image_url_input, assistant_prompt_input],\n        outputs=[image_output, chatbot_output],\n    )\n\ndemo.launch(server_name=\"127.0.0.1\", server_port=8911, inbrowser=True, share=False)\n"
  },
  {
    "path": "inference/vllm_cli_demo.py",
    "content": "\"\"\"\nThis script creates a CLI demo with vllm backand for the glm-4-9b model,\nallowing users to interact with the model through a command-line interface.\n\nUsage:\n- Run the script to start the CLI demo.\n- Interact with the model by typing questions and receiving responses.\n\nNote: The script includes a modification to handle markdown to plain text conversion,\nensuring that the CLI interface displays formatted text correctly.\n\"\"\"\n\nimport asyncio\nimport time\nfrom typing import Dict, List\n\nfrom transformers import AutoTokenizer\nfrom vllm import AsyncEngineArgs, AsyncLLMEngine, SamplingParams\nfrom vllm.lora.request import LoRARequest\n\n\nMODEL_PATH = \"THUDM/GLM-4-9B-0414\"\nLORA_PATH = \"\"\n\n\ndef load_model_and_tokenizer(model_dir: str, enable_lora: bool):\n    tokenizer = AutoTokenizer.from_pretrained(model_dir)\n\n    engine_args = AsyncEngineArgs(\n        model=model_dir,\n        tokenizer=model_dir,\n        enable_lora=enable_lora,\n        tensor_parallel_size=1,\n        dtype=\"bfloat16\",\n        gpu_memory_utilization=0.9,\n        disable_log_requests=True,\n    )\n\n    engine = AsyncLLMEngine.from_engine_args(engine_args)\n    return engine, tokenizer\n\n\nenable_lora = False\nif LORA_PATH:\n    enable_lora = True\n\nengine, tokenizer = load_model_and_tokenizer(MODEL_PATH, enable_lora)\n\n\nasync def vllm_gen(\n    lora_path: str,\n    enable_lora: bool,\n    messages: List[Dict[str, str]],\n    top_p: float,\n    temperature: float,\n    max_dec_len: int,\n):\n    inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)\n    params_dict = {\n        \"n\": 1,\n        \"best_of\": 1,\n        \"presence_penalty\": 1.0,\n        \"frequency_penalty\": 0.0,\n        \"temperature\": temperature,\n        \"top_p\": top_p,\n        \"max_tokens\": max_dec_len,\n        \"skip_special_tokens\": True,\n    }\n    sampling_params = SamplingParams(**params_dict)\n    if enable_lora:\n        async for output in engine.generate(\n            prompt=inputs,\n            sampling_params=sampling_params,\n            request_id=f\"{time.time()}\",\n            lora_request=LoRARequest(\"glm-4-lora\", 1, lora_path=lora_path),\n        ):\n            yield output.outputs[0].text\n    else:\n        async for output in engine.generate(\n            prompt=inputs, sampling_params=sampling_params, request_id=f\"{time.time()}\"\n        ):\n            yield output.outputs[0].text\n\n\nasync def chat():\n    history = []\n    max_length = 8192\n    top_p = 0.8\n    temperature = 0.6\n\n    print(\"Welcome to the GLM-4-9B CLI chat. Type your messages below.\")\n    while True:\n        user_input = input(\"\\nYou: \")\n        if user_input.lower() in [\"exit\", \"quit\"]:\n            break\n        history.append([user_input, \"\"])\n\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"content\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"content\": model_msg})\n\n        print(\"\\nGLM-4: \", end=\"\")\n        current_length = 0\n        output = \"\"\n        async for output in vllm_gen(LORA_PATH, enable_lora, messages, top_p, temperature, max_length):\n            print(output[current_length:], end=\"\", flush=True)\n            current_length = len(output)\n        history[-1][1] = output\n\n\nif __name__ == \"__main__\":\n    asyncio.run(chat())\n"
  },
  {
    "path": "inference/vllm_cli_vision_demo.py",
    "content": "\"\"\"\nThis script creates a CLI demo with vllm backand for the glm-4v-9b model,\nallowing users to interact with the model through a command-line interface.\n\nUsage:\n- Run the script to start the CLI demo.\n- Interact with the model by typing questions and receiving responses.\n\nNote: The script includes a modification to handle markdown to plain text conversion,\nensuring that the CLI interface displays formatted text correctly.\n\"\"\"\n\nimport asyncio\nimport time\nfrom typing import Dict, List\n\nfrom PIL import Image\nfrom vllm import AsyncEngineArgs, AsyncLLMEngine, SamplingParams\n\n\nMODEL_PATH = \"THUDM/glm-4v-9b\"\n\n\ndef load_model_and_tokenizer(model_dir: str):\n    engine_args = AsyncEngineArgs(\n        model=model_dir,\n        tokenizer=model_dir,\n        tensor_parallel_size=1,\n        dtype=\"bfloat16\",\n        gpu_memory_utilization=0.9,\n        enforce_eager=True,\n        disable_log_requests=True,\n    )\n    engine = AsyncLLMEngine.from_engine_args(engine_args)\n    return engine\n\n\nengine = load_model_and_tokenizer(MODEL_PATH)\n\n\nasync def vllm_gen(messages: List[Dict[str, str]], top_p: float, temperature: float, max_dec_len: int):\n    inputs = messages[-1]\n    params_dict = {\n        \"n\": 1,\n        \"best_of\": 1,\n        \"presence_penalty\": 1.0,\n        \"frequency_penalty\": 0.0,\n        \"temperature\": temperature,\n        \"top_p\": top_p,\n        \"max_tokens\": max_dec_len,\n        \"skip_special_tokens\": True,\n    }\n    sampling_params = SamplingParams(**params_dict)\n\n    async for output in engine.generate(prompt=inputs, sampling_params=sampling_params, request_id=f\"{time.time()}\"):\n        yield output.outputs[0].text\n\n\nasync def chat():\n    history = []\n    max_length = 8192\n    top_p = 0.8\n    temperature = 0.6\n    image = None\n\n    print(\"Welcome to the GLM-4v-9B CLI chat. Type your messages below.\")\n    image_path = input(\"Image Path:\")\n    try:\n        image = Image.open(image_path).convert(\"RGB\")\n    except:\n        print(\"Invalid image path. Continuing with text conversation.\")\n    while True:\n        user_input = input(\"\\nYou: \")\n        if user_input.lower() in [\"exit\", \"quit\"]:\n            break\n        history.append([user_input, \"\"])\n\n        messages = []\n        for idx, (user_msg, model_msg) in enumerate(history):\n            if idx == len(history) - 1 and not model_msg:\n                messages.append(\n                    {\n                        \"prompt\": user_msg,\n                        \"multi_modal_data\": {\"image\": image},\n                    }\n                )\n                break\n            if user_msg:\n                messages.append({\"role\": \"user\", \"prompt\": user_msg})\n            if model_msg:\n                messages.append({\"role\": \"assistant\", \"prompt\": model_msg})\n\n        print(\"\\nGLM-4v: \", end=\"\")\n        current_length = 0\n        output = \"\"\n        async for output in vllm_gen(messages, top_p, temperature, max_length):\n            print(output[current_length:], end=\"\", flush=True)\n            current_length = len(output)\n        history[-1][1] = output\n\n\nif __name__ == \"__main__\":\n    asyncio.run(chat())\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.ruff]\nline-length = 119\n\n[tool.ruff.lint]\n# Never enforce `E501` (line length violations).\nignore = [\"C901\", \"E501\", \"E741\", \"F402\", \"F823\"]\nselect = [\"C\", \"E\", \"F\", \"I\", \"W\"]\n\n# Ignore import violations in all `__init__.py` files.\n[tool.ruff.lint.per-file-ignores]\n\"__init__.py\" = [\"E402\", \"F401\", \"F403\", \"F811\"]\n\n[tool.ruff.lint.isort]\nlines-after-imports = 2\n\n[tool.ruff.format]\n# Like Black, use double quotes for strings.\nquote-style = \"double\"\n\n# Like Black, indent with spaces, rather than tabs.\nindent-style = \"space\"\n\n# Like Black, respect magic trailing commas.\nskip-magic-trailing-comma = false\n\n# Like Black, automatically detect the appropriate line ending.\nline-ending = \"auto\"\n"
  },
  {
    "path": "resources/WECHAT.md",
    "content": "<div align=\"center\">\n<img src=wechat.jpg width=\"60%\"/>\n\n<p> 扫码加入「GLM-4交流群」 </p>\n<p> Scan the QR code to follow to join the \"ChatGLM Discussion Group\" </p>\n</div>\n"
  }
]