Ubuntu commited on
Commit
892e231
1 Parent(s): 41ece54
.gitattributes CHANGED
@@ -1,35 +1,47 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
  *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
11
  *.model filter=lfs diff=lfs merge=lfs -text
12
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
13
  *.onnx filter=lfs diff=lfs merge=lfs -text
14
  *.ot filter=lfs diff=lfs merge=lfs -text
15
  *.parquet filter=lfs diff=lfs merge=lfs -text
16
  *.pb filter=lfs diff=lfs merge=lfs -text
 
 
17
  *.pt filter=lfs diff=lfs merge=lfs -text
18
  *.pth filter=lfs diff=lfs merge=lfs -text
19
  *.rar filter=lfs diff=lfs merge=lfs -text
 
20
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
22
  *.tflite filter=lfs diff=lfs merge=lfs -text
23
  *.tgz filter=lfs diff=lfs merge=lfs -text
 
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *.tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ *.db* filter=lfs diff=lfs merge=lfs -text
29
+ *.ark* filter=lfs diff=lfs merge=lfs -text
30
+ **/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
31
+ **/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
32
+ **/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
33
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
34
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
35
+ *.gguf* filter=lfs diff=lfs merge=lfs -text
36
+ *.ggml filter=lfs diff=lfs merge=lfs -text
37
+ *.llamafile* filter=lfs diff=lfs merge=lfs -text
38
+ *.pt2 filter=lfs diff=lfs merge=lfs -text
39
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
40
+ *.npy filter=lfs diff=lfs merge=lfs -text
41
+ *.npz filter=lfs diff=lfs merge=lfs -text
42
+ *.pickle filter=lfs diff=lfs merge=lfs -text
43
+ *.pkl filter=lfs diff=lfs merge=lfs -text
44
+ *.tar filter=lfs diff=lfs merge=lfs -text
45
+ *.wasm filter=lfs diff=lfs merge=lfs -text
46
  *.zst filter=lfs diff=lfs merge=lfs -text
47
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The CogAgent License
2
+
3
+ 1. Definitions
4
+
5
+ "Licensor" refers to the CogAgent model team distributing its software.
6
+ "Software" refers to the CogAgent model parameters provided under this license.
7
+
8
+ 2. License Grant
9
+
10
+ Subject to the terms and conditions of this license, the Licensor hereby grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license.
11
+ This license permits you to use all open-source models in this repository for free for academic research purposes. Users wishing to use the model for commercial purposes must complete registration [here](https://open.bigmodel.cn/mla/form). Registered users may use the model for commercial activities free of charge but must comply with all terms and conditions of this license.
12
+ The above copyright statement and this license statement must be included in all copies or significant portions of the software.
13
+ If you distribute or provide materials from THUDM/Zhipu AI regarding the CogAgent open-source model (or any derivative works thereof) or use any materials (including all open-source models in the CogAgent series) in products or services, you must:
14
+
15
+ (A) Provide a copy of this agreement with any such materials from THUDM/Zhipu AI;
16
+ (B) Prominently display “Built with CogAgent” on relevant websites, user interfaces, blog posts, about pages, or product documentation.
17
+ If you use materials from THUDM/Zhipu AI's CogAgent open-source model to create, train, fine-tune, or otherwise improve distributed or publicly available AI models, you must also prepend “CogAgent” to the names of any such AI models.
18
+
19
+ 3. Restrictions
20
+
21
+ You must comply with applicable laws, regulations, ethical standards, and other requirements in your jurisdiction when using this software. You must independently obtain permissions, licenses, or other access rights required by third-party software/applications and make prudent and independent judgments on all operational decisions. You must not use the software or implement the following actions in an improper manner:
22
+ (1) Use, copy, modify, merge, publish, distribute, or create derivative works of this software, in whole or in part, for any military or illegal purposes;
23
+ (2) Engage in activities that harm national security, public interest, social morals, or infringe upon others' trade secrets, intellectual property, reputation, portrait rights, property rights, or other rights and interests;
24
+ (3) Use the software for fraud, phishing, spamming, misleading, bullying, harassment, discrimination, hate promotion, or dissemination of false information;
25
+ (4) Use the software to make automated high-risk decisions in fields such as health, education, credit, finance, or critical infrastructure management, which significantly impact individual or societal safety, rights, or welfare;
26
+ (5) Rely on the software to perform major operations, including but not limited to monetary transactions, large purchases, placing irreversible orders, or publishing content detrimental to others' rights or social ethics;
27
+ (6) Use the software in services requiring subject qualifications or professional review, or as a substitute for professional services in fields such as medicine, law, journalism, education, or financial investment;
28
+ (7) Use the software dishonestly, claim or imply AI-generated content is human-created, or disguise human-created works as AI-generated content;
29
+ (8) Engage in illegal network intrusion, disrupt normal network functionality, steal network data, or deliberately spread malicious programs or viruses that harm network security and order;
30
+ (9) Collect personal information unlawfully or use the software in a way that infringes upon any third party’s personal information protection rights or privacy.
31
+ The Licensor bears no responsibility for your actions while using this software, and you shall assume all resulting liabilities.
32
+
33
+ 4. Disclaimer
34
+
35
+ The software is provided "as is" without any express or implied warranties, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement.
36
+ The Licensor does not guarantee the content or operations executed by the software are entirely accurate, reliable, functional, timely, secure, error-free, uninterrupted, or continuously stable. The Licensor is not liable for risks arising from your operational errors or software defects.
37
+ In no event shall the authors or copyright holders be liable for any claims, damages, or other liabilities, whether in contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software.
38
+
39
+ 5. Limitation of Liability
40
+
41
+ To the maximum extent permitted by applicable law, in no event and under no legal theory shall the Licensor be liable for any direct, indirect, special, incidental, exemplary, or consequential damages, or any other commercial losses, even if the Licensor has been advised of the possibility of such damages.
42
+
43
+ 6. Dispute Resolution
44
+
45
+ This license is governed by and construed in accordance with the laws of the People's Republic of China. Any disputes arising out of or in connection with this license shall be submitted to the People's Court of Haidian District, Beijing.
46
+ Please note that this license may be updated to a more comprehensive version. For any questions about the license or copyright, please contact us at [email protected] or [email protected].
47
+
48
+ CogAgent系列模型开源协议
49
+
50
+ 1. 定义
51
+
52
+ “许可方”是指分发其软件的 CogAgent系列 模型团队。
53
+ “软件”是指根据本许可提供的 CogAgent系列 模型参数。
54
+
55
+ 2. 许可授予
56
+
57
+ 根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
58
+ 本许可仅允许您免费使用本仓库中的所有开源模型进行学术研究,对于希望将模型用于商业目的的用户,需在[这里](https://open.bigmodel.cn/mla/form)完成登记。经过登记的用户可以免费使用本模型进行商业活动,但必须遵守本许可的所有条款和条件。
59
+ 上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
60
+ 如果您分发或提供 THUDM / 智谱AI 关于 CogAgent系列开源模型的材料(或其任何衍生作品),或使用其中任何材料(包括 CogAgent系列的所有开源模型)的产品或服务,您应:
61
+
62
+ (A) 随任何此类 THUDM / 智谱AI 材料提供本协议的副本;
63
+ (B) 在相关网站、用户界面、博客文章、关于页面或产品文档上突出显示 “Built with CogAgent”。
64
+ 如果您使用 THUDM / 智谱AI的 CogAgent系列开源模型的材料来创建、训练、微调或以其他方式改进已分发或可用的 AI 模型,您还应在任何此类 AI 模型名称的开头添加 “CogAgent”。
65
+
66
+ 3. 限制
67
+
68
+ 您在使用中应遵循使用地所适用的法律法规政策、道德规范等要求,在操作应用程序时自行取得第三方软件/应用所需的操作权限、授权或其他准入要求并对所有操作决策进行独立审慎的判断。您不得以以下不当方式使用软件或利用软件实施以下行为:
69
+ (1) 出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品;
70
+ (2) 利用本软件从事任何危害国家安全和国家统一,危害社会公共利益及公序良俗,侵犯他人商业秘密、知识产权、名誉权、肖像权、财产权等权益的行为;
71
+ (3) 用于欺诈、诈骗、发送垃圾短信/邮件、误导、欺凌、骚扰、歧视、宣扬仇恨、传播虚假信息等途径;
72
+ (4) 利用软件实施任何决策行为,如在健康、教育、信贷、金融、关键基础设施管理等对个人及社会的安全、权利或福祉有重大影响的领域做出高风险的自动化决策;
73
+ (5) 依赖本软件执行任何重大的操作,包括但不限于资金交易、大额消费、下单不可撤销的订单、发布有损他人权益或社会公德的消息等;
74
+ (6) 用于任何对主体资格有要求或需要专业人员审查的服务中,或作为专业服务的替代品,包括但不限于医疗、律师、新闻、教育、投资理财等专业领域;
75
+ (7) 以不诚实的方式使用,主张或声称人工智能的生成物是人类的作品,或将人类的作品伪装为人工智能的生成物;
76
+ (8) 非法侵入网络、干扰网络正常功能、窃取网络数据、故意传播恶意程序或病毒等危害网络安全和网络秩序的活动;
77
+ (9) 违法采集他人个人信息,或以可能侵犯任何第三方个人信息保护权及隐私的方式使用本软件。
78
+ 许可方不对您使用本软件的行为承担任何责任,由此产生的责任将由您自行承担。
79
+
80
+ 4. 免责声明
81
+
82
+ 本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。
83
+ 许可方不保证软件生成的内容及执行的操作百分百准确可靠、功能可用、及时、安全、无错误、不受干扰、无中断、持续稳定、不存在任何故障,AI并不能真正像人类一样理解您输入的内容及指令,如果由于您的操作失误或AI的缺陷导致的风险,许可方不承担相应的责任。
84
+ 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,包括但不限于由软件或软件的使用引起、利用软件进行的交易或与软件相关引起的问题。
85
+
86
+ 5. 责任限制
87
+
88
+ 除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、
89
+ 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
90
+
91
+ 6. 争议解决
92
+
93
+ 本许可受中华人民共和国法律管辖并按其解释。 因本许可引���的或与本许可有关的任何争议应提交北京市海淀区人民法院。
94
+ 请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 [email protected][email protected] 与我们联系。
README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - zh
5
+ - en
6
+ base_model:
7
+ - THUDM/glm-4v-9b
8
+ pipeline_tag: image-text-to-text
9
+ library_name: transformers
10
+ ---
11
+
12
+ # CogAgent
13
+
14
+ ## 关于模型
15
+
16
+ `cogagent-9b-20241220` 是 我们基于 [GLM-4V-9B](https://huggingface.co/THUDM/glm-4v-9b) 训练得到的一个专门用于 Agent任务的模型。
17
+ `cogagent-9b-20241220` 是一款较为先进的智能体模型,它具备强大的跨平台兼容性,能够实现对多种计算设备上的图形界面进行自动化的操作。
18
+ 无论是Windows、macOS还是Android系统,`cogagent-9b-20241220` 都能够接收用户指令,自动获取设备屏幕截图,经过模型推理后执行自动化设备操作。
19
+
20
+ ## 运行模型
21
+
22
+ 请前往我们的[github](https://github.com/THUDM/CogAgent) 查看具体的运行示例。
23
+
24
+ ## 输入和输出
25
+
26
+ cogagent-9b-20241220是一个Agent类执行模型而非对话模型,不支持连续对话,但是但支持连续的执行历史。
27
+ 这里展示了用户应该怎么整理自己的输入格式化的传入给模型。并获得模型规则的回复。
28
+
29
+ ### 用户输入部分
30
+
31
+ 1. `task` 字段
32
+
33
+ 用户输入的任务描述,类似文本格式的prompt,该输入可以指导 CogAgent1.5 模型完成用户任务指令。请保证简洁明了。
34
+
35
+ 2. `platform` 字段
36
+
37
+ CogAgent1.5 支持在多个平台上执行可操作Agent功能, 我们支持的带有图形界面的操作系统有三个系统,
38
+ - Windows 10,11,请使用 `WIN` 字段。
39
+ - Mac 14,15,请使用 `MAC` 字段。
40
+ - Android 13,14,15 以及其他GUI和UI操作方式几乎相同的安卓UI发行版,请使用 `Mobile` 字段。
41
+
42
+ 如果您使用的是其他系统,效果可能不佳,但可以尝试使用 `Mobile` 字段用于手机设备,`WIN` 字段用于Windows设备,`MAC`
43
+ 字段用于Mac设备。
44
+
45
+ 3. `format` 字段
46
+
47
+ 用户希望 CogAgent1.5 返回何种格式的数据, 这里有以下几种选项:
48
+ - `Answer in Action-Operation-Sensitive format.`: 本仓库中demo默认使用的返回方式,返回模型的行为,对应的操作,以及对应的敏感程度。
49
+ - `Answer in Status-Plan-Action-Operation format.`: 返回模型的装题,行为,以及相应的操作。
50
+ - `Answer in Status-Action-Operation-Sensitive format.`: 返回模型的状态,行为,对应的操作,以及对应的敏感程度。
51
+ - `Answer in Status-Action-Operation format.`: 返回模型的状态,行为。
52
+ - `Answer in Action-Operation format.` 返回模型的行为,对应的操作。
53
+
54
+ 4. `history` 字段
55
+
56
+ 拼接顺序和结果应该如下所示:
57
+ ```
58
+ query = f'{task}{history}{platform}{format}'
59
+ ```
60
+
61
+ ### 模型返回部分
62
+
63
+ 1. 敏感操作: 包括 `<<敏感操作>> <<一般操作>>` 几种类型,只有要求返回`Sensitive`的时候返回。
64
+ 2. `Plan`, `Agent`, `Status`, `Action` 字段: 用于描述模型的行为和操作。只有要求返回对应字段的时候返回,例如带有`Action`则返回
65
+ `Action`字段内容。
66
+ 3. 常规回答部分,这部分回答会在格式化回答之前,表示综述。
67
+ 4. `Grounded Operation` 字段:
68
+ 用于描述模型的具体操作,包括操作的位置,类型,以及具体的操作内容。其中 `box` 代表执行区域的坐标,`element_type` 代表执行的元素类型,
69
+ `element_info` 代表执行的元素描述。这些信息被一个 `操作指令` 操作所包裹。这些指令包括:
70
+ - `CLICK`: 点击操作,模拟鼠标点击或者手指触摸。
71
+ - `LONGPRESS`: 长案操作。仅在 `Mobile` 模式下支持。
72
+
73
+ ### 例子
74
+
75
+ 用户的任务是希望帮忙将所有邮件标记为已读,用户使用的是 Mac系统,希望返回的是Action-Operation-Sensitive格式。
76
+ 正确拼接后的提示词应该为:
77
+
78
+ ```
79
+ Task: 帮我将所有的邮件标注为已读
80
+ (Platform: Mac)
81
+ (Answer in Action-Operation-Sensitive format.)
82
+ ```
83
+
84
+ 接着,这里展现了不同格式要求下的返回结果:
85
+
86
+
87
+ <details>
88
+ <summary>Answer in Action-Operation-Sensitive format</summary>
89
+
90
+ ```
91
+ Action: 点击页面顶部工具栏中的“全部标为已读”按钮,将所有邮件标记为已读。
92
+ Grounded Operation: CLICK(box=[[219,186,311,207]], element_type='可点击文本', element_info='全部标为已读')
93
+ <<一般操作>>
94
+ ```
95
+
96
+ </details>
97
+
98
+ <details>
99
+ <summary>Answer in Status-Plan-Action-Operation format</summary>
100
+
101
+ ```
102
+ Status: None
103
+ Plan: None.
104
+ Action: 点击收件箱页面顶部中间的“全部标记为已读”按钮,将所有邮件标记为已读。
105
+ Grounded Operation: CLICK(box=[[219,186,311,207]], element_type='可点击文本', element_info='全部标为已读')
106
+ ```
107
+
108
+ </details>
109
+
110
+ <details>
111
+ <summary>Answer in Status-Action-Operation-Sensitive format</summary>
112
+
113
+ ```
114
+ Status: 当前处于邮箱界面[[0, 2, 998, 905]],左侧是邮箱分类[[1, 216, 144, 570]],中间是收件箱[[144, 216, 998, 903]],已经点击“全部标为已读”按钮[[223, 178, 311, 210]]。
115
+ Action: 点击页面顶部工具栏中的“全部标为已读”按钮,将所有邮件标记为已读。
116
+ Grounded Operation: CLICK(box=[[219,186,311,207]], element_type='可点击文本', element_info='全部标为已读')
117
+ <<一般操作>>
118
+ ```
119
+
120
+ </details>
121
+
122
+ <details>
123
+ <summary>Answer in Status-Action-Operation format</summary>
124
+
125
+ ```
126
+ Status: None
127
+ Action: 在收件箱页面顶部,点击“全部标记为已读”按钮,将所有邮件标记为已读。
128
+ Grounded Operation: CLICK(box=[[219,186,311,207]], element_type='可点击文本', element_info='全部标为已读')
129
+ ```
130
+
131
+ </details>
132
+
133
+ <details>
134
+ <summary>Answer in Action-Operation format</summary>
135
+
136
+ ```
137
+ Action: 在左侧邮件列表中,右键单击第一封邮件,以打开操作菜单。
138
+ Grounded Operation: RIGHT_CLICK(box=[[154,275,343,341]], element_info='[AXCell]')
139
+ ```
140
+
141
+ </details>
142
+
143
+ ### 注意事项
144
+
145
+ 1. 该模型不是对话模型,不支持连续对话,请发送具体指令,并参考我们提供的历史拼接方式进行拼接。
146
+ 2. 该模型必须要有图片传入,纯文字对话无法实现GUI Agent任务。
147
+ 3. 该模型输出有严格的格式要求,请严格按照我们的要求进行解析。输出格式为 STR 格式,不支持输出JSON 格式。
148
+
149
+
150
+ ## 先前的工作
151
+
152
+ 在2023年11月,我们发布了CogAgent的第一代模型,现在,你可以在 [CogVLM&CogAgent官方仓库](https://github.com/THUDM/CogVLM)
153
+ 找到相关代码和权重地址。
154
+
155
+ <div align="center">
156
+ <img src=assets/cogagent_function_cn.jpg width=70% />
157
+ </div>
158
+
159
+ <table>
160
+ <tr>
161
+ <td>
162
+ <h2> CogVLM </h2>
163
+ <p> 📖 Paper: <a href="https://arxiv.org/abs/2311.03079">CogVLM: Visual Expert for Pretrained Language Models</a></p>
164
+ <p><b>CogVLM</b> 是一个强大的开源视觉语言模型(VLM)。CogVLM-17B拥有100亿的视觉参数和70亿的语言参数,支持490*490分辨率的图像理解和多轮对话。</p>
165
+ <p><b>CogVLM-17B 17B在10个经典的跨模态基准测试中取得了最先进的性能</b>包括NoCaps, Flicker30k captioning, RefCOCO, RefCOCO+, RefCOCOg, Visual7W, GQA, ScienceQA, VizWiz VQA 和 TDIUC 基准测试。</p>
166
+ </td>
167
+ <td>
168
+ <h2> CogAgent </h2>
169
+ <p> 📖 Paper: <a href="https://arxiv.org/abs/2312.08914">CogAgent: A Visual Language Model for GUI Agents </a></p>
170
+ <p><b>CogAgent</b> 是一个基于CogVLM改进的开源视觉语言模型。CogAgent-18B拥有110亿的视觉参数和70亿的语言参数, <b>支持1120*1120分辨率的图像理解。在CogVLM的能力之上,它进一步拥有了GUI图像Agent的能力。</b></p>
171
+ <p> <b>CogAgent-18B 在9个经典的跨模态基准测试中实现了最先进的通用性能,</b>包括 VQAv2, OK-VQ, TextVQA, ST-VQA, ChartQA, infoVQA, DocVQA, MM-Vet, 和 POPE 测试基准。它在包括AITW和Mind2Web在内的GUI操作数据集上显著超越了现有的模型。</p>
172
+ </td>
173
+ </tr>
174
+ </table>
175
+
176
+ ## 协议
177
+
178
+ 模型权重的使用请遵循 [Model License](LICENSE)。
config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/cogagent-9b-20241220",
3
+ "add_bias_linear": false,
4
+ "add_qkv_bias": true,
5
+ "apply_query_key_layer_scaling": true,
6
+ "apply_residual_connection_post_layernorm": false,
7
+ "architectures": [
8
+ "ChatGLMForConditionalGeneration"
9
+ ],
10
+ "attention_dropout": 0.0,
11
+ "attention_softmax_in_fp32": true,
12
+ "auto_map": {
13
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
14
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
15
+ "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
16
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
17
+ "AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
18
+ },
19
+ "bias_dropout_fusion": true,
20
+ "boi_token_id": 151339,
21
+ "classifier_dropout": null,
22
+ "eoi_token_id": 151340,
23
+ "eos_token_id": [
24
+ 151329,
25
+ 151336,
26
+ 151338
27
+ ],
28
+ "ffn_hidden_size": 13696,
29
+ "fp32_residual_connection": false,
30
+ "hidden_dropout": 0.0,
31
+ "hidden_size": 4096,
32
+ "kv_channels": 128,
33
+ "layernorm_epsilon": 1e-05,
34
+ "model_type": "chatglm",
35
+ "multi_query_attention": true,
36
+ "multi_query_group_num": 2,
37
+ "num_attention_heads": 32,
38
+ "num_layers": 40,
39
+ "original_rope": false,
40
+ "pad_token_id": 151329,
41
+ "padded_vocab_size": 151552,
42
+ "post_layer_norm": true,
43
+ "pre_seq_len": null,
44
+ "prefix_projection": false,
45
+ "rmsnorm": true,
46
+ "rope_ratio": 1,
47
+ "rotary_percent": 0.5,
48
+ "seq_length": 8192,
49
+ "tie_word_embeddings": false,
50
+ "torch_dtype": "bfloat16",
51
+ "transformers_version": "4.48.0.dev0",
52
+ "use_cache": true,
53
+ "vision_config": {
54
+ "dropout_prob": 0.0,
55
+ "hidden_act": "gelu",
56
+ "hidden_size": 1792,
57
+ "image_size": 1120,
58
+ "in_channels": 3,
59
+ "intermediate_size": 15360,
60
+ "layer_norm_eps": 1e-06,
61
+ "num_heads": 16,
62
+ "num_hidden_layers": 63,
63
+ "num_positions": 6401,
64
+ "patch_size": 14,
65
+ "scaling_factor": 8
66
+ },
67
+ "vocab_size": 151552
68
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ model_type = "chatglm"
6
+
7
+ def __init__(
8
+ self,
9
+ num_layers=28,
10
+ padded_vocab_size=65024,
11
+ hidden_size=4096,
12
+ ffn_hidden_size=13696,
13
+ kv_channels=128,
14
+ num_attention_heads=32,
15
+ seq_length=2048,
16
+ hidden_dropout=0.0,
17
+ classifier_dropout=None,
18
+ attention_dropout=0.0,
19
+ layernorm_epsilon=1e-5,
20
+ rmsnorm=True,
21
+ apply_residual_connection_post_layernorm=False,
22
+ post_layer_norm=True,
23
+ add_bias_linear=False,
24
+ add_qkv_bias=False,
25
+ bias_dropout_fusion=True,
26
+ multi_query_attention=False,
27
+ multi_query_group_num=1,
28
+ rope_ratio=1,
29
+ apply_query_key_layer_scaling=True,
30
+ attention_softmax_in_fp32=True,
31
+ fp32_residual_connection=False,
32
+ pre_seq_len=None,
33
+ prefix_projection=False,
34
+ boi_token_id=None,
35
+ eoi_token_id=None,
36
+ **kwargs
37
+ ):
38
+ self.num_layers = num_layers
39
+ self.vocab_size = padded_vocab_size
40
+ self.padded_vocab_size = padded_vocab_size
41
+ self.hidden_size = hidden_size
42
+ self.ffn_hidden_size = ffn_hidden_size
43
+ self.kv_channels = kv_channels
44
+ self.num_attention_heads = num_attention_heads
45
+ self.seq_length = seq_length
46
+ self.hidden_dropout = hidden_dropout
47
+ self.classifier_dropout = classifier_dropout
48
+ self.attention_dropout = attention_dropout
49
+ self.layernorm_epsilon = layernorm_epsilon
50
+ self.rmsnorm = rmsnorm
51
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
52
+ self.post_layer_norm = post_layer_norm
53
+ self.add_bias_linear = add_bias_linear
54
+ self.add_qkv_bias = add_qkv_bias
55
+ self.bias_dropout_fusion = bias_dropout_fusion
56
+ self.multi_query_attention = multi_query_attention
57
+ self.multi_query_group_num = multi_query_group_num
58
+ self.rope_ratio = rope_ratio
59
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
60
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
61
+ self.fp32_residual_connection = fp32_residual_connection
62
+ self.pre_seq_len = pre_seq_len
63
+ self.prefix_projection = prefix_projection
64
+ self.boi_token_id = boi_token_id
65
+ self.eoi_token_id = eoi_token_id
66
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "eos_token_id": [
4
+ 151329,
5
+ 151336,
6
+ 151338
7
+ ],
8
+ "max_length": 8192,
9
+ "pad_token_id": 151329,
10
+ "temperature": 0.8,
11
+ "top_p": 0.8,
12
+ "transformers_version": "4.48.0.dev0"
13
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b033b2ba0c50f4419193a5c4c5675e8d5a6624ad7ee4d38e18ae840600b7dbf4
3
+ size 4984147224
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ce26fdbdff90ff3eb9ab33f716426859392b3b4eda8c8e19fd4b58bb9e432c7
3
+ size 4895071360
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0155eebf0b4ac001ed6b491c794293e5322c93ab674a035c14bb10a54e95f777
3
+ size 4895071384
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c38da65d46c2b5108d05daab370d128442f62947fa4521a7601eee8c2e3203b
3
+ size 4946649072
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f9241684ffa89177321a4deeb39ae569760f04932d08fe1ef309fc5954d178e
3
+ size 4971562032
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9442cb2c34489cfea752010373f6261e6aafaef50f8e084f40fa50689918aea7
3
+ size 3120285152
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_chatglm.py ADDED
@@ -0,0 +1,1637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ import torch
4
+ import torch.utils.checkpoint
5
+ import torch.nn.functional as F
6
+ from torch import nn
7
+ from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
8
+ from torch.nn.utils import skip_init
9
+ from typing import Optional, Tuple, Union, List, Dict, Any
10
+
11
+ import pdb
12
+ from transformers.modeling_outputs import (
13
+ BaseModelOutputWithPast,
14
+ CausalLMOutputWithPast,
15
+ SequenceClassifierOutputWithPast,
16
+ )
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import logging, is_torch_npu_available
19
+ from transformers.generation.logits_process import LogitsProcessor
20
+ from transformers.generation.utils import (
21
+ LogitsProcessorList,
22
+ StoppingCriteriaList,
23
+ GenerationConfig,
24
+ ModelOutput,
25
+ )
26
+
27
+ from .visual import EVA2CLIPModel
28
+ from .configuration_chatglm import ChatGLMConfig
29
+
30
+ try:
31
+ from transformers.utils import (
32
+ is_flash_attn_greater_or_equal_2_10,
33
+ is_flash_attn_2_available,
34
+ )
35
+
36
+ if is_flash_attn_2_available():
37
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
38
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
39
+ except:
40
+ pass
41
+
42
+ if sys.platform != "darwin" and not is_torch_npu_available():
43
+ torch._C._jit_set_profiling_mode(False)
44
+ torch._C._jit_set_profiling_executor(False)
45
+ torch._C._jit_override_can_fuse_on_cpu(True)
46
+ torch._C._jit_override_can_fuse_on_gpu(True)
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ LANGUAGE_TOKEN_TYPE = 0
51
+ VISION_TOKEN_TYPE = 1
52
+
53
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
54
+ _CONFIG_FOR_DOC = "ChatGLMConfig"
55
+
56
+
57
+ def default_init(cls, *args, **kwargs):
58
+ return cls(*args, **kwargs)
59
+
60
+
61
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
62
+ def __call__(
63
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
64
+ ) -> torch.FloatTensor:
65
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
66
+ scores.zero_()
67
+ scores[..., 198] = 5e4
68
+ return scores
69
+
70
+
71
+ class PrefixEncoder(torch.nn.Module):
72
+ """
73
+ The torch.nn model to encode the prefix
74
+ Input shape: (batch-size, prefix-length)
75
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
76
+ """
77
+
78
+ def __init__(self, config: ChatGLMConfig):
79
+ super().__init__()
80
+ self.prefix_projection = config.prefix_projection
81
+ if self.prefix_projection:
82
+ # Use a two-layer MLP to encode the prefix
83
+ kv_size = (
84
+ config.num_layers
85
+ * config.kv_channels
86
+ * config.multi_query_group_num
87
+ * 2
88
+ )
89
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
90
+ self.trans = torch.nn.Sequential(
91
+ torch.nn.Linear(kv_size, config.hidden_size),
92
+ torch.nn.Tanh(),
93
+ torch.nn.Linear(config.hidden_size, kv_size),
94
+ )
95
+ else:
96
+ self.embedding = torch.nn.Embedding(
97
+ config.pre_seq_len,
98
+ config.num_layers
99
+ * config.kv_channels
100
+ * config.multi_query_group_num
101
+ * 2,
102
+ )
103
+
104
+ def forward(self, prefix: torch.Tensor):
105
+ if self.prefix_projection:
106
+ prefix_tokens = self.embedding(prefix)
107
+ past_key_values = self.trans(prefix_tokens)
108
+ else:
109
+ past_key_values = self.embedding(prefix)
110
+ return past_key_values
111
+
112
+
113
+ def split_tensor_along_last_dim(
114
+ tensor: torch.Tensor,
115
+ num_partitions: int,
116
+ contiguous_split_chunks: bool = False,
117
+ ) -> List[torch.Tensor]:
118
+ """Split a tensor along its last dimension.
119
+
120
+ Arguments:
121
+ tensor: input tensor.
122
+ num_partitions: number of partitions to split the tensor
123
+ contiguous_split_chunks: If True, make each chunk contiguous
124
+ in memory.
125
+
126
+ Returns:
127
+ A list of Tensors
128
+ """
129
+ # Get the size and dimension.
130
+ last_dim = tensor.dim() - 1
131
+ last_dim_size = tensor.size()[last_dim] // num_partitions
132
+ # Split.
133
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
134
+ # Note: torch.split does not create contiguous tensors by default.
135
+ if contiguous_split_chunks:
136
+ return tuple(chunk.contiguous() for chunk in tensor_list)
137
+
138
+ return tensor_list
139
+
140
+
141
+ class RotaryEmbedding(nn.Module):
142
+ def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
143
+ super().__init__()
144
+ inv_freq = 1.0 / (
145
+ 10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim)
146
+ )
147
+ self.register_buffer("inv_freq", inv_freq)
148
+ self.dim = dim
149
+ self.original_impl = original_impl
150
+ self.rope_ratio = rope_ratio
151
+
152
+ def impl(self, seq_length: int, dim: int, device: torch.device, dtype: torch.dtype):
153
+ base = 10000 * self.rope_ratio
154
+ inv_freq = 1.0 / (
155
+ base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim)
156
+ )
157
+ seq = torch.arange(seq_length, device=inv_freq.device, dtype=torch.float32)
158
+ freqs = torch.outer(seq, inv_freq)
159
+ # first part even vector components, second part odd vector components,
160
+ # 2 * dim in dimension size
161
+ # emb = torch.cat((freqs, freqs), dim=-1)
162
+ # emb = torch.stack((freqs, freqs), dim=-1).to(dtype)
163
+ emb = torch.stack((freqs.cos(), freqs.sin()), dim=-1).to(dtype=dtype)
164
+ return emb
165
+
166
+ def forward_impl(
167
+ self,
168
+ seq_len: int,
169
+ n_elem: int,
170
+ dtype: torch.dtype,
171
+ device: torch.device,
172
+ base: int = 10000,
173
+ ):
174
+ """Enhanced Transformer with Rotary Position Embedding.
175
+
176
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
177
+ transformers/rope/__init__.py. MIT License:
178
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
179
+ """
180
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
181
+ base = base * self.rope_ratio
182
+ theta = 1.0 / (
183
+ base
184
+ ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem)
185
+ )
186
+
187
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
188
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
189
+
190
+ # Calculate the product of position index and $\theta_i$
191
+ idx_theta = torch.outer(seq_idx, theta).float()
192
+
193
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
194
+
195
+ # this is to mimic the behaviour of complex32, else we will get different results
196
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
197
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
198
+ return cache
199
+
200
+ def forward(self, max_seq_len, offset=0):
201
+ if self.original_impl:
202
+ return self.forward_impl(
203
+ max_seq_len,
204
+ self.dim,
205
+ dtype=self.inv_freq.dtype,
206
+ device=self.inv_freq.device,
207
+ )
208
+ else:
209
+ return self.impl(
210
+ max_seq_len,
211
+ self.dim,
212
+ dtype=self.inv_freq.dtype,
213
+ device=self.inv_freq.device,
214
+ )
215
+
216
+
217
+ @torch.jit.script
218
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
219
+ # x: [b, np, sq, hn]
220
+ sq = x.size(1)
221
+ rot_dim = rope_cache.shape[-2] * 2
222
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
223
+ # truncate to support variable sizes
224
+ rope_cache = rope_cache[:, :sq]
225
+ xshaped = x.chunk(2, -1)
226
+ cos, sin = rope_cache[...,0].unsqueeze(2), rope_cache[...,1].unsqueeze(2)
227
+ x_out2 = torch.concat(
228
+ [
229
+ xshaped[0] * cos - xshaped[1] * sin,
230
+ xshaped[1] * cos + xshaped[0] * sin,
231
+ ],
232
+ -1,
233
+ )
234
+ return torch.cat((x_out2, x_pass), dim=-1)
235
+
236
+
237
+ class RMSNorm(torch.nn.Module):
238
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
239
+ super().__init__()
240
+ self.weight = torch.nn.Parameter(
241
+ torch.empty(normalized_shape, device=device, dtype=dtype)
242
+ )
243
+ self.eps = eps
244
+
245
+ def forward(self, hidden_states: torch.Tensor):
246
+ input_dtype = hidden_states.dtype
247
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
248
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
249
+
250
+ return (self.weight * hidden_states).to(input_dtype)
251
+
252
+
253
+ class CoreAttention(torch.nn.Module):
254
+ def __init__(self, config: ChatGLMConfig, layer_number):
255
+ super(CoreAttention, self).__init__()
256
+
257
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
258
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
259
+ if self.apply_query_key_layer_scaling:
260
+ self.attention_softmax_in_fp32 = True
261
+ self.layer_number = max(1, layer_number)
262
+
263
+ projection_size = config.kv_channels * config.num_attention_heads
264
+
265
+ # Per attention head and per partition values.
266
+ self.hidden_size_per_partition = projection_size
267
+ self.hidden_size_per_attention_head = (
268
+ projection_size // config.num_attention_heads
269
+ )
270
+ self.num_attention_heads_per_partition = config.num_attention_heads
271
+
272
+ coeff = None
273
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
274
+ if self.apply_query_key_layer_scaling:
275
+ coeff = self.layer_number
276
+ self.norm_factor *= coeff
277
+ self.coeff = coeff
278
+
279
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
280
+
281
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
282
+ pytorch_major_version = int(torch.__version__.split(".")[0])
283
+ if pytorch_major_version >= 2:
284
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
285
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
286
+ query_layer, key_layer, value_layer, is_causal=True
287
+ )
288
+ else:
289
+ if attention_mask is not None:
290
+ attention_mask = ~attention_mask
291
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
292
+ query_layer, key_layer, value_layer, attention_mask
293
+ )
294
+ context_layer = context_layer.transpose(1, 2).contiguous()
295
+ new_context_layer_shape = context_layer.size()[:-2] + (
296
+ self.hidden_size_per_partition,
297
+ )
298
+ context_layer = context_layer.reshape(*new_context_layer_shape)
299
+ else:
300
+ # Raw attention scores
301
+
302
+ # [b, np, sq, sk]
303
+ output_size = (
304
+ query_layer.size(0),
305
+ query_layer.size(1),
306
+ query_layer.size(2),
307
+ key_layer.size(2),
308
+ )
309
+
310
+ # [b, np, sq, hn] -> [b * np, sq, hn]
311
+ query_layer = query_layer.view(
312
+ output_size[0] * output_size[1], output_size[2], -1
313
+ )
314
+ # [b, np, sk, hn] -> [b * np, sk, hn]
315
+ key_layer = key_layer.view(
316
+ output_size[0] * output_size[1], output_size[3], -1
317
+ )
318
+
319
+ # preallocting input tensor: [b * np, sq, sk]
320
+ matmul_input_buffer = torch.empty(
321
+ output_size[0] * output_size[1],
322
+ output_size[2],
323
+ output_size[3],
324
+ dtype=query_layer.dtype,
325
+ device=query_layer.device,
326
+ )
327
+
328
+ # Raw attention scores. [b * np, sq, sk]
329
+ matmul_result = torch.baddbmm(
330
+ matmul_input_buffer,
331
+ query_layer, # [b * np, sq, hn]
332
+ key_layer.transpose(1, 2), # [b * np, hn, sk]
333
+ beta=0.0,
334
+ alpha=(1.0 / self.norm_factor),
335
+ )
336
+
337
+ # change view to [b, np, sq, sk]
338
+ attention_scores = matmul_result.view(*output_size)
339
+
340
+ # ===========================
341
+ # Attention probs and dropout
342
+ # ===========================
343
+
344
+ # attention scores and attention mask [b, np, sq, sk]
345
+ if self.attention_softmax_in_fp32:
346
+ attention_scores = attention_scores.float()
347
+ if self.coeff is not None:
348
+ attention_scores = attention_scores * self.coeff
349
+ if (
350
+ attention_mask is None
351
+ and attention_scores.shape[2] == attention_scores.shape[3]
352
+ ):
353
+ attention_mask = torch.ones(
354
+ output_size[0],
355
+ 1,
356
+ output_size[2],
357
+ output_size[3],
358
+ device=attention_scores.device,
359
+ dtype=torch.bool,
360
+ )
361
+ attention_mask.tril_()
362
+ attention_mask = ~attention_mask
363
+ if attention_mask is not None:
364
+ attention_scores = attention_scores.masked_fill(
365
+ attention_mask, float("-inf")
366
+ )
367
+ attention_probs = F.softmax(attention_scores, dim=-1)
368
+ attention_probs = attention_probs.type_as(value_layer)
369
+
370
+ # This is actually dropping out entire tokens to attend to, which might
371
+ # seem a bit unusual, but is taken from the original Transformer paper.
372
+ attention_probs = self.attention_dropout(attention_probs)
373
+ # =========================
374
+ # Context layer. [sq, b, hp]
375
+ # =========================
376
+
377
+ # value_layer -> context layer.
378
+ # [sk, b, np, hn] --> [b, np, sq, hn]
379
+
380
+ # context layer shape: [b, np, sq, hn]
381
+ output_size = (
382
+ value_layer.size(1),
383
+ value_layer.size(2),
384
+ query_layer.size(0),
385
+ value_layer.size(3),
386
+ )
387
+ # change view [b * np, sk, hn]
388
+ value_layer = value_layer.view(
389
+ output_size[0] * output_size[1], value_layer.size(2), -1
390
+ )
391
+ # change view [b * np, sq, sk]
392
+ attention_probs = attention_probs.view(
393
+ output_size[0] * output_size[1], output_size[2], -1
394
+ )
395
+ # matmul: [b * np, sq, hn]
396
+ context_layer = torch.bmm(attention_probs, value_layer)
397
+ # change view [b, np, sq, hn]
398
+ context_layer = context_layer.view(*output_size)
399
+ # [b, np, sq, hn] --> [b, sq, np, hn]
400
+ context_layer = context_layer.transpose(1, 2).contiguous()
401
+ # [b, sq, np, hn] --> [b, sq, hp]
402
+ new_context_layer_shape = context_layer.size()[:-2] + (
403
+ self.hidden_size_per_partition,
404
+ )
405
+ context_layer = context_layer.reshape(*new_context_layer_shape)
406
+
407
+ return context_layer
408
+
409
+
410
+ class SdpaAttention(CoreAttention):
411
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
412
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
413
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
414
+ query_layer,
415
+ key_layer,
416
+ value_layer,
417
+ is_causal=True,
418
+ dropout_p=self.config.attention_dropout if self.training else 0.0,
419
+ )
420
+ else:
421
+ if attention_mask is not None:
422
+ attention_mask = ~attention_mask
423
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
424
+ query_layer,
425
+ key_layer,
426
+ value_layer,
427
+ attention_mask,
428
+ dropout_p=self.config.attention_dropout if self.training else 0.0,
429
+ )
430
+ context_layer = context_layer.transpose(1, 2).contiguous()
431
+ new_context_layer_shape = context_layer.size()[:-2] + (
432
+ self.hidden_size_per_partition,
433
+ )
434
+ context_layer = context_layer.reshape(*new_context_layer_shape)
435
+ return context_layer
436
+
437
+
438
+ def _get_unpad_data(attention_mask):
439
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
440
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
441
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
442
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
443
+ return (
444
+ indices,
445
+ cu_seqlens,
446
+ max_seqlen_in_batch,
447
+ )
448
+
449
+
450
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2
451
+ class FlashAttention2(CoreAttention):
452
+ def __init__(self, *args, **kwargs):
453
+ super().__init__(*args, **kwargs)
454
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
455
+
456
+ def forward(self, query_states, key_states, value_states, attention_mask):
457
+ query_states = query_states.transpose(1, 2)
458
+ key_states = key_states.transpose(1, 2)
459
+ value_states = value_states.transpose(1, 2)
460
+ batch_size, query_length = query_states.shape[:2]
461
+ if not self._flash_attn_uses_top_left_mask:
462
+ causal = self.is_causal
463
+ else:
464
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
465
+ causal = self.is_causal and query_length != 1
466
+ dropout = self.config.attention_dropout if self.training else 0.0
467
+ # Contains at least one padding token in the sequence
468
+ if attention_mask is not None:
469
+ (
470
+ query_states,
471
+ key_states,
472
+ value_states,
473
+ indices_q,
474
+ cu_seq_lens,
475
+ max_seq_lens,
476
+ ) = self._upad_input(
477
+ query_states, key_states, value_states, attention_mask, query_length
478
+ )
479
+
480
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
481
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
482
+
483
+ attn_output_unpad = flash_attn_varlen_func(
484
+ query_states,
485
+ key_states,
486
+ value_states,
487
+ cu_seqlens_q=cu_seqlens_q,
488
+ cu_seqlens_k=cu_seqlens_k,
489
+ max_seqlen_q=max_seqlen_in_batch_q,
490
+ max_seqlen_k=max_seqlen_in_batch_k,
491
+ dropout_p=dropout,
492
+ softmax_scale=None,
493
+ causal=causal,
494
+ )
495
+
496
+ attn_output = pad_input(
497
+ attn_output_unpad, indices_q, batch_size, query_length
498
+ )
499
+ else:
500
+ attn_output = flash_attn_func(
501
+ query_states,
502
+ key_states,
503
+ value_states,
504
+ dropout,
505
+ softmax_scale=None,
506
+ causal=causal,
507
+ )
508
+ attn_output = attn_output.reshape(
509
+ batch_size, query_length, self.hidden_size_per_partition
510
+ ).contiguous()
511
+ return attn_output
512
+
513
+ def _upad_input(
514
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
515
+ ):
516
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
517
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
518
+
519
+ key_layer = index_first_axis(
520
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
521
+ indices_k,
522
+ )
523
+ value_layer = index_first_axis(
524
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
525
+ indices_k,
526
+ )
527
+ if query_length == kv_seq_len:
528
+ query_layer = index_first_axis(
529
+ query_layer.reshape(
530
+ batch_size * kv_seq_len,
531
+ self.num_attention_heads_per_partition,
532
+ head_dim,
533
+ ),
534
+ indices_k,
535
+ )
536
+ cu_seqlens_q = cu_seqlens_k
537
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
538
+ indices_q = indices_k
539
+ elif query_length == 1:
540
+ max_seqlen_in_batch_q = 1
541
+ cu_seqlens_q = torch.arange(
542
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
543
+ ) # There is a memcpy here, that is very bad.
544
+ indices_q = cu_seqlens_q[:-1]
545
+ query_layer = query_layer.squeeze(1)
546
+ else:
547
+ # The -q_len: slice assumes left padding.
548
+ attention_mask = attention_mask[:, -query_length:]
549
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
550
+ query_layer, attention_mask
551
+ )
552
+
553
+ return (
554
+ query_layer,
555
+ key_layer,
556
+ value_layer,
557
+ indices_q,
558
+ (cu_seqlens_q, cu_seqlens_k),
559
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
560
+ )
561
+
562
+
563
+ CORE_ATTENTION_CLASSES = {
564
+ "eager": CoreAttention,
565
+ "sdpa": SdpaAttention,
566
+ "flash_attention_2": FlashAttention2,
567
+ }
568
+
569
+
570
+ class SelfAttention(torch.nn.Module):
571
+ """Parallel self-attention layer abstract class.
572
+
573
+ Self-attention layer takes input with size [s, b, h]
574
+ and returns output of the same size.
575
+ """
576
+
577
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
578
+ super(SelfAttention, self).__init__()
579
+ self.layer_number = max(1, layer_number)
580
+
581
+ self.projection_size = config.kv_channels * config.num_attention_heads
582
+
583
+ # Per attention head and per partition values.
584
+ self.hidden_size_per_attention_head = (
585
+ self.projection_size // config.num_attention_heads
586
+ )
587
+ self.num_attention_heads_per_partition = config.num_attention_heads
588
+
589
+ self.multi_query_attention = config.multi_query_attention
590
+ self.qkv_hidden_size = 3 * self.projection_size
591
+ self.original_rope = config.original_rope
592
+ if self.multi_query_attention:
593
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
594
+ self.qkv_hidden_size = (
595
+ self.projection_size
596
+ + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
597
+ )
598
+ self.query_key_value = nn.Linear(
599
+ config.hidden_size,
600
+ self.qkv_hidden_size,
601
+ bias=config.add_bias_linear or config.add_qkv_bias,
602
+ device=device,
603
+ **_config_to_kwargs(config),
604
+ )
605
+
606
+ self.core_attention = CoreAttention(config, self.layer_number)
607
+
608
+ # Output.
609
+ self.dense = nn.Linear(
610
+ self.projection_size,
611
+ config.hidden_size,
612
+ bias=config.add_bias_linear,
613
+ device=device,
614
+ **_config_to_kwargs(config),
615
+ )
616
+
617
+ def _allocate_memory(
618
+ self, inference_max_sequence_len, batch_size, device=None, dtype=None
619
+ ):
620
+ if self.multi_query_attention:
621
+ num_attention_heads = self.num_multi_query_groups_per_partition
622
+ else:
623
+ num_attention_heads = self.num_attention_heads_per_partition
624
+ return torch.empty(
625
+ inference_max_sequence_len,
626
+ batch_size,
627
+ num_attention_heads,
628
+ self.hidden_size_per_attention_head,
629
+ dtype=dtype,
630
+ device=device,
631
+ )
632
+
633
+ def forward(
634
+ self,
635
+ hidden_states,
636
+ attention_mask,
637
+ rotary_pos_emb,
638
+ kv_cache=None,
639
+ use_cache=True,
640
+ ):
641
+ # hidden_states: [b, sq, h]
642
+
643
+ # =================================================
644
+ # Pre-allocate memory for key-values for inference.
645
+ # =================================================
646
+ # =====================
647
+ # Query, Key, and Value
648
+ # =====================
649
+
650
+ # Attention heads [b, sq, h] --> [b, sq, (np * 3 * hn)]
651
+ mixed_x_layer = self.query_key_value(hidden_states)
652
+
653
+ if self.multi_query_attention:
654
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
655
+ [
656
+ self.num_attention_heads_per_partition
657
+ * self.hidden_size_per_attention_head,
658
+ self.num_multi_query_groups_per_partition
659
+ * self.hidden_size_per_attention_head,
660
+ self.num_multi_query_groups_per_partition
661
+ * self.hidden_size_per_attention_head,
662
+ ],
663
+ dim=-1,
664
+ )
665
+ query_layer = query_layer.view(
666
+ query_layer.size()[:-1]
667
+ + (
668
+ self.num_attention_heads_per_partition,
669
+ self.hidden_size_per_attention_head,
670
+ )
671
+ )
672
+ key_layer = key_layer.view(
673
+ key_layer.size()[:-1]
674
+ + (
675
+ self.num_multi_query_groups_per_partition,
676
+ self.hidden_size_per_attention_head,
677
+ )
678
+ )
679
+ value_layer = value_layer.view(
680
+ value_layer.size()[:-1]
681
+ + (
682
+ self.num_multi_query_groups_per_partition,
683
+ self.hidden_size_per_attention_head,
684
+ )
685
+ )
686
+ else:
687
+ new_tensor_shape = mixed_x_layer.size()[:-1] + (
688
+ self.num_attention_heads_per_partition,
689
+ 3 * self.hidden_size_per_attention_head,
690
+ )
691
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
692
+
693
+ # [b, sq, np, 3 * hn] --> 3 [b, sq, np, hn]
694
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(
695
+ mixed_x_layer, 3
696
+ )
697
+
698
+
699
+
700
+ # apply relative positional encoding (rotary embedding)
701
+ if rotary_pos_emb is not None:
702
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
703
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
704
+
705
+
706
+ # [b, sq, np, hn] -> [b, np, sq, hn]
707
+ query_layer, key_layer, value_layer = [
708
+ k.transpose(1, 2) for k in [query_layer, key_layer, value_layer]
709
+ ]
710
+
711
+ # adjust key and value for inference
712
+ if kv_cache is not None:
713
+ cache_k, cache_v = kv_cache
714
+ key_layer = torch.cat((cache_k, key_layer), dim=2)
715
+ value_layer = torch.cat((cache_v, value_layer), dim=2)
716
+
717
+ if use_cache:
718
+ kv_cache = (key_layer, value_layer)
719
+ else:
720
+ kv_cache = None
721
+
722
+ if self.multi_query_attention:
723
+ key_layer = key_layer.repeat_interleave(self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, dim=1)
724
+ value_layer = value_layer.repeat_interleave(self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, dim=1)
725
+
726
+ # ==================================
727
+ # core attention computation
728
+ # ==================================
729
+
730
+ context_layer = self.core_attention(
731
+ query_layer, key_layer, value_layer, attention_mask
732
+ )
733
+
734
+ # =================
735
+ # Output. [sq, b, h]
736
+ # =================
737
+
738
+ output = self.dense(context_layer)
739
+
740
+ return output, kv_cache
741
+
742
+
743
+ def _config_to_kwargs(args):
744
+ common_kwargs = {
745
+ "dtype": args.torch_dtype,
746
+ }
747
+ return common_kwargs
748
+
749
+
750
+ class MLP(torch.nn.Module):
751
+ """MLP.
752
+
753
+ MLP will take the input with h hidden state, project it to 4*h
754
+ hidden dimension, perform nonlinear transformation, and project the
755
+ state back into h hidden dimension.
756
+ """
757
+
758
+ def __init__(self, config: ChatGLMConfig, device=None):
759
+ super(MLP, self).__init__()
760
+
761
+ self.add_bias = config.add_bias_linear
762
+
763
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
764
+ self.dense_h_to_4h = nn.Linear(
765
+ config.hidden_size,
766
+ config.ffn_hidden_size * 2,
767
+ bias=self.add_bias,
768
+ device=device,
769
+ **_config_to_kwargs(config),
770
+ )
771
+
772
+ def swiglu(x):
773
+ x = torch.chunk(x, 2, dim=-1)
774
+ return F.silu(x[0]) * x[1]
775
+
776
+ self.activation_func = swiglu
777
+
778
+ # Project back to h.
779
+ self.dense_4h_to_h = nn.Linear(
780
+ config.ffn_hidden_size,
781
+ config.hidden_size,
782
+ bias=self.add_bias,
783
+ device=device,
784
+ **_config_to_kwargs(config),
785
+ )
786
+
787
+ def forward(self, hidden_states):
788
+ # [s, b, 4hp]
789
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
790
+ intermediate_parallel = self.activation_func(intermediate_parallel)
791
+ # [s, b, h]
792
+ output = self.dense_4h_to_h(intermediate_parallel)
793
+ return output
794
+
795
+
796
+ class GLMBlock(torch.nn.Module):
797
+ """A single transformer layer.
798
+
799
+ Transformer layer takes input with size [s, b, h] and returns an
800
+ output of the same size.
801
+ """
802
+
803
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
804
+ super(GLMBlock, self).__init__()
805
+ self.layer_number = layer_number
806
+
807
+ self.apply_residual_connection_post_layernorm = (
808
+ config.apply_residual_connection_post_layernorm
809
+ )
810
+
811
+ self.fp32_residual_connection = config.fp32_residual_connection
812
+
813
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
814
+ # Layernorm on the input data.
815
+ self.input_layernorm = LayerNormFunc(
816
+ config.hidden_size,
817
+ eps=config.layernorm_epsilon,
818
+ device=device,
819
+ dtype=config.torch_dtype,
820
+ )
821
+
822
+ # Self attention.
823
+ self.self_attention = SelfAttention(config, layer_number, device=device)
824
+ self.hidden_dropout = config.hidden_dropout
825
+
826
+ # Layernorm on the attention output
827
+ self.post_attention_layernorm = LayerNormFunc(
828
+ config.hidden_size,
829
+ eps=config.layernorm_epsilon,
830
+ device=device,
831
+ dtype=config.torch_dtype,
832
+ )
833
+
834
+ # MLP
835
+ self.mlp = MLP(config, device=device)
836
+
837
+ def forward(
838
+ self,
839
+ hidden_states,
840
+ attention_mask,
841
+ rotary_pos_emb,
842
+ kv_cache=None,
843
+ use_cache=True,
844
+ ):
845
+ # hidden_states: [s, b, h]
846
+
847
+ # Layer norm at the beginning of the transformer layer.
848
+ layernorm_output = self.input_layernorm(hidden_states)
849
+ # Self attention.
850
+ attention_output, kv_cache = self.self_attention(
851
+ layernorm_output,
852
+ attention_mask,
853
+ rotary_pos_emb,
854
+ kv_cache=kv_cache,
855
+ use_cache=use_cache,
856
+ )
857
+
858
+ # Residual connection.
859
+ if self.apply_residual_connection_post_layernorm:
860
+ residual = layernorm_output
861
+ else:
862
+ residual = hidden_states
863
+
864
+ layernorm_input = torch.nn.functional.dropout(
865
+ attention_output, p=self.hidden_dropout, training=self.training
866
+ )
867
+ layernorm_input = residual + layernorm_input
868
+
869
+ # Layer norm post the self attention.
870
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
871
+
872
+ # MLP.
873
+ mlp_output = self.mlp(layernorm_output)
874
+
875
+ # Second residual connection.
876
+ if self.apply_residual_connection_post_layernorm:
877
+ residual = layernorm_output
878
+ else:
879
+ residual = layernorm_input
880
+
881
+ output = torch.nn.functional.dropout(
882
+ mlp_output, p=self.hidden_dropout, training=self.training
883
+ )
884
+ output = residual + output
885
+
886
+ return output, kv_cache
887
+
888
+
889
+ class GLMTransformer(torch.nn.Module):
890
+ """Transformer class."""
891
+
892
+ def __init__(self, config: ChatGLMConfig, device=None):
893
+ super(GLMTransformer, self).__init__()
894
+
895
+ self.fp32_residual_connection = config.fp32_residual_connection
896
+ self.post_layer_norm = config.post_layer_norm
897
+
898
+ # Number of layers.
899
+ self.num_layers = config.num_layers
900
+
901
+ # Transformer layers.
902
+ def build_layer(layer_number):
903
+ return GLMBlock(config, layer_number, device=device)
904
+
905
+ self.layers = torch.nn.ModuleList(
906
+ [build_layer(i + 1) for i in range(self.num_layers)]
907
+ )
908
+
909
+ if self.post_layer_norm:
910
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
911
+ # Final layer norm before output.
912
+ self.final_layernorm = LayerNormFunc(
913
+ config.hidden_size,
914
+ eps=config.layernorm_epsilon,
915
+ device=device,
916
+ dtype=config.torch_dtype,
917
+ )
918
+
919
+ self.gradient_checkpointing = False
920
+
921
+ def _get_layer(self, layer_number):
922
+ return self.layers[layer_number]
923
+
924
+ def forward(
925
+ self,
926
+ hidden_states,
927
+ attention_mask,
928
+ rotary_pos_emb,
929
+ kv_caches=None,
930
+ use_cache: Optional[bool] = True,
931
+ output_hidden_states: Optional[bool] = False,
932
+ ):
933
+ if not kv_caches:
934
+ kv_caches = [None for _ in range(self.num_layers)]
935
+ presents = () if use_cache else None
936
+ if self.gradient_checkpointing and self.training:
937
+ if use_cache:
938
+ logger.warning_once(
939
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
940
+ )
941
+ use_cache = False
942
+
943
+ all_self_attentions = None
944
+ all_hidden_states = () if output_hidden_states else None
945
+ for index in range(self.num_layers):
946
+ if output_hidden_states:
947
+ all_hidden_states = all_hidden_states + (hidden_states,)
948
+
949
+ layer = self._get_layer(index)
950
+ if self.gradient_checkpointing and self.training:
951
+ layer_ret = torch.utils.checkpoint.checkpoint(
952
+ layer,
953
+ hidden_states,
954
+ attention_mask,
955
+ rotary_pos_emb,
956
+ kv_caches[index],
957
+ use_cache,
958
+ use_reentrant=False,
959
+ )
960
+ else:
961
+ layer_ret = layer(
962
+ hidden_states,
963
+ attention_mask,
964
+ rotary_pos_emb,
965
+ kv_cache=kv_caches[index],
966
+ use_cache=use_cache,
967
+ )
968
+ hidden_states, kv_cache = layer_ret
969
+ if use_cache:
970
+ presents = presents + (kv_cache,)
971
+
972
+ if output_hidden_states:
973
+ all_hidden_states = all_hidden_states + (hidden_states,)
974
+
975
+ # Final layer norm.
976
+ if self.post_layer_norm:
977
+ hidden_states = self.final_layernorm(hidden_states)
978
+
979
+ return hidden_states, presents, all_hidden_states, all_self_attentions
980
+
981
+
982
+ class ChatGLMPreTrainedModel(PreTrainedModel):
983
+ """
984
+ An abstract class to handle weights initialization and
985
+ a simple interface for downloading and loading pretrained models.
986
+ """
987
+
988
+ is_parallelizable = False
989
+ supports_gradient_checkpointing = True
990
+ config_class = ChatGLMConfig
991
+ base_model_prefix = "transformer"
992
+ _no_split_modules = ["GLMBlock"]
993
+ _supports_flash_attn_2 = True
994
+ _supports_sdpa = True
995
+
996
+ def _init_weights(self, module: nn.Module):
997
+ """Initialize the weights."""
998
+ return
999
+
1000
+ def get_masks(self, input_embeds, past_key_values, padding_mask=None):
1001
+ batch_size, seq_length, embed_size = input_embeds.shape
1002
+ full_attention_mask = torch.ones(
1003
+ batch_size, seq_length, seq_length, device=input_embeds.device
1004
+ )
1005
+ full_attention_mask.tril_()
1006
+ past_length = 0
1007
+ if past_key_values:
1008
+ past_length = past_key_values[0][0].shape[2]
1009
+ if past_length:
1010
+ full_attention_mask = torch.cat(
1011
+ (
1012
+ torch.ones(
1013
+ batch_size, seq_length, past_length, device=input_embeds.device
1014
+ ),
1015
+ full_attention_mask,
1016
+ ),
1017
+ dim=-1,
1018
+ )
1019
+ if padding_mask is not None:
1020
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
1021
+ if not past_length and padding_mask is not None:
1022
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
1023
+ full_attention_mask = (full_attention_mask < 0.5).bool()
1024
+ full_attention_mask.unsqueeze_(1)
1025
+ return full_attention_mask
1026
+
1027
+ def get_position_ids(self, input_ids, device):
1028
+ batch_size, seq_length = input_ids.shape
1029
+ position_ids = (
1030
+ torch.arange(seq_length, dtype=torch.long, device=device)
1031
+ .unsqueeze(0)
1032
+ .repeat(batch_size, 1)
1033
+ )
1034
+ return position_ids
1035
+
1036
+ def get_multimodal_position_ids(self, input_ids, device):
1037
+ batch_size, seq_length = input_ids.shape
1038
+ position_ids = (
1039
+ torch.arange(seq_length, dtype=torch.long, device=device)
1040
+ .unsqueeze(0)
1041
+ .repeat(batch_size, 1)
1042
+ )
1043
+
1044
+
1045
+ class Embedding(torch.nn.Module):
1046
+ """Language model embeddings."""
1047
+
1048
+ def __init__(self, config: ChatGLMConfig, device=None):
1049
+ super(Embedding, self).__init__()
1050
+
1051
+ self.hidden_size = config.hidden_size
1052
+ # Word embeddings (parallel).
1053
+ self.word_embeddings = nn.Embedding(
1054
+ config.padded_vocab_size,
1055
+ self.hidden_size,
1056
+ dtype=config.torch_dtype,
1057
+ device=device,
1058
+ )
1059
+ self.fp32_residual_connection = config.fp32_residual_connection
1060
+
1061
+ def forward(self, input_ids):
1062
+ # Embeddings.
1063
+ words_embeddings = self.word_embeddings(input_ids)
1064
+ embeddings = words_embeddings
1065
+ # If the input flag for fp32 residual connection is set, convert for float.
1066
+ if self.fp32_residual_connection:
1067
+ embeddings = embeddings.float()
1068
+ return embeddings
1069
+
1070
+
1071
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
1072
+ if images_list is None or len(images_list) == 0:
1073
+ return True
1074
+ for image_list in images_list:
1075
+ if image_list is not None:
1076
+ return False
1077
+ return True
1078
+
1079
+
1080
+ class ChatGLMModel(ChatGLMPreTrainedModel):
1081
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
1082
+ super().__init__(config)
1083
+ if empty_init:
1084
+ init_method = skip_init
1085
+ else:
1086
+ init_method = default_init
1087
+ init_kwargs = {}
1088
+ if device is not None:
1089
+ init_kwargs["device"] = device
1090
+ self.embedding = init_method(Embedding, config, **init_kwargs)
1091
+ self.num_layers = config.num_layers
1092
+ self.multi_query_group_num = config.multi_query_group_num
1093
+ self.kv_channels = config.kv_channels
1094
+
1095
+ # Rotary positional embeddings
1096
+ self.seq_length = config.seq_length
1097
+ rotary_dim = (
1098
+ config.hidden_size // config.num_attention_heads
1099
+ if config.kv_channels is None
1100
+ else config.kv_channels
1101
+ )
1102
+
1103
+ self.rotary_pos_emb = RotaryEmbedding(
1104
+ rotary_dim // 2,
1105
+ rope_ratio=config.rope_ratio,
1106
+ original_impl=config.original_rope,
1107
+ device=device,
1108
+ dtype=config.torch_dtype,
1109
+ )
1110
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
1111
+ self.output_layer = init_method(
1112
+ nn.Linear,
1113
+ config.hidden_size,
1114
+ config.padded_vocab_size,
1115
+ bias=False,
1116
+ dtype=config.torch_dtype,
1117
+ **init_kwargs,
1118
+ )
1119
+ self.pre_seq_len = config.pre_seq_len
1120
+ self.prefix_projection = config.prefix_projection
1121
+ if self.pre_seq_len is not None:
1122
+ for param in self.parameters():
1123
+ param.requires_grad = False
1124
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
1125
+ self.prefix_encoder = PrefixEncoder(config)
1126
+ self.dropout = torch.nn.Dropout(0.1)
1127
+
1128
+ self.vision = EVA2CLIPModel(config)
1129
+ self.position_ids_skipped = False
1130
+
1131
+ def get_input_embeddings(self):
1132
+ return self.embedding.word_embeddings
1133
+
1134
+ def set_input_embeddings(self, value):
1135
+ self.embedding.word_embeddings = value
1136
+
1137
+ def get_prompt(self, batch_size, device, dtype=torch.half):
1138
+ prefix_tokens = (
1139
+ self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
1140
+ )
1141
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
1142
+ past_key_values = past_key_values.view(
1143
+ batch_size,
1144
+ self.pre_seq_len,
1145
+ self.pre_seq_len,
1146
+ self.num_layers * 2,
1147
+ self.multi_query_group_num,
1148
+ self.kv_channels,
1149
+ )
1150
+ # seq_len, b, nh, hidden_size
1151
+ past_key_values = self.dropout(past_key_values)
1152
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
1153
+ return past_key_values
1154
+
1155
+ def forward(
1156
+ self,
1157
+ input_ids: torch.LongTensor = None,
1158
+ images: torch.Tensor = None,
1159
+ position_ids: Optional[torch.Tensor] = None,
1160
+ attention_mask: Optional[torch.BoolTensor] = None,
1161
+ full_attention_mask: Optional[torch.BoolTensor] = None,
1162
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1163
+ inputs_embeds: Optional[torch.Tensor] = None,
1164
+ use_cache: Optional[bool] = None,
1165
+ output_hidden_states: Optional[bool] = None,
1166
+ return_dict: Optional[bool] = None,
1167
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1168
+ """take care of image_encode, position_ids and (attention_mask = None is fine)"""
1169
+ # generate mode with past_key_values. the image features are already mapped
1170
+ if past_key_values is None:
1171
+ self.position_ids_skipped = False
1172
+ # not allow for inputs_embeds, because we want to process image feature
1173
+ assert (
1174
+ input_ids is not None and inputs_embeds is None
1175
+ ), f"{input_ids} {inputs_embeds}"
1176
+ if not is_empty(images): # multi-modality
1177
+ image_size: int = self.config.vision_config["image_size"]
1178
+ patch_size: int = self.config.vision_config["patch_size"]
1179
+ num_patches = (image_size // patch_size // 2) ** 2
1180
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
1181
+
1182
+ inputs_embeds = self.embedding(input_ids)
1183
+
1184
+ images = images.to(dtype=inputs_embeds.dtype)
1185
+ images_features = self.vision(images)
1186
+
1187
+ if position_ids is None:
1188
+ position_ids = self.get_position_ids(
1189
+ input_ids, device=inputs_embeds.device
1190
+ )
1191
+ new_input_embeds, new_position_ids = [], []
1192
+
1193
+ for i in range(len(input_ids)):
1194
+ input_id = input_ids[i].tolist()
1195
+ boi_token_pos, eoi_token_pos = (
1196
+ input_id.index(self.config.boi_token_id),
1197
+ input_id.index(self.config.eoi_token_id),
1198
+ )
1199
+ assert eoi_token_pos - boi_token_pos == 2
1200
+ new_input_embeds.append(
1201
+ torch.cat(
1202
+ (
1203
+ inputs_embeds[i, :boi_token_pos],
1204
+ images_features[i].to(inputs_embeds.device),
1205
+ inputs_embeds[i, eoi_token_pos + 1 :],
1206
+ )
1207
+ )
1208
+ )
1209
+ new_position_ids.append(
1210
+ torch.arange(
1211
+ 0,
1212
+ len(input_id) + num_patches - 1,
1213
+ dtype=position_ids.dtype,
1214
+ device=inputs_embeds.device,
1215
+ )
1216
+ )
1217
+ inputs_embeds = torch.stack(new_input_embeds, dim=0)
1218
+ position_ids = torch.stack(new_position_ids, dim=0)
1219
+ output_hidden_states = (
1220
+ output_hidden_states
1221
+ if output_hidden_states is not None
1222
+ else self.config.output_hidden_states
1223
+ )
1224
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1225
+ return_dict = (
1226
+ return_dict if return_dict is not None else self.config.use_return_dict
1227
+ )
1228
+
1229
+ batch_size, seq_length = input_ids.shape
1230
+
1231
+ if inputs_embeds is None:
1232
+ inputs_embeds = self.embedding(input_ids)
1233
+
1234
+ if self.pre_seq_len is not None:
1235
+ if past_key_values is None:
1236
+ past_key_values = self.get_prompt(
1237
+ batch_size=batch_size,
1238
+ device=input_ids.device,
1239
+ dtype=inputs_embeds.dtype,
1240
+ )
1241
+ if attention_mask is not None:
1242
+ attention_mask = torch.cat(
1243
+ [
1244
+ attention_mask.new_ones((batch_size, self.pre_seq_len)),
1245
+ attention_mask,
1246
+ ],
1247
+ dim=-1,
1248
+ )
1249
+
1250
+ if full_attention_mask is None:
1251
+ if (attention_mask is not None and not attention_mask.all()) or (
1252
+ past_key_values and seq_length != 1
1253
+ ):
1254
+ if self.training:
1255
+ # https://github.com/THUDM/GLM-4/issues/264
1256
+ new_input_ids, new_attention_mask = [], []
1257
+ for i in range(len(input_ids)):
1258
+ input_id = input_ids[i].tolist()
1259
+ boi_token_pos, eoi_token_pos = (
1260
+ input_id.index(self.config.boi_token_id),
1261
+ input_id.index(self.config.eoi_token_id),
1262
+ )
1263
+ assert eoi_token_pos - boi_token_pos == 2
1264
+
1265
+ new_attention_mask.append(
1266
+ torch.cat(
1267
+ (
1268
+ attention_mask[i, : boi_token_pos + 1],
1269
+ torch.ones(num_patches).to(attention_mask.device),
1270
+ attention_mask[i, eoi_token_pos:],
1271
+ )
1272
+ )
1273
+ )
1274
+
1275
+ new_input_ids.append(
1276
+ torch.cat(
1277
+ (
1278
+ input_ids[i, : boi_token_pos + 1],
1279
+ input_ids[i, -1].repeat(num_patches),
1280
+ input_ids[i, eoi_token_pos:],
1281
+ )
1282
+ )
1283
+ )
1284
+
1285
+ attention_mask = torch.stack(new_attention_mask, dim=0)
1286
+ input_ids = torch.stack(new_input_ids, dim=0)
1287
+ inputs_embeds = self.embedding(input_ids)
1288
+
1289
+ full_attention_mask = self.get_masks(
1290
+ inputs_embeds, past_key_values, padding_mask=attention_mask
1291
+ )
1292
+
1293
+ # Rotary positional embeddings
1294
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
1295
+ if position_ids[0].size()[0] == 1 and not self.position_ids_skipped:
1296
+ self.position_ids_skipped = True
1297
+ position_ids[:, 0] = position_ids[:, 0] + 1600 - 1
1298
+
1299
+ if position_ids is not None:
1300
+ rotary_pos_emb = rotary_pos_emb[position_ids]
1301
+ else:
1302
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
1303
+
1304
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
1305
+ inputs_embeds,
1306
+ full_attention_mask,
1307
+ rotary_pos_emb=rotary_pos_emb,
1308
+ kv_caches=past_key_values,
1309
+ use_cache=use_cache,
1310
+ output_hidden_states=output_hidden_states,
1311
+ )
1312
+
1313
+ if not return_dict:
1314
+ return tuple(
1315
+ v
1316
+ for v in [
1317
+ hidden_states,
1318
+ presents,
1319
+ all_hidden_states,
1320
+ all_self_attentions,
1321
+ ]
1322
+ if v is not None
1323
+ )
1324
+
1325
+ return BaseModelOutputWithPast(
1326
+ last_hidden_state=hidden_states,
1327
+ past_key_values=presents,
1328
+ hidden_states=all_hidden_states,
1329
+ attentions=all_self_attentions,
1330
+ )
1331
+
1332
+
1333
+ def _history_to_prompt(history, query):
1334
+ prompt = ""
1335
+ flag = False
1336
+ for i, (old_query, response) in enumerate(history):
1337
+ prompt += (
1338
+ ("<|user|>" if flag else "")
1339
+ + old_query
1340
+ + "<|assistant|>"
1341
+ + response
1342
+ + "<|endoftext|>"
1343
+ )
1344
+ flag = True
1345
+ prompt += "{}{}<|assistant|>".format("<|user|>" if flag else "", query)
1346
+ return prompt
1347
+
1348
+
1349
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1350
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1351
+ super().__init__(config)
1352
+
1353
+ self.max_sequence_length = config.max_length
1354
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1355
+ self.config = config
1356
+
1357
+ def _update_model_kwargs_for_generation(
1358
+ self,
1359
+ outputs: ModelOutput,
1360
+ model_kwargs: Dict[str, Any],
1361
+ is_encoder_decoder: bool = False,
1362
+ ) -> Dict[str, Any]:
1363
+
1364
+ # update past_key_values
1365
+ cache_name, cache = self._extract_past_from_model_output(outputs)
1366
+ model_kwargs[cache_name] = cache
1367
+
1368
+ # update attention mask
1369
+ if "attention_mask" in model_kwargs:
1370
+ attention_mask = model_kwargs["attention_mask"]
1371
+ model_kwargs["attention_mask"] = torch.cat(
1372
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))],
1373
+ dim=-1,
1374
+ )
1375
+
1376
+ # update position ids
1377
+ if "position_ids" in model_kwargs:
1378
+ position_ids = model_kwargs["position_ids"]
1379
+ new_position_id = position_ids[..., -1:].clone()
1380
+ new_position_id += 1
1381
+ model_kwargs["position_ids"] = torch.cat(
1382
+ [position_ids, new_position_id], dim=-1
1383
+ )
1384
+
1385
+ model_kwargs["is_first_forward"] = False
1386
+ return model_kwargs
1387
+
1388
+ def prepare_inputs_for_generation(
1389
+ self,
1390
+ input_ids: torch.LongTensor,
1391
+ images: Optional[torch.Tensor] = None,
1392
+ past_key_values: Optional[torch.Tensor] = None,
1393
+ attention_mask: Optional[torch.Tensor] = None,
1394
+ position_ids: Optional[torch.Tensor] = None,
1395
+ use_cache: Optional[bool] = None,
1396
+ is_first_forward: bool = True,
1397
+ **kwargs,
1398
+ ) -> dict:
1399
+ # only last token for input_ids if past is not None
1400
+ if position_ids is None:
1401
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
1402
+ if attention_mask is not None:
1403
+ image_size: int = self.config.vision_config["image_size"]
1404
+ patch_size: int = self.config.vision_config["patch_size"]
1405
+ num_patches = (image_size // patch_size // 2) ** 2
1406
+ new_attention_masks = []
1407
+
1408
+ # if not image, use this default id
1409
+ eoi_token_pos = 6
1410
+ boi_token_pos = 4
1411
+
1412
+ for i in range(len(input_ids)):
1413
+ input_id = input_ids[i].tolist()
1414
+ if not is_empty(images):
1415
+ boi_token_pos, eoi_token_pos = (
1416
+ input_id.index(self.config.boi_token_id),
1417
+ input_id.index(self.config.eoi_token_id),
1418
+ )
1419
+ assert eoi_token_pos - boi_token_pos == 2
1420
+ new_attention_masks.append(
1421
+ torch.cat(
1422
+ (
1423
+ attention_mask[i, : boi_token_pos + 1],
1424
+ attention_mask.new_ones(num_patches),
1425
+ attention_mask[i, eoi_token_pos:],
1426
+ )
1427
+ )
1428
+ )
1429
+ attention_mask = torch.stack(new_attention_masks, dim=0)
1430
+ if not is_first_forward:
1431
+ if past_key_values is not None:
1432
+ position_ids = position_ids[..., -1:]
1433
+ input_ids = input_ids[:, -1:]
1434
+ return {
1435
+ "input_ids": input_ids,
1436
+ "images": images,
1437
+ "past_key_values": past_key_values,
1438
+ "position_ids": position_ids,
1439
+ "attention_mask": attention_mask,
1440
+ "return_last_logit": True,
1441
+ "use_cache": use_cache,
1442
+ }
1443
+
1444
+ def forward(
1445
+ self,
1446
+ input_ids: Optional[torch.Tensor] = None,
1447
+ images: List[List[torch.Tensor]] = None,
1448
+ position_ids: Optional[torch.Tensor] = None,
1449
+ attention_mask: Optional[torch.Tensor] = None,
1450
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1451
+ inputs_embeds: Optional[torch.Tensor] = None,
1452
+ labels: Optional[torch.Tensor] = None,
1453
+ use_cache: Optional[bool] = None,
1454
+ output_attentions: Optional[bool] = None,
1455
+ output_hidden_states: Optional[bool] = None,
1456
+ return_dict: Optional[bool] = None,
1457
+ return_last_logit: Optional[bool] = False,
1458
+ ):
1459
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1460
+ return_dict = (
1461
+ return_dict if return_dict is not None else self.config.use_return_dict
1462
+ )
1463
+
1464
+ transformer_outputs = self.transformer(
1465
+ input_ids=input_ids,
1466
+ images=images,
1467
+ position_ids=position_ids,
1468
+ attention_mask=attention_mask,
1469
+ past_key_values=past_key_values,
1470
+ inputs_embeds=inputs_embeds,
1471
+ use_cache=use_cache,
1472
+ output_hidden_states=output_hidden_states,
1473
+ return_dict=return_dict,
1474
+ )
1475
+
1476
+ hidden_states = transformer_outputs[0]
1477
+ if return_last_logit:
1478
+ hidden_states = hidden_states[:, -1:]
1479
+ lm_logits = self.transformer.output_layer(hidden_states)
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ new_labels = []
1484
+ for i in range(len(input_ids)):
1485
+ input_id = input_ids[i].tolist()
1486
+ boi_token_pos, eoi_token_pos = (
1487
+ input_id.index(self.config.boi_token_id),
1488
+ input_id.index(self.config.eoi_token_id),
1489
+ )
1490
+ assert eoi_token_pos - boi_token_pos == 2
1491
+
1492
+ new_labels.append(
1493
+ torch.cat(
1494
+ (
1495
+ labels[i, : boi_token_pos + 1],
1496
+ torch.tensor([-100])
1497
+ .to(labels.device)
1498
+ .to(labels.dtype)
1499
+ .repeat(1600),
1500
+ labels[i, eoi_token_pos:],
1501
+ )
1502
+ )
1503
+ )
1504
+
1505
+ labels = torch.stack(new_labels, dim=0)
1506
+ lm_logits = lm_logits.to(torch.float32)
1507
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1508
+ shift_labels = labels[..., 1:].contiguous()
1509
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1510
+ loss = loss_fct(
1511
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1512
+ )
1513
+
1514
+ lm_logits = lm_logits.to(hidden_states.dtype)
1515
+ loss = loss.to(hidden_states.dtype)
1516
+
1517
+ if not return_dict:
1518
+ output = (lm_logits,) + transformer_outputs[1:]
1519
+ return ((loss,) + output) if loss is not None else output
1520
+
1521
+ return CausalLMOutputWithPast(
1522
+ loss=loss,
1523
+ logits=lm_logits,
1524
+ past_key_values=transformer_outputs.past_key_values,
1525
+ hidden_states=transformer_outputs.hidden_states,
1526
+ attentions=transformer_outputs.attentions,
1527
+ )
1528
+
1529
+ @staticmethod
1530
+ def _reorder_cache(
1531
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1532
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1533
+ """
1534
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1535
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1536
+ beam_idx at every generation step.
1537
+
1538
+ Output shares the same memory storage as `past`.
1539
+ """
1540
+ return tuple(
1541
+ (
1542
+ layer_past[0].index_select(0, beam_idx.to(layer_past[0].device)),
1543
+ layer_past[1].index_select(0, beam_idx.to(layer_past[1].device)),
1544
+ )
1545
+ for layer_past in past
1546
+ )
1547
+
1548
+
1549
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1550
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1551
+ super().__init__(config)
1552
+
1553
+ self.num_labels = config.num_labels
1554
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1555
+
1556
+ self.classifier_head = nn.Linear(
1557
+ config.hidden_size, config.num_labels, bias=True, dtype=torch.half
1558
+ )
1559
+ if config.classifier_dropout is not None:
1560
+ self.dropout = nn.Dropout(config.classifier_dropout)
1561
+ else:
1562
+ self.dropout = None
1563
+ self.config = config
1564
+
1565
+ def forward(
1566
+ self,
1567
+ input_ids: Optional[torch.LongTensor] = None,
1568
+ position_ids: Optional[torch.LongTensor] = None,
1569
+ attention_mask: Optional[torch.Tensor] = None,
1570
+ full_attention_mask: Optional[torch.Tensor] = None,
1571
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1572
+ inputs_embeds: Optional[torch.LongTensor] = None,
1573
+ labels: Optional[torch.LongTensor] = None,
1574
+ use_cache: Optional[bool] = None,
1575
+ output_hidden_states: Optional[bool] = None,
1576
+ return_dict: Optional[bool] = None,
1577
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1578
+ return_dict = (
1579
+ return_dict if return_dict is not None else self.config.use_return_dict
1580
+ )
1581
+
1582
+ transformer_outputs = self.transformer(
1583
+ input_ids=input_ids,
1584
+ position_ids=position_ids,
1585
+ attention_mask=attention_mask,
1586
+ full_attention_mask=full_attention_mask,
1587
+ past_key_values=past_key_values,
1588
+ inputs_embeds=inputs_embeds,
1589
+ use_cache=use_cache,
1590
+ output_hidden_states=output_hidden_states,
1591
+ return_dict=return_dict,
1592
+ )
1593
+
1594
+ hidden_states = transformer_outputs[0]
1595
+ pooled_hidden_states = hidden_states[-1]
1596
+ if self.dropout is not None:
1597
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1598
+ logits = self.classifier_head(pooled_hidden_states)
1599
+
1600
+ loss = None
1601
+ if labels is not None:
1602
+ if self.config.problem_type is None:
1603
+ if self.num_labels == 1:
1604
+ self.config.problem_type = "regression"
1605
+ elif self.num_labels > 1 and (
1606
+ labels.dtype == torch.long or labels.dtype == torch.int
1607
+ ):
1608
+ self.config.problem_type = "single_label_classification"
1609
+ else:
1610
+ self.config.problem_type = "multi_label_classification"
1611
+
1612
+ if self.config.problem_type == "regression":
1613
+ loss_fct = MSELoss()
1614
+ if self.num_labels == 1:
1615
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1616
+ else:
1617
+ loss = loss_fct(logits.float(), labels)
1618
+ elif self.config.problem_type == "single_label_classification":
1619
+ loss_fct = CrossEntropyLoss()
1620
+ loss = loss_fct(
1621
+ logits.view(-1, self.num_labels).float(), labels.view(-1)
1622
+ )
1623
+ elif self.config.problem_type == "multi_label_classification":
1624
+ loss_fct = BCEWithLogitsLoss()
1625
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1626
+
1627
+ if not return_dict:
1628
+ output = (logits,) + transformer_outputs[1:]
1629
+ return ((loss,) + output) if loss is not None else output
1630
+
1631
+ return SequenceClassifierOutputWithPast(
1632
+ loss=loss,
1633
+ logits=logits,
1634
+ past_key_values=transformer_outputs.past_key_values,
1635
+ hidden_states=transformer_outputs.hidden_states,
1636
+ attentions=transformer_outputs.attentions,
1637
+ )
tokenization_chatglm.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import regex as re
2
+ import base64
3
+ import os
4
+ import json
5
+ import tiktoken
6
+ import torch
7
+ from torch import TensorType
8
+ from typing import List, Optional, Union, Dict, Any
9
+ from torchvision import transforms
10
+ from transformers import PreTrainedTokenizer
11
+ from transformers.utils import PaddingStrategy
12
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
13
+
14
+
15
+ class ChatGLM4Tokenizer(PreTrainedTokenizer):
16
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
17
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_file,
22
+ padding_side="left",
23
+ clean_up_tokenization_spaces=False,
24
+ encode_special_tokens=False,
25
+ image_size=None,
26
+ **kwargs,
27
+ ):
28
+ self.name = "GLM4Tokenizer"
29
+ self.vocab_file = vocab_file
30
+ pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
31
+ self.pat_str = re.compile(pat_str)
32
+ self.encode_special_tokens = encode_special_tokens
33
+ self.image_size = image_size
34
+
35
+ mergeable_ranks = {}
36
+ with open(vocab_file) as f:
37
+ for line in f:
38
+ token, rank = line.strip().split()
39
+ rank = int(rank)
40
+ token = base64.b64decode(token)
41
+ mergeable_ranks[token] = rank
42
+
43
+ self.mergeable_ranks = mergeable_ranks
44
+
45
+ self.tokenizer = tiktoken.Encoding(
46
+ name="my_tokenizer",
47
+ pat_str=pat_str,
48
+ mergeable_ranks=mergeable_ranks,
49
+ special_tokens={},
50
+ )
51
+ self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
52
+ self.n_words = len(self.decoder)
53
+
54
+ super().__init__(
55
+ padding_side=padding_side,
56
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
57
+ **kwargs,
58
+ )
59
+
60
+ @property
61
+ def vocab_size(self):
62
+ return self.n_words
63
+
64
+ def get_vocab(self):
65
+ """Returns vocab as a dict"""
66
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
67
+ vocab.update(self.added_tokens_encoder)
68
+ return vocab
69
+
70
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str, int]]) -> str:
71
+ """
72
+ Converts a sequence of tokens in a single string.
73
+ """
74
+ text = ""
75
+ temp = b""
76
+ for t in tokens:
77
+ if isinstance(t, int):
78
+ t = chr(t)
79
+ if isinstance(t, str):
80
+ if temp:
81
+ text += temp.decode("utf-8", errors="replace")
82
+ elif isinstance(t, bytes):
83
+ temp += t
84
+ else:
85
+ raise TypeError("token should only be of type int, bytes or str")
86
+ if temp:
87
+ text += temp.decode("utf-8", errors="replace")
88
+ return text
89
+
90
+ def _tokenize(self, text, **kwargs):
91
+ tokens = []
92
+ ids = self.tokenizer.encode(text)
93
+ for t in ids:
94
+ tokens.append(self.decoder[t])
95
+ return tokens
96
+
97
+ def _convert_token_to_id(self, token):
98
+ """Converts a token (str) in an id using the vocab."""
99
+ return self.mergeable_ranks[token]
100
+
101
+ def _convert_id_to_token(self, index):
102
+ """Converts an index (integer) in a token (str) using the vocab."""
103
+ return self.decoder.get(index, "")
104
+
105
+ def save_vocabulary(self, save_directory, filename_prefix=None):
106
+ """
107
+ Save the vocabulary and special tokens file to a directory.
108
+
109
+ Args:
110
+ save_directory (`str`):
111
+ The directory in which to save the vocabulary.
112
+ filename_prefix (`str`, *optional*):
113
+ An optional prefix to add to the named of the saved files.
114
+
115
+ Returns:
116
+ `Tuple(str)`: Paths to the files saved.
117
+ """
118
+ if os.path.isdir(save_directory):
119
+ vocab_file = os.path.join(
120
+ save_directory, self.vocab_files_names["vocab_file"]
121
+ )
122
+ else:
123
+ vocab_file = save_directory
124
+
125
+ with open(self.vocab_file, "rb") as fin:
126
+ proto_str = fin.read()
127
+
128
+ with open(vocab_file, "wb") as writer:
129
+ writer.write(proto_str)
130
+
131
+ return (vocab_file,)
132
+
133
+ def get_prefix_tokens(self):
134
+ prefix_tokens = [
135
+ self.convert_tokens_to_ids("[gMASK]"),
136
+ self.convert_tokens_to_ids("<sop>"),
137
+ ]
138
+ return prefix_tokens
139
+
140
+ def build_single_message(
141
+ self, role, metadata, message, tokenize=True, message_prefix=None
142
+ ):
143
+ assert role in ["system", "user", "assistant", "observation"], role
144
+ if tokenize:
145
+ role_tokens = [
146
+ self.convert_tokens_to_ids(f"<|{role}|>")
147
+ ] + self.tokenizer.encode(f"{metadata}\n", disallowed_special=())
148
+ message_tokens = self.tokenizer.encode(message, disallowed_special=())
149
+ if message_prefix is not None:
150
+ message_tokens = message_prefix + message_tokens
151
+ tokens = role_tokens + message_tokens
152
+ return tokens
153
+ else:
154
+ return str(f"<|{role}|>{metadata}\n{message}")
155
+
156
+ def apply_chat_template(
157
+ self,
158
+ conversation: Union[
159
+ List[Dict[str, str]], List[List[Dict[str, str]]], "Conversation"
160
+ ],
161
+ add_generation_prompt: bool = False,
162
+ tokenize: bool = True,
163
+ padding: bool = False,
164
+ truncation: bool = False,
165
+ max_length: Optional[int] = None,
166
+ return_tensors: Optional[Union[str, TensorType]] = None,
167
+ return_dict: bool = False,
168
+ tokenizer_kwargs: Optional[Dict[str, Any]] = None,
169
+ add_special_tokens: bool = True,
170
+ **kwargs,
171
+ ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
172
+ if return_dict and not tokenize:
173
+ raise ValueError(
174
+ "`return_dict=True` is incompatible with `tokenize=False`, because there is no dict "
175
+ "of tokenizer outputs to return."
176
+ )
177
+
178
+ def handle_single_conversation(conversation):
179
+ input_ids = self.get_prefix_tokens() if add_special_tokens else []
180
+ input_message = "[gMASK]<sop>" if add_special_tokens else ""
181
+ input_image = None
182
+ transform = transforms.Compose(
183
+ [
184
+ transforms.Resize(
185
+ (self.image_size, self.image_size),
186
+ interpolation=transforms.InterpolationMode.BICUBIC,
187
+ ),
188
+ transforms.ToTensor(),
189
+ transforms.Normalize(
190
+ (0.48145466, 0.4578275, 0.40821073),
191
+ (0.26862954, 0.26130258, 0.27577711),
192
+ ),
193
+ ]
194
+ )
195
+ for item in conversation:
196
+ message = ""
197
+ message_prefix = None
198
+ if item.get("image"):
199
+ assert input_image is None, "Multiple images are not supported"
200
+ input_image = transform(item["image"])
201
+ message_prefix = self.convert_tokens_to_ids(
202
+ ["<|begin_of_image|>", "<|endoftext|>", "<|end_of_image|>"]
203
+ )
204
+ if item.get("content"):
205
+ message += item["content"]
206
+ if message or message_prefix:
207
+ input = self.build_single_message(
208
+ item["role"],
209
+ item.get("metadata", ""),
210
+ message,
211
+ tokenize=tokenize,
212
+ message_prefix=message_prefix,
213
+ )
214
+ if tokenize:
215
+ input_ids.extend(input)
216
+ else:
217
+ input_message += input
218
+ if add_generation_prompt:
219
+ if tokenize:
220
+ input_ids.extend([self.convert_tokens_to_ids("<|assistant|>"), 198]) # 198 is \n in the vocab
221
+ else:
222
+ input_message += "<|assistant|>\n"
223
+ return {
224
+ "input": input_ids if tokenize else input_message,
225
+ "image": input_image,
226
+ }
227
+
228
+ # Main logic to handle different conversation formats
229
+ if isinstance(conversation, list) and all(
230
+ isinstance(i, dict) for i in conversation
231
+ ):
232
+ result = handle_single_conversation(conversation)
233
+ input_ids = result["input"]
234
+ input_images = [result["image"]]
235
+ elif isinstance(conversation, list) and all(
236
+ isinstance(i, list) for i in conversation
237
+ ):
238
+ results = [handle_single_conversation(c) for c in conversation]
239
+ input_ids = [item["input"] for item in results]
240
+ input_images = [item["image"] for item in results]
241
+ elif hasattr(conversation, "messages"):
242
+ result = handle_single_conversation(conversation.messages)
243
+ input_ids = result["input"]
244
+ input_images = [result["image"]]
245
+ else:
246
+ raise ValueError("Invalid conversation format")
247
+
248
+ if tokenize:
249
+ output = self.batch_encode_plus(
250
+ [input_ids] if isinstance(input_ids[0], int) else input_ids,
251
+ padding=padding,
252
+ truncation=truncation,
253
+ max_length=max_length,
254
+ return_tensors=return_tensors,
255
+ is_split_into_words=True,
256
+ add_special_tokens=False,
257
+ )
258
+ if return_dict:
259
+ found_image = False
260
+ for image in input_images:
261
+ if image is not None:
262
+ found_image = True
263
+ break
264
+ if found_image:
265
+ output["images"] = torch.stack(input_images)
266
+ return output
267
+ else:
268
+ return output["input_ids"]
269
+ else:
270
+ return input_ids
271
+
272
+ def build_inputs_with_special_tokens(
273
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
274
+ ) -> List[int]:
275
+ """
276
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
277
+ adding special tokens. A BERT sequence has the following format:
278
+
279
+ - single sequence: `[CLS] X [SEP]`
280
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
281
+
282
+ Args:
283
+ token_ids_0 (`List[int]`):
284
+ List of IDs to which the special tokens will be added.
285
+ token_ids_1 (`List[int]`, *optional*):
286
+ Optional second list of IDs for sequence pairs.
287
+
288
+ Returns:
289
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
290
+ """
291
+ prefix_tokens = self.get_prefix_tokens()
292
+ token_ids_0 = prefix_tokens + token_ids_0
293
+ if token_ids_1 is not None:
294
+ token_ids_0 = (
295
+ token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
296
+ )
297
+ return token_ids_0
298
+
299
+ def _pad(
300
+ self,
301
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
302
+ max_length: Optional[int] = None,
303
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
304
+ pad_to_multiple_of: Optional[int] = None,
305
+ padding_side: Optional[str] = None,
306
+ return_attention_mask: Optional[bool] = None,
307
+ ) -> dict:
308
+ """
309
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
310
+
311
+ Args:
312
+ encoded_inputs:
313
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
314
+ max_length: maximum length of the returned list and optionally padding length (see below).
315
+ Will truncate by taking into account the special tokens.
316
+ padding_strategy: PaddingStrategy to use for padding.
317
+
318
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
319
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
320
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
321
+ The tokenizer padding sides are defined in self.padding_side:
322
+
323
+ - 'left': pads on the left of the sequences
324
+ - 'right': pads on the right of the sequences
325
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
326
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
327
+ `>= 7.5` (Volta).
328
+ return_attention_mask:
329
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
330
+ """
331
+ # Load from model defaults
332
+ assert self.padding_side == "left"
333
+
334
+ required_input = encoded_inputs[self.model_input_names[0]]
335
+ seq_length = len(required_input)
336
+
337
+ if padding_strategy == PaddingStrategy.LONGEST:
338
+ max_length = len(required_input)
339
+
340
+ if (
341
+ max_length is not None
342
+ and pad_to_multiple_of is not None
343
+ and (max_length % pad_to_multiple_of != 0)
344
+ ):
345
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
346
+
347
+ needs_to_be_padded = (
348
+ padding_strategy != PaddingStrategy.DO_NOT_PAD
349
+ and len(required_input) != max_length
350
+ )
351
+
352
+ # Initialize attention mask if not present.
353
+ if "attention_mask" not in encoded_inputs:
354
+ encoded_inputs["attention_mask"] = [1] * seq_length
355
+
356
+ if "position_ids" not in encoded_inputs:
357
+ encoded_inputs["position_ids"] = list(range(seq_length))
358
+
359
+ if needs_to_be_padded:
360
+ difference = max_length - len(required_input)
361
+
362
+ if "attention_mask" in encoded_inputs:
363
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs[
364
+ "attention_mask"
365
+ ]
366
+ if "position_ids" in encoded_inputs:
367
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs[
368
+ "position_ids"
369
+ ]
370
+ encoded_inputs[self.model_input_names[0]] = [
371
+ self.pad_token_id
372
+ ] * difference + required_input
373
+
374
+ return encoded_inputs
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a493598071550244b2ee7f26118f3edec2150b9dfa967929a99052ac83fe716
3
+ size 2623634
tokenizer_config.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_chatglm.ChatGLM4Tokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "added_tokens_decoder": {
9
+ "151329": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false,
15
+ "special": true
16
+ },
17
+ "151330": {
18
+ "content": "[MASK]",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false,
23
+ "special": true
24
+ },
25
+ "151331": {
26
+ "content": "[gMASK]",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false,
31
+ "special": true
32
+ },
33
+ "151332": {
34
+ "content": "[sMASK]",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false,
39
+ "special": true
40
+ },
41
+ "151333": {
42
+ "content": "<sop>",
43
+ "lstrip": false,
44
+ "normalized": false,
45
+ "rstrip": false,
46
+ "single_word": false,
47
+ "special": true
48
+ },
49
+ "151334": {
50
+ "content": "<eop>",
51
+ "lstrip": false,
52
+ "normalized": false,
53
+ "rstrip": false,
54
+ "single_word": false,
55
+ "special": true
56
+ },
57
+ "151335": {
58
+ "content": "<|system|>",
59
+ "lstrip": false,
60
+ "normalized": false,
61
+ "rstrip": false,
62
+ "single_word": false,
63
+ "special": true
64
+ },
65
+ "151336": {
66
+ "content": "<|user|>",
67
+ "lstrip": false,
68
+ "normalized": false,
69
+ "rstrip": false,
70
+ "single_word": false,
71
+ "special": true
72
+ },
73
+ "151337": {
74
+ "content": "<|assistant|>",
75
+ "lstrip": false,
76
+ "normalized": false,
77
+ "rstrip": false,
78
+ "single_word": false,
79
+ "special": true
80
+ },
81
+ "151338": {
82
+ "content": "<|observation|>",
83
+ "lstrip": false,
84
+ "normalized": false,
85
+ "rstrip": false,
86
+ "single_word": false,
87
+ "special": true
88
+ },
89
+ "151339": {
90
+ "content": "<|begin_of_image|>",
91
+ "lstrip": false,
92
+ "normalized": false,
93
+ "rstrip": false,
94
+ "single_word": false,
95
+ "special": true
96
+ },
97
+ "151340": {
98
+ "content": "<|end_of_image|>",
99
+ "lstrip": false,
100
+ "normalized": false,
101
+ "rstrip": false,
102
+ "single_word": false,
103
+ "special": true
104
+ },
105
+ "151341": {
106
+ "content": "<|begin_of_video|>",
107
+ "lstrip": false,
108
+ "normalized": false,
109
+ "rstrip": false,
110
+ "single_word": false,
111
+ "special": true
112
+ },
113
+ "151342": {
114
+ "content": "<|end_of_video|>",
115
+ "lstrip": false,
116
+ "normalized": false,
117
+ "rstrip": false,
118
+ "single_word": false,
119
+ "special": true
120
+ }
121
+ },
122
+ "additional_special_tokens": ["<|endoftext|>", "[MASK]", "[gMASK]", "[sMASK]", "<sop>", "<eop>", "<|system|>",
123
+ "<|user|>", "<|assistant|>", "<|observation|>", "<|begin_of_image|>", "<|end_of_image|>",
124
+ "<|begin_of_video|>", "<|end_of_video|>"],
125
+ "clean_up_tokenization_spaces": false,
126
+ "do_lower_case": false,
127
+ "eos_token": "<|endoftext|>",
128
+ "pad_token": "<|endoftext|>",
129
+ "model_max_length": 8192,
130
+ "padding_side": "left",
131
+ "remove_space": false,
132
+ "tokenizer_class": "ChatGLM4Tokenizer",
133
+ "image_size": 1120
134
+ }
visual.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from argparse import Namespace
4
+ import torch.nn.functional as F
5
+ from transformers.activations import ACT2FN
6
+ import math
7
+ from torch.nn import LayerNorm
8
+
9
+
10
+ def standard_attention(
11
+ query_layer, key_layer, value_layer, scaling_attention_score=True
12
+ ):
13
+ if scaling_attention_score:
14
+ query_layer = query_layer / math.sqrt(query_layer.shape[-1])
15
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
16
+ attention_probs = F.softmax(attention_scores, dim=-1)
17
+ context_layer = torch.matmul(attention_probs, value_layer)
18
+ return context_layer
19
+
20
+
21
+ def attention_fn_default(
22
+ query_layer, key_layer, value_layer, scaling_attention_score=True
23
+ ):
24
+ if int(torch.__version__.split(".")[0]) >= 2 and scaling_attention_score:
25
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
26
+ query_layer,
27
+ key_layer,
28
+ value_layer,
29
+ attn_mask=None,
30
+ dropout_p=0.0,
31
+ is_causal=False,
32
+ )
33
+ return attn_output
34
+ else:
35
+ return standard_attention(
36
+ query_layer,
37
+ key_layer,
38
+ value_layer,
39
+ scaling_attention_score=scaling_attention_score,
40
+ )
41
+
42
+
43
+ class PatchEmbedding(nn.Module):
44
+ def __init__(self, config):
45
+ super().__init__()
46
+ self.proj = nn.Conv2d(
47
+ config.in_channels,
48
+ config.hidden_size,
49
+ kernel_size=config.patch_size,
50
+ stride=config.patch_size,
51
+ )
52
+ self.cls_embedding = nn.Parameter(torch.zeros(1, config.hidden_size))
53
+ self.position_embedding = nn.Embedding(config.num_positions, config.hidden_size)
54
+
55
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
56
+ x = self.proj(images)
57
+ x = x.flatten(2).transpose(1, 2)
58
+ x += self.position_embedding.weight[1:, :].unsqueeze(0)
59
+ return x
60
+
61
+
62
+ class Attention(nn.Module):
63
+ def __init__(self, config):
64
+ super().__init__()
65
+ self.num_heads = config.num_heads
66
+ head_dim = config.hidden_size // config.num_heads
67
+ self.scale = head_dim**-0.5
68
+ self.query_key_value = nn.Linear(config.hidden_size, config.hidden_size * 3)
69
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
70
+ self.output_dropout = torch.nn.Dropout(config.dropout_prob)
71
+
72
+ def forward(self, x: "tensor(B, L, D)") -> "tensor(B, L, D)":
73
+ B, L, _ = x.shape
74
+ qkv = self.query_key_value(x)
75
+ qkv = qkv.reshape(B, L, self.num_heads, 3, -1).permute(
76
+ 3, 0, 2, 1, 4
77
+ ) # 3, B, H, L, D
78
+ q, k, v = qkv[0], qkv[1], qkv[2]
79
+
80
+ out = attention_fn_default(q, k, v)
81
+ output = self.dense(out.transpose(1, 2).reshape(B, L, -1))
82
+ output = self.output_dropout(output)
83
+ return output
84
+
85
+ def attention(self, q, k, v):
86
+ attn_weights = torch.matmul(q * self.scale, k.transpose(-2, -1))
87
+ attn_weights = attn_weights.softmax(dim=-1)
88
+ output = torch.matmul(attn_weights, v)
89
+ return output
90
+
91
+
92
+ class MLP(nn.Module):
93
+ def __init__(self, config):
94
+ super().__init__()
95
+ self.config = config
96
+ self.activation_fn = ACT2FN[config.hidden_act]
97
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
98
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
99
+
100
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
101
+ x = self.fc1(x)
102
+ x = self.activation_fn(x)
103
+ x = self.fc2(x)
104
+ return x
105
+
106
+
107
+ class TransformerLayer(nn.Module):
108
+ def __init__(self, config):
109
+ super().__init__()
110
+ self.input_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
111
+ self.attention = Attention(config)
112
+ self.mlp = MLP(config)
113
+ self.post_attention_layernorm = LayerNorm(
114
+ config.hidden_size, eps=config.layer_norm_eps
115
+ )
116
+
117
+ def forward(self, hidden_states):
118
+ attention_input = hidden_states
119
+ attention_output = self.input_layernorm(self.attention(attention_input))
120
+ hidden_states = attention_input + attention_output
121
+ mlp_input = hidden_states
122
+ mlp_output = self.post_attention_layernorm(self.mlp(mlp_input)).to(
123
+ mlp_input.device
124
+ )
125
+ output = mlp_input + mlp_output
126
+ return output
127
+
128
+
129
+ class Transformer(nn.Module):
130
+ def __init__(self, config):
131
+ super().__init__()
132
+ self.layers = nn.ModuleList(
133
+ [TransformerLayer(config) for _ in range(config.num_hidden_layers)]
134
+ )
135
+
136
+ def forward(self, hidden_states):
137
+ for layer_module in self.layers:
138
+ hidden_states = layer_module(hidden_states)
139
+ return hidden_states
140
+
141
+
142
+ class GLU(nn.Module):
143
+ def __init__(self, config, in_features):
144
+ super().__init__()
145
+ self.linear_proj = nn.Linear(in_features, config.hidden_size, bias=False)
146
+ self.norm1 = nn.LayerNorm(config.hidden_size)
147
+ self.act1 = nn.GELU()
148
+ self.act2 = nn.functional.silu
149
+ self.dense_h_to_4h = nn.Linear(
150
+ config.hidden_size, config.ffn_hidden_size, bias=False
151
+ )
152
+ self.gate_proj = nn.Linear(
153
+ config.hidden_size, config.ffn_hidden_size, bias=False
154
+ )
155
+ self.dense_4h_to_h = nn.Linear(
156
+ config.ffn_hidden_size, config.hidden_size, bias=False
157
+ )
158
+
159
+ def forward(self, x):
160
+ x = self.linear_proj(x)
161
+ x = self.act1(self.norm1(x))
162
+ x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
163
+ x = self.dense_4h_to_h(x)
164
+ return x
165
+
166
+
167
+ class EVA2CLIPModel(nn.Module):
168
+ def __init__(self, config):
169
+ super().__init__()
170
+ vision_config = Namespace(**config.vision_config)
171
+ self.patch_embedding = PatchEmbedding(vision_config)
172
+ self.transformer = Transformer(vision_config)
173
+ self.linear_proj = GLU(config, in_features=config.hidden_size)
174
+ self.conv = nn.Conv2d(
175
+ in_channels=vision_config.hidden_size,
176
+ out_channels=config.hidden_size,
177
+ kernel_size=2,
178
+ stride=2,
179
+ )
180
+ self.boi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
181
+ self.eoi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
182
+ self.scaling_factor = vision_config.scaling_factor
183
+
184
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
185
+ x = self.patch_embedding(images)
186
+ x = self.transformer(x)
187
+
188
+ b, s, h = x.shape
189
+ grid_size = int(s**0.5)
190
+ x = x.view(b, grid_size, grid_size, h).permute(0, 3, 1, 2)
191
+ x = self.conv(x)
192
+
193
+ x = x.flatten(2).transpose(1, 2)
194
+ x = self.linear_proj(x)
195
+ boi = self.boi.expand(x.shape[0], -1, -1).to(x.device)
196
+ eoi = self.eoi.expand(x.shape[0], -1, -1).to(x.device)
197
+ x = torch.cat((boi, x, eoi), dim=1)
198
+
199
+ return x