coin_model_funtuned_LICENSE ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The glm-4-9b License
2
+
3
+ 1. 定义
4
+
5
+ “许可方”是指分发其软件的 glm-4-9b 模型团队。
6
+ “软件”是指根据本许可提供的 glm-4-9b 模型参数。
7
+
8
+ 2. 许可授予
9
+
10
+ 根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
11
+ 本许可允许您免费使用本仓库中的所有开源模型进行学术研究,对于希望将模型用于商业目的的用户,需在[这里](https://open.bigmodel.cn/mla/form)完成登记。经过登记的用户可以免费使用本模型进行商业活动,但必须遵守本许可的所有条款和条件。
12
+ 上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
13
+ 如果您分发或提供 THUDM / 智谱AI 关于 glm-4 开源模型的材料(或其任何衍生作品),或使用其中任何材料(包括 glm-4 系列的所有开源模型)的产品或服务,您应:
14
+
15
+ (A) 随任何此类 THUDM / 智谱AI 材料提供本协议的副本;
16
+ (B) 在相关网站、用户界面、博客文章、关于页面或产品文档上突出显示 “Built with glm-4”。
17
+ 如果您使用 THUDM / 智谱AI的 glm-4 开源模型的材料来创建、训练、微调或以其他方式改进已分发或可用的 AI 模型,您还应在任何此类 AI 模型名称的开头添加 “glm-4”。
18
+
19
+ 3. 限制
20
+
21
+ 您不得出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品。
22
+ 您不得利用本软件从事任何危害国家安全和国家统一,危害社会公共利益及公序良俗,侵犯他人商业秘密、知识产权、名誉权、肖像权、财产权等权益的行为。
23
+ 您在使用中应遵循使用地所适用的法律法规政策、道德规范等要求。
24
+
25
+ 4. 免责声明
26
+
27
+ 本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。
28
+ 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关
29
+ 软件。
30
+
31
+ 5. 责任限制
32
+
33
+ 除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、
34
+ 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
35
+
36
+ 6. 争议解决
37
+
38
+ 本许可受中华人民共和国法律管辖并按其解释。 因本许可引起的或与本许可有关的任何争议应提交北京市海淀区人民法院。
39
+ 请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 [email protected] 与我们联系。
40
+
41
+ 1. Definitions
42
+
43
+ “Licensor” means the glm-4-9b Model Team that distributes its Software.
44
+ “Software” means the glm-4-9b model parameters made available under this license.
45
+
46
+ 2. License
47
+
48
+ Under 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.
49
+ This license allows you to use all open source models in this repository for free for academic research. For users who wish to use the models for commercial purposes, please do so [here](https://open.bigmodel.cn/mla/form)
50
+ Complete registration. Registered users are free to use this model for commercial activities, but must comply with all terms and conditions of this license.
51
+ The copyright notice and this license notice shall be included in all copies or substantial portions of the Software.
52
+ If you distribute or provide THUDM / Zhipu AI materials on the glm-4 open source model (or any derivative works thereof), or products or services that use any materials therein (including all open source models of the glm-4 series), you should:
53
+
54
+ (A) Provide a copy of this Agreement with any such THUDM/Zhipu AI Materials;
55
+ (B) Prominently display "Built with glm-4" on the relevant website, user interface, blog post, related page or product documentation.
56
+ If you use materials from THUDM/Zhipu AI's glm-4 model to create, train, operate, or otherwise improve assigned or available AI models, you should also add "glm-4" to the beginning of any such AI model name.
57
+
58
+ 3. Restrictions
59
+
60
+ You are not allowed to use, copy, modify, merge, publish, distribute, copy or create all or part of the derivative works of this software for any military or illegal purposes.
61
+ You are not allowed to use this software to engage in any behavior that endangers national security and unity, endangers social public interests and public order, infringes on the rights and interests of others such as trade secrets, intellectual property rights, reputation rights, portrait rights, and property rights.
62
+ You should comply with the applicable laws, regulations, policies, ethical standards, and other requirements in the place of use during use.
63
+
64
+ 4. Disclaimer
65
+
66
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
67
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
68
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
69
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
+
71
+ 5. Limitation of Liability
72
+
73
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT,
74
+ NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL,
75
+ INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED
76
+ OF THE POSSIBILITY OF SUCH DAMAGES.
77
+
78
+ 6. Dispute Resolution
79
+
80
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute
81
+ arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
82
+
83
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and
84
+ copyright, please contact us at [email protected].
coin_model_funtuned_config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/glm-4v-9b",
3
+ "model_type": "chatglm",
4
+ "architectures": [
5
+ "ChatGLMModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
9
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
10
+ "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
11
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
12
+ "AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
13
+ },
14
+ "vision_config": {
15
+ "dropout_prob": 0.0,
16
+ "hidden_act": "gelu",
17
+ "in_channels": 3,
18
+ "num_hidden_layers": 63,
19
+ "hidden_size": 1792,
20
+ "patch_size": 14,
21
+ "num_heads": 16,
22
+ "intermediate_size": 15360,
23
+ "layer_norm_eps": 1e-06,
24
+ "num_positions": 6401,
25
+ "image_size": 1120,
26
+ "scaling_factor": 8
27
+ },
28
+ "add_bias_linear": false,
29
+ "add_qkv_bias": true,
30
+ "apply_query_key_layer_scaling": true,
31
+ "apply_residual_connection_post_layernorm": false,
32
+ "attention_dropout": 0.0,
33
+ "attention_softmax_in_fp32": true,
34
+ "attn_implementation": "sdpa",
35
+ "bias_dropout_fusion": true,
36
+ "ffn_hidden_size": 13696,
37
+ "fp32_residual_connection": false,
38
+ "hidden_dropout": 0.0,
39
+ "hidden_size": 4096,
40
+ "kv_channels": 128,
41
+ "layernorm_epsilon": 0.00000015625,
42
+ "multi_query_attention": true,
43
+ "multi_query_group_num": 2,
44
+ "num_attention_heads": 32,
45
+ "num_layers": 40,
46
+ "original_rope": true,
47
+ "padded_vocab_size": 151552,
48
+ "post_layer_norm": true,
49
+ "rmsnorm": true,
50
+ "seq_length": 8192,
51
+ "use_cache": true,
52
+ "torch_dtype": "bfloat16",
53
+ "transformers_version": "4.40.2",
54
+ "tie_word_embeddings": false,
55
+ "eos_token_id": [151329, 151336, 151338],
56
+ "pad_token_id": 151329,
57
+ "boi_token_id": 151339,
58
+ "eoi_token_id": 151340
59
+ }
coin_model_funtuned_configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"nli"}
coin_model_funtuned_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)
coin_model_funtuned_generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token_id": [
3
+ 151329,
4
+ 151336,
5
+ 151338
6
+ ],
7
+ "pad_token_id": 151329,
8
+ "do_sample": true,
9
+ "temperature": 0.8,
10
+ "max_length": 8192,
11
+ "top_p": 0.8,
12
+ "transformers_version": "4.40.2"
13
+ }
coin_model_funtuned_model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
coin_model_funtuned_modeling_chatglm.py ADDED
@@ -0,0 +1,1519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+ import json
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import re
7
+ import sys
8
+
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ import torch.nn.functional as F
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
14
+ from torch.nn.utils import skip_init
15
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
16
+ from copy import deepcopy
17
+
18
+ from transformers.modeling_outputs import (
19
+ BaseModelOutputWithPast,
20
+ CausalLMOutputWithPast,
21
+ SequenceClassifierOutputWithPast,
22
+ )
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.utils import logging, is_torch_npu_available
25
+ from transformers.generation.logits_process import LogitsProcessor
26
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
27
+
28
+ from .visual import EVA2CLIPModel
29
+ from .configuration_chatglm import ChatGLMConfig
30
+
31
+ try:
32
+ from transformers.utils import is_flash_attn_greater_or_equal_2_10, is_flash_attn_2_available
33
+ if is_flash_attn_2_available():
34
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
35
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
36
+ except:
37
+ pass
38
+
39
+ # flags required to enable jit fusion kernels
40
+
41
+ if sys.platform != 'darwin' and not is_torch_npu_available():
42
+ torch._C._jit_set_profiling_mode(False)
43
+ torch._C._jit_set_profiling_executor(False)
44
+ torch._C._jit_override_can_fuse_on_cpu(True)
45
+ torch._C._jit_override_can_fuse_on_gpu(True)
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ LANGUAGE_TOKEN_TYPE = 0
50
+ VISION_TOKEN_TYPE = 1
51
+
52
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
53
+ _CONFIG_FOR_DOC = "ChatGLMConfig"
54
+
55
+
56
+ def default_init(cls, *args, **kwargs):
57
+ return cls(*args, **kwargs)
58
+
59
+
60
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
61
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
62
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
63
+ scores.zero_()
64
+ scores[..., 198] = 5e4
65
+ return scores
66
+
67
+
68
+ class PrefixEncoder(torch.nn.Module):
69
+ """
70
+ The torch.nn model to encode the prefix
71
+ Input shape: (batch-size, prefix-length)
72
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
73
+ """
74
+
75
+ def __init__(self, config: ChatGLMConfig):
76
+ super().__init__()
77
+ self.prefix_projection = config.prefix_projection
78
+ if self.prefix_projection:
79
+ # Use a two-layer MLP to encode the prefix
80
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
81
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
82
+ self.trans = torch.nn.Sequential(
83
+ torch.nn.Linear(kv_size, config.hidden_size),
84
+ torch.nn.Tanh(),
85
+ torch.nn.Linear(config.hidden_size, kv_size)
86
+ )
87
+ else:
88
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
89
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
90
+
91
+ def forward(self, prefix: torch.Tensor):
92
+ if self.prefix_projection:
93
+ prefix_tokens = self.embedding(prefix)
94
+ past_key_values = self.trans(prefix_tokens)
95
+ else:
96
+ past_key_values = self.embedding(prefix)
97
+ return past_key_values
98
+
99
+
100
+ def split_tensor_along_last_dim(
101
+ tensor: torch.Tensor,
102
+ num_partitions: int,
103
+ contiguous_split_chunks: bool = False,
104
+ ) -> List[torch.Tensor]:
105
+ """Split a tensor along its last dimension.
106
+
107
+ Arguments:
108
+ tensor: input tensor.
109
+ num_partitions: number of partitions to split the tensor
110
+ contiguous_split_chunks: If True, make each chunk contiguous
111
+ in memory.
112
+
113
+ Returns:
114
+ A list of Tensors
115
+ """
116
+ # Get the size and dimension.
117
+ last_dim = tensor.dim() - 1
118
+ last_dim_size = tensor.size()[last_dim] // num_partitions
119
+ # Split.
120
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
121
+ # Note: torch.split does not create contiguous tensors by default.
122
+ if contiguous_split_chunks:
123
+ return tuple(chunk.contiguous() for chunk in tensor_list)
124
+
125
+ return tensor_list
126
+
127
+
128
+ class RotaryEmbedding(nn.Module):
129
+ def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
130
+ super().__init__()
131
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
132
+ self.register_buffer("inv_freq", inv_freq)
133
+ self.dim = dim
134
+ self.original_impl = original_impl
135
+ self.rope_ratio = rope_ratio
136
+
137
+ def impl(self, seq_length: int, dim: int, device: torch.device, dtype: torch.dtype):
138
+ base = 10000 * self.rope_ratio
139
+ inv_freq = 1.0 / (
140
+ base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
141
+ seq = torch.arange(seq_length, device=inv_freq.device, dtype=torch.float32)
142
+ freqs = torch.outer(seq, inv_freq)
143
+ # first part even vector components, second part odd vector components,
144
+ # 2 * dim in dimension size
145
+ emb = torch.cat((freqs, freqs), dim=-1)
146
+ return emb
147
+
148
+ def forward_impl(
149
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
150
+ ):
151
+ """Enhanced Transformer with Rotary Position Embedding.
152
+
153
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
154
+ transformers/rope/__init__.py. MIT License:
155
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
156
+ """
157
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
158
+ base = base * self.rope_ratio
159
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
160
+
161
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
162
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
163
+
164
+ # Calculate the product of position index and $\theta_i$
165
+ idx_theta = torch.outer(seq_idx, theta).float()
166
+
167
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
168
+
169
+ # this is to mimic the behaviour of complex32, else we will get different results
170
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
171
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
172
+ return cache
173
+
174
+ def forward(self, max_seq_len, offset=0):
175
+ if self.original_impl:
176
+ return self.forward_impl(
177
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
178
+ )
179
+ else:
180
+ return self.impl(max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device)
181
+
182
+
183
+ @torch.jit.script
184
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
185
+ # x: [b, np, sq, hn]
186
+ b, np, sq, hn = x.size(0), x.size(1), x.size(2), x.size(3)
187
+ rot_dim = rope_cache.shape[-2] * 2
188
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
189
+ # truncate to support variable sizes
190
+ rope_cache = rope_cache[:, :sq]
191
+ xshaped = x.reshape(b, np, sq, rot_dim // 2, 2)
192
+ rope_cache = rope_cache.view(-1, 1, sq, xshaped.size(3), 2)
193
+ x_out2 = torch.stack(
194
+ [
195
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
196
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
197
+ ],
198
+ -1,
199
+ )
200
+ x_out2 = x_out2.flatten(3)
201
+ return torch.cat((x_out2, x_pass), dim=-1)
202
+
203
+
204
+ class RMSNorm(torch.nn.Module):
205
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
206
+ super().__init__()
207
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
208
+ self.eps = eps
209
+
210
+ def forward(self, hidden_states: torch.Tensor):
211
+ input_dtype = hidden_states.dtype
212
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
213
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
214
+
215
+ return (self.weight * hidden_states).to(input_dtype)
216
+
217
+
218
+ class CoreAttention(torch.nn.Module):
219
+ def __init__(self, config: ChatGLMConfig, layer_number):
220
+ super(CoreAttention, self).__init__()
221
+
222
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
223
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
224
+ if self.apply_query_key_layer_scaling:
225
+ self.attention_softmax_in_fp32 = True
226
+ self.layer_number = max(1, layer_number)
227
+
228
+ projection_size = config.kv_channels * config.num_attention_heads
229
+
230
+ # Per attention head and per partition values.
231
+ self.hidden_size_per_partition = projection_size
232
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
233
+ self.num_attention_heads_per_partition = config.num_attention_heads
234
+
235
+ coeff = None
236
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
237
+ if self.apply_query_key_layer_scaling:
238
+ coeff = self.layer_number
239
+ self.norm_factor *= coeff
240
+ self.coeff = coeff
241
+
242
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
243
+
244
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
245
+ pytorch_major_version = int(torch.__version__.split('.')[0])
246
+ if pytorch_major_version >= 2:
247
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
248
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
249
+ is_causal=True)
250
+ else:
251
+ if attention_mask is not None:
252
+ attention_mask = ~attention_mask
253
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
254
+ attention_mask)
255
+ context_layer = context_layer.transpose(1, 2).contiguous()
256
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
257
+ context_layer = context_layer.reshape(*new_context_layer_shape)
258
+ else:
259
+ # Raw attention scores
260
+
261
+ # [b, np, sq, sk]
262
+ output_size = (query_layer.size(0), query_layer.size(1), query_layer.size(2), key_layer.size(2))
263
+
264
+ # [b, np, sq, hn] -> [b * np, sq, hn]
265
+ query_layer = query_layer.view(output_size[0] * output_size[1], output_size[2], -1)
266
+ # [b, np, sk, hn] -> [b * np, sk, hn]
267
+ key_layer = key_layer.view(output_size[0] * output_size[1], output_size[3], -1)
268
+
269
+ # preallocting input tensor: [b * np, sq, sk]
270
+ matmul_input_buffer = torch.empty(
271
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
272
+ device=query_layer.device
273
+ )
274
+
275
+ # Raw attention scores. [b * np, sq, sk]
276
+ matmul_result = torch.baddbmm(
277
+ matmul_input_buffer,
278
+ query_layer, # [b * np, sq, hn]
279
+ key_layer.transpose(1, 2), # [b * np, hn, sk]
280
+ beta=0.0,
281
+ alpha=(1.0 / self.norm_factor),
282
+ )
283
+
284
+ # change view to [b, np, sq, sk]
285
+ attention_scores = matmul_result.view(*output_size)
286
+
287
+ # ===========================
288
+ # Attention probs and dropout
289
+ # ===========================
290
+
291
+ # attention scores and attention mask [b, np, sq, sk]
292
+ if self.attention_softmax_in_fp32:
293
+ attention_scores = attention_scores.float()
294
+ if self.coeff is not None:
295
+ attention_scores = attention_scores * self.coeff
296
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
297
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
298
+ device=attention_scores.device, dtype=torch.bool)
299
+ attention_mask.tril_()
300
+ attention_mask = ~attention_mask
301
+ if attention_mask is not None:
302
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
303
+ attention_probs = F.softmax(attention_scores, dim=-1)
304
+ attention_probs = attention_probs.type_as(value_layer)
305
+
306
+ # This is actually dropping out entire tokens to attend to, which might
307
+ # seem a bit unusual, but is taken from the original Transformer paper.
308
+ attention_probs = self.attention_dropout(attention_probs)
309
+ # =========================
310
+ # Context layer. [sq, b, hp]
311
+ # =========================
312
+
313
+ # value_layer -> context layer.
314
+ # [sk, b, np, hn] --> [b, np, sq, hn]
315
+
316
+ # context layer shape: [b, np, sq, hn]
317
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
318
+ # change view [b * np, sk, hn]
319
+ value_layer = value_layer.view(output_size[0] * output_size[1], value_layer.size(2), -1)
320
+ # change view [b * np, sq, sk]
321
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
322
+ # matmul: [b * np, sq, hn]
323
+ context_layer = torch.bmm(attention_probs, value_layer)
324
+ # change view [b, np, sq, hn]
325
+ context_layer = context_layer.view(*output_size)
326
+ # [b, np, sq, hn] --> [b, sq, np, hn]
327
+ context_layer = context_layer.transpose(1, 2).contiguous()
328
+ # [b, sq, np, hn] --> [b, sq, hp]
329
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
330
+ context_layer = context_layer.reshape(*new_context_layer_shape)
331
+
332
+ return context_layer
333
+
334
+
335
+ class SdpaAttention(CoreAttention):
336
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
337
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
338
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
339
+ is_causal=True,
340
+ dropout_p=self.config.attention_dropout if self.training else 0.0)
341
+ else:
342
+ if attention_mask is not None:
343
+ attention_mask = ~attention_mask
344
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
345
+ attention_mask,
346
+ dropout_p=self.config.attention_dropout if self.training else 0.0)
347
+ context_layer = context_layer.transpose(1, 2).contiguous()
348
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
349
+ context_layer = context_layer.reshape(*new_context_layer_shape)
350
+ return context_layer
351
+
352
+
353
+ def _get_unpad_data(attention_mask):
354
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
355
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
356
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
357
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
358
+ return (
359
+ indices,
360
+ cu_seqlens,
361
+ max_seqlen_in_batch,
362
+ )
363
+
364
+
365
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2
366
+ class FlashAttention2(CoreAttention):
367
+ def __init__(self, *args, **kwargs):
368
+ super().__init__(*args, **kwargs)
369
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
370
+
371
+ def forward(self, query_states, key_states, value_states, attention_mask):
372
+ query_states = query_states.transpose(1, 2)
373
+ key_states = key_states.transpose(1, 2)
374
+ value_states = value_states.transpose(1, 2)
375
+ batch_size, query_length = query_states.shape[:2]
376
+ if not self._flash_attn_uses_top_left_mask:
377
+ causal = self.is_causal
378
+ else:
379
+ # 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__.
380
+ causal = self.is_causal and query_length != 1
381
+ dropout = self.config.attention_dropout if self.training else 0.0
382
+ # Contains at least one padding token in the sequence
383
+ if attention_mask is not None:
384
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
385
+ query_states, key_states, value_states, attention_mask, query_length
386
+ )
387
+
388
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
389
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
390
+
391
+ attn_output_unpad = flash_attn_varlen_func(
392
+ query_states,
393
+ key_states,
394
+ value_states,
395
+ cu_seqlens_q=cu_seqlens_q,
396
+ cu_seqlens_k=cu_seqlens_k,
397
+ max_seqlen_q=max_seqlen_in_batch_q,
398
+ max_seqlen_k=max_seqlen_in_batch_k,
399
+ dropout_p=dropout,
400
+ softmax_scale=None,
401
+ causal=causal,
402
+ )
403
+
404
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
405
+ else:
406
+ attn_output = flash_attn_func(
407
+ query_states, key_states, value_states, dropout, softmax_scale=None, causal=causal
408
+ )
409
+ attn_output = attn_output.reshape(batch_size, query_length, self.hidden_size_per_partition).contiguous()
410
+ return attn_output
411
+
412
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
413
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
414
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
415
+
416
+ key_layer = index_first_axis(
417
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
418
+ )
419
+ value_layer = index_first_axis(
420
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
421
+ )
422
+ if query_length == kv_seq_len:
423
+ query_layer = index_first_axis(
424
+ query_layer.reshape(batch_size * kv_seq_len, self.num_attention_heads_per_partition, head_dim),
425
+ indices_k
426
+ )
427
+ cu_seqlens_q = cu_seqlens_k
428
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
429
+ indices_q = indices_k
430
+ elif query_length == 1:
431
+ max_seqlen_in_batch_q = 1
432
+ cu_seqlens_q = torch.arange(
433
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
434
+ ) # There is a memcpy here, that is very bad.
435
+ indices_q = cu_seqlens_q[:-1]
436
+ query_layer = query_layer.squeeze(1)
437
+ else:
438
+ # The -q_len: slice assumes left padding.
439
+ attention_mask = attention_mask[:, -query_length:]
440
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
441
+
442
+ return (
443
+ query_layer,
444
+ key_layer,
445
+ value_layer,
446
+ indices_q,
447
+ (cu_seqlens_q, cu_seqlens_k),
448
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
449
+ )
450
+
451
+
452
+ CORE_ATTENTION_CLASSES = {
453
+ "eager": CoreAttention,
454
+ "sdpa": SdpaAttention,
455
+ "flash_attention_2": FlashAttention2
456
+ }
457
+
458
+
459
+ class SelfAttention(torch.nn.Module):
460
+ """Parallel self-attention layer abstract class.
461
+
462
+ Self-attention layer takes input with size [s, b, h]
463
+ and returns output of the same size.
464
+ """
465
+
466
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
467
+ super(SelfAttention, self).__init__()
468
+ self.layer_number = max(1, layer_number)
469
+
470
+ self.projection_size = config.kv_channels * config.num_attention_heads
471
+
472
+ # Per attention head and per partition values.
473
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
474
+ self.num_attention_heads_per_partition = config.num_attention_heads
475
+
476
+ self.multi_query_attention = config.multi_query_attention
477
+ self.qkv_hidden_size = 3 * self.projection_size
478
+ self.original_rope = config.original_rope
479
+ if self.multi_query_attention:
480
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
481
+ self.qkv_hidden_size = (
482
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
483
+ )
484
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
485
+ bias=config.add_bias_linear or config.add_qkv_bias,
486
+ device=device, **_config_to_kwargs(config)
487
+ )
488
+
489
+ self.core_attention = CoreAttention(config, self.layer_number)
490
+
491
+ # Output.
492
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
493
+ device=device, **_config_to_kwargs(config)
494
+ )
495
+
496
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
497
+ if self.multi_query_attention:
498
+ num_attention_heads = self.num_multi_query_groups_per_partition
499
+ else:
500
+ num_attention_heads = self.num_attention_heads_per_partition
501
+ return torch.empty(
502
+ inference_max_sequence_len,
503
+ batch_size,
504
+ num_attention_heads,
505
+ self.hidden_size_per_attention_head,
506
+ dtype=dtype,
507
+ device=device,
508
+ )
509
+
510
+ def forward(
511
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
512
+ ):
513
+ # hidden_states: [b, sq, h]
514
+
515
+ # =================================================
516
+ # Pre-allocate memory for key-values for inference.
517
+ # =================================================
518
+ # =====================
519
+ # Query, Key, and Value
520
+ # =====================
521
+
522
+ # Attention heads [b, sq, h] --> [b, sq, (np * 3 * hn)]
523
+ mixed_x_layer = self.query_key_value(hidden_states)
524
+
525
+ if self.multi_query_attention:
526
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
527
+ [
528
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
529
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
530
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
531
+ ],
532
+ dim=-1,
533
+ )
534
+ query_layer = query_layer.view(
535
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
536
+ )
537
+ key_layer = key_layer.view(
538
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
539
+ )
540
+ value_layer = value_layer.view(
541
+ value_layer.size()[:-1]
542
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
543
+ )
544
+ else:
545
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
546
+ (self.num_attention_heads_per_partition,
547
+ 3 * self.hidden_size_per_attention_head)
548
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
549
+
550
+ # [b, sq, np, 3 * hn] --> 3 [b, sq, np, hn]
551
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
552
+
553
+ # [b, sq, np, hn] -> [b, np, sq, hn]
554
+ query_layer, key_layer, value_layer = [k.transpose(1, 2) for k in [query_layer, key_layer, value_layer]]
555
+
556
+ # apply relative positional encoding (rotary embedding)
557
+ if rotary_pos_emb is not None:
558
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
559
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
560
+
561
+ # adjust key and value for inference
562
+ if kv_cache is not None:
563
+ cache_k, cache_v = kv_cache
564
+ key_layer = torch.cat((cache_k, key_layer), dim=2)
565
+ value_layer = torch.cat((cache_v, value_layer), dim=2)
566
+ if use_cache:
567
+ kv_cache = (key_layer, value_layer)
568
+ else:
569
+ kv_cache = None
570
+
571
+ if self.multi_query_attention:
572
+ key_layer = key_layer.unsqueeze(2)
573
+ key_layer = key_layer.expand(
574
+ -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
575
+ )
576
+ key_layer = key_layer.contiguous().view(
577
+ key_layer.size()[:1] + (self.num_attention_heads_per_partition,) + key_layer.size()[3:]
578
+ )
579
+ value_layer = value_layer.unsqueeze(2)
580
+ value_layer = value_layer.expand(
581
+ -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
582
+ )
583
+ value_layer = value_layer.contiguous().view(
584
+ value_layer.size()[:1] + (self.num_attention_heads_per_partition,) + value_layer.size()[3:]
585
+ )
586
+
587
+ # ==================================
588
+ # core attention computation
589
+ # ==================================
590
+
591
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
592
+
593
+ # =================
594
+ # Output. [sq, b, h]
595
+ # =================
596
+
597
+ output = self.dense(context_layer)
598
+
599
+ return output, kv_cache
600
+
601
+
602
+ def _config_to_kwargs(args):
603
+ common_kwargs = {
604
+ "dtype": args.torch_dtype,
605
+ }
606
+ return common_kwargs
607
+
608
+
609
+ class MLP(torch.nn.Module):
610
+ """MLP.
611
+
612
+ MLP will take the input with h hidden state, project it to 4*h
613
+ hidden dimension, perform nonlinear transformation, and project the
614
+ state back into h hidden dimension.
615
+ """
616
+
617
+ def __init__(self, config: ChatGLMConfig, device=None):
618
+ super(MLP, self).__init__()
619
+
620
+ self.add_bias = config.add_bias_linear
621
+
622
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
623
+ self.dense_h_to_4h = nn.Linear(
624
+ config.hidden_size,
625
+ config.ffn_hidden_size * 2,
626
+ bias=self.add_bias,
627
+ device=device,
628
+ **_config_to_kwargs(config)
629
+ )
630
+
631
+ def swiglu(x):
632
+ x = torch.chunk(x, 2, dim=-1)
633
+ return F.silu(x[0]) * x[1]
634
+
635
+ self.activation_func = swiglu
636
+
637
+ # Project back to h.
638
+ self.dense_4h_to_h = nn.Linear(
639
+ config.ffn_hidden_size,
640
+ config.hidden_size,
641
+ bias=self.add_bias,
642
+ device=device,
643
+ **_config_to_kwargs(config)
644
+ )
645
+
646
+ def forward(self, hidden_states):
647
+ # [s, b, 4hp]
648
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
649
+ intermediate_parallel = self.activation_func(intermediate_parallel)
650
+ # [s, b, h]
651
+ output = self.dense_4h_to_h(intermediate_parallel)
652
+ return output
653
+
654
+
655
+ class GLMBlock(torch.nn.Module):
656
+ """A single transformer layer.
657
+
658
+ Transformer layer takes input with size [s, b, h] and returns an
659
+ output of the same size.
660
+ """
661
+
662
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
663
+ super(GLMBlock, self).__init__()
664
+ self.layer_number = layer_number
665
+
666
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
667
+
668
+ self.fp32_residual_connection = config.fp32_residual_connection
669
+
670
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
671
+ # Layernorm on the input data.
672
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
673
+ dtype=config.torch_dtype)
674
+
675
+ # Self attention.
676
+ self.self_attention = SelfAttention(config, layer_number, device=device)
677
+ self.hidden_dropout = config.hidden_dropout
678
+
679
+ # Layernorm on the attention output
680
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
681
+ dtype=config.torch_dtype)
682
+
683
+ # MLP
684
+ self.mlp = MLP(config, device=device)
685
+
686
+ def forward(
687
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
688
+ ):
689
+ # hidden_states: [s, b, h]
690
+
691
+ # Layer norm at the beginning of the transformer layer.
692
+ layernorm_output = self.input_layernorm(hidden_states)
693
+ # Self attention.
694
+ attention_output, kv_cache = self.self_attention(
695
+ layernorm_output,
696
+ attention_mask,
697
+ rotary_pos_emb,
698
+ kv_cache=kv_cache,
699
+ use_cache=use_cache
700
+ )
701
+
702
+ # Residual connection.
703
+ if self.apply_residual_connection_post_layernorm:
704
+ residual = layernorm_output
705
+ else:
706
+ residual = hidden_states
707
+
708
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
709
+ layernorm_input = residual + layernorm_input
710
+
711
+ # Layer norm post the self attention.
712
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
713
+
714
+ # MLP.
715
+ mlp_output = self.mlp(layernorm_output)
716
+
717
+ # Second residual connection.
718
+ if self.apply_residual_connection_post_layernorm:
719
+ residual = layernorm_output
720
+ else:
721
+ residual = layernorm_input
722
+
723
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
724
+ output = residual + output
725
+
726
+ return output, kv_cache
727
+
728
+
729
+ class GLMTransformer(torch.nn.Module):
730
+ """Transformer class."""
731
+
732
+ def __init__(self, config: ChatGLMConfig, device=None):
733
+ super(GLMTransformer, self).__init__()
734
+
735
+ self.fp32_residual_connection = config.fp32_residual_connection
736
+ self.post_layer_norm = config.post_layer_norm
737
+
738
+ # Number of layers.
739
+ self.num_layers = config.num_layers
740
+
741
+ # Transformer layers.
742
+ def build_layer(layer_number):
743
+ return GLMBlock(config, layer_number, device=device)
744
+
745
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
746
+
747
+ if self.post_layer_norm:
748
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
749
+ # Final layer norm before output.
750
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
751
+ dtype=config.torch_dtype)
752
+
753
+ self.gradient_checkpointing = False
754
+
755
+ def _get_layer(self, layer_number):
756
+ return self.layers[layer_number]
757
+
758
+ def forward(
759
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
760
+ use_cache: Optional[bool] = True,
761
+ output_hidden_states: Optional[bool] = False,
762
+ ):
763
+ if not kv_caches:
764
+ kv_caches = [None for _ in range(self.num_layers)]
765
+ presents = () if use_cache else None
766
+ if self.gradient_checkpointing and self.training:
767
+ if use_cache:
768
+ logger.warning_once(
769
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
770
+ )
771
+ use_cache = False
772
+
773
+ all_self_attentions = None
774
+ all_hidden_states = () if output_hidden_states else None
775
+ for index in range(self.num_layers):
776
+ if output_hidden_states:
777
+ all_hidden_states = all_hidden_states + (hidden_states,)
778
+
779
+ layer = self._get_layer(index)
780
+ if self.gradient_checkpointing and self.training:
781
+ layer_ret = torch.utils.checkpoint.checkpoint(
782
+ layer,
783
+ hidden_states,
784
+ attention_mask,
785
+ rotary_pos_emb,
786
+ kv_caches[index],
787
+ use_cache,
788
+ use_reentrant=False
789
+ )
790
+ else:
791
+ layer_ret = layer(
792
+ hidden_states,
793
+ attention_mask,
794
+ rotary_pos_emb,
795
+ kv_cache=kv_caches[index],
796
+ use_cache=use_cache
797
+ )
798
+ hidden_states, kv_cache = layer_ret
799
+ if use_cache:
800
+ presents = presents + (kv_cache,)
801
+
802
+ if output_hidden_states:
803
+ all_hidden_states = all_hidden_states + (hidden_states,)
804
+
805
+ # Final layer norm.
806
+ if self.post_layer_norm:
807
+ hidden_states = self.final_layernorm(hidden_states)
808
+
809
+ return hidden_states, presents, all_hidden_states, all_self_attentions
810
+
811
+
812
+ class ChatGLMPreTrainedModel(PreTrainedModel):
813
+ """
814
+ An abstract class to handle weights initialization and
815
+ a simple interface for downloading and loading pretrained models.
816
+ """
817
+
818
+ is_parallelizable = False
819
+ supports_gradient_checkpointing = True
820
+ config_class = ChatGLMConfig
821
+ base_model_prefix = "transformer"
822
+ _no_split_modules = ["GLMBlock"]
823
+ _supports_flash_attn_2 = True
824
+ _supports_sdpa = True
825
+
826
+ def _init_weights(self, module: nn.Module):
827
+ """Initialize the weights."""
828
+ return
829
+
830
+ def get_masks(self, input_embeds, past_key_values, padding_mask=None):
831
+ if self.config._attn_implementation == "flash_attention_2":
832
+ if padding_mask is not None and not padding_mask.all():
833
+ return padding_mask
834
+ return None
835
+ batch_size, seq_length, embed_size = input_embeds.shape
836
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_embeds.device)
837
+ full_attention_mask.tril_()
838
+ past_length = 0
839
+ if past_key_values:
840
+ past_length = past_key_values[0][0].shape[2]
841
+ if past_length:
842
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
843
+ device=input_embeds.device), full_attention_mask), dim=-1)
844
+ if padding_mask is not None:
845
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
846
+ if not past_length and padding_mask is not None:
847
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
848
+ full_attention_mask = (full_attention_mask < 0.5).bool()
849
+ full_attention_mask.unsqueeze_(1)
850
+ return full_attention_mask
851
+
852
+ def get_position_ids(self, input_ids, device):
853
+ batch_size, seq_length = input_ids.shape
854
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
855
+ return position_ids
856
+
857
+ def get_multimodal_position_ids(self, input_ids, device):
858
+ batch_size, seq_length = input_ids.shape
859
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
860
+
861
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
862
+ if not self.supports_gradient_checkpointing:
863
+ raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
864
+
865
+
866
+ class Embedding(torch.nn.Module):
867
+ """Language model embeddings."""
868
+
869
+ def __init__(self, config: ChatGLMConfig, device=None):
870
+ super(Embedding, self).__init__()
871
+
872
+ self.hidden_size = config.hidden_size
873
+ # Word embeddings (parallel).
874
+ self.word_embeddings = nn.Embedding(
875
+ config.padded_vocab_size,
876
+ self.hidden_size,
877
+ dtype=config.torch_dtype,
878
+ device=device
879
+ )
880
+ self.fp32_residual_connection = config.fp32_residual_connection
881
+
882
+ def forward(self, input_ids):
883
+ # Embeddings.
884
+ words_embeddings = self.word_embeddings(input_ids)
885
+ embeddings = words_embeddings
886
+ # If the input flag for fp32 residual connection is set, convert for float.
887
+ if self.fp32_residual_connection:
888
+ embeddings = embeddings.float()
889
+ return embeddings
890
+
891
+
892
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
893
+ if images_list is None or len(images_list) == 0:
894
+ return True
895
+ for image_list in images_list:
896
+ if image_list is not None:
897
+ return False
898
+ return True
899
+
900
+
901
+ class ChatGLMModel(ChatGLMPreTrainedModel):
902
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
903
+ super().__init__(config)
904
+ if empty_init:
905
+ init_method = skip_init
906
+ else:
907
+ init_method = default_init
908
+ init_kwargs = {}
909
+ if device is not None:
910
+ init_kwargs["device"] = device
911
+ self.embedding = init_method(Embedding, config, **init_kwargs)
912
+ self.num_layers = config.num_layers
913
+ self.multi_query_group_num = config.multi_query_group_num
914
+ self.kv_channels = config.kv_channels
915
+
916
+ # Rotary positional embeddings
917
+ self.seq_length = config.seq_length
918
+ rotary_dim = (
919
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
920
+ )
921
+
922
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio,
923
+ original_impl=config.original_rope,
924
+ device=device, dtype=config.torch_dtype)
925
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
926
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
927
+ dtype=config.torch_dtype, **init_kwargs)
928
+ self.pre_seq_len = config.pre_seq_len
929
+ self.prefix_projection = config.prefix_projection
930
+ if self.pre_seq_len is not None:
931
+ for param in self.parameters():
932
+ param.requires_grad = False
933
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
934
+ self.prefix_encoder = PrefixEncoder(config)
935
+ self.dropout = torch.nn.Dropout(0.1)
936
+
937
+ self.vision = EVA2CLIPModel(config)
938
+
939
+ def get_input_embeddings(self):
940
+ return self.embedding.word_embeddings
941
+
942
+ def set_input_embeddings(self, value):
943
+ self.embedding.word_embeddings = value
944
+
945
+ def get_prompt(self, batch_size, device, dtype=torch.half):
946
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
947
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
948
+ past_key_values = past_key_values.view(
949
+ batch_size,
950
+ self.pre_seq_len,
951
+ self.pre_seq_len,
952
+ self.num_layers * 2,
953
+ self.multi_query_group_num,
954
+ self.kv_channels
955
+ )
956
+ # seq_len, b, nh, hidden_size
957
+ past_key_values = self.dropout(past_key_values)
958
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
959
+ return past_key_values
960
+
961
+ def forward(
962
+ self,
963
+ input_ids: torch.LongTensor = None,
964
+ images: torch.Tensor = None,
965
+ position_ids: Optional[torch.Tensor] = None,
966
+ attention_mask: Optional[torch.BoolTensor] = None,
967
+ full_attention_mask: Optional[torch.BoolTensor] = None,
968
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
969
+ inputs_embeds: Optional[torch.Tensor] = None,
970
+ use_cache: Optional[bool] = None,
971
+ output_hidden_states: Optional[bool] = None,
972
+ return_dict: Optional[bool] = None,
973
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
974
+ """take care of image_encode, position_ids and (attention_mask = None is fine)"""
975
+
976
+ # generate mode with past_key_values. the image features are already mapped
977
+ if past_key_values is None:
978
+ # not allow for inputs_embeds, because we want to process image feature
979
+ assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
980
+ if not is_empty(images): # multi-modality
981
+
982
+ image_size: int = self.config.vision_config['image_size']
983
+ patch_size: int = self.config.vision_config['patch_size']
984
+ num_patches = (image_size // patch_size // 2) ** 2
985
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
986
+ inputs_embeds = self.embedding(input_ids)
987
+
988
+ images = images.to(dtype=inputs_embeds.dtype)
989
+ images_features = self.vision(images)
990
+
991
+ if position_ids is None:
992
+ position_ids = self.get_position_ids(input_ids, device=inputs_embeds.device)
993
+ new_input_embeds, new_position_ids = [], []
994
+
995
+ for i in range(len(input_ids)):
996
+ input_id = input_ids[i].tolist()
997
+ boi_token_pos, eoi_token_pos = input_id.index(self.config.boi_token_id), input_id.index(
998
+ self.config.eoi_token_id)
999
+ assert eoi_token_pos - boi_token_pos == 2
1000
+ new_input_embeds.append(torch.cat(
1001
+ (inputs_embeds[i, :boi_token_pos], images_features[i].to(inputs_embeds.device),
1002
+ inputs_embeds[i, eoi_token_pos + 1:])))
1003
+ new_position_ids.append(torch.cat(
1004
+ (position_ids[i, :boi_token_pos + 1], position_ids[i, boi_token_pos + 1].repeat(num_patches),
1005
+ position_ids[i, eoi_token_pos:])
1006
+ ))
1007
+ inputs_embeds = torch.stack(new_input_embeds, dim=0)
1008
+ position_ids = torch.stack(new_position_ids, dim=0)
1009
+
1010
+ output_hidden_states = (
1011
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1012
+ )
1013
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1014
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1015
+
1016
+ batch_size, seq_length = input_ids.shape
1017
+
1018
+ if inputs_embeds is None:
1019
+ inputs_embeds = self.embedding(input_ids)
1020
+
1021
+ if self.pre_seq_len is not None:
1022
+ if past_key_values is None:
1023
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
1024
+ dtype=inputs_embeds.dtype)
1025
+ if attention_mask is not None:
1026
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
1027
+ attention_mask], dim=-1)
1028
+
1029
+ if full_attention_mask is None:
1030
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
1031
+ full_attention_mask = self.get_masks(inputs_embeds, past_key_values, padding_mask=attention_mask)
1032
+
1033
+ # Rotary positional embeddings
1034
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
1035
+ if position_ids is not None:
1036
+ rotary_pos_emb = rotary_pos_emb[position_ids]
1037
+ else:
1038
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
1039
+
1040
+ # Run encoder.
1041
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
1042
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
1043
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
1044
+ )
1045
+
1046
+ if not return_dict:
1047
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1048
+
1049
+ return BaseModelOutputWithPast(
1050
+ last_hidden_state=hidden_states,
1051
+ past_key_values=presents,
1052
+ hidden_states=all_hidden_states,
1053
+ attentions=all_self_attentions,
1054
+ )
1055
+
1056
+
1057
+ def _history_to_prompt(history, query):
1058
+ prompt = ''
1059
+ flag = False
1060
+ for i, (old_query, response) in enumerate(history):
1061
+ prompt += ('<|user|>' if flag else '') + old_query + "<|assistant|>" + response + "<|endoftext|>"
1062
+ flag = True
1063
+ prompt += '{}{}<|assistant|>'.format('<|user|>' if flag else '', query)
1064
+ return prompt
1065
+
1066
+
1067
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1068
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1069
+ super().__init__(config)
1070
+
1071
+ self.max_sequence_length = config.max_length
1072
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1073
+ self.config = config
1074
+
1075
+ def _update_model_kwargs_for_generation(
1076
+ self,
1077
+ outputs: ModelOutput,
1078
+ model_kwargs: Dict[str, Any],
1079
+ is_encoder_decoder: bool = False,
1080
+ standardize_cache_format: bool = False,
1081
+ ) -> Dict[str, Any]:
1082
+ # update past_key_values
1083
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1084
+ outputs, standardize_cache_format=standardize_cache_format
1085
+ )
1086
+
1087
+ # update attention mask
1088
+ if "attention_mask" in model_kwargs:
1089
+ attention_mask = model_kwargs["attention_mask"]
1090
+ model_kwargs["attention_mask"] = torch.cat(
1091
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1092
+ )
1093
+
1094
+ # update position ids
1095
+ if "position_ids" in model_kwargs:
1096
+ position_ids = model_kwargs["position_ids"]
1097
+ new_position_id = position_ids[..., -1:].clone()
1098
+ new_position_id += 1
1099
+ model_kwargs["position_ids"] = torch.cat(
1100
+ [position_ids, new_position_id], dim=-1
1101
+ )
1102
+
1103
+ model_kwargs["is_first_forward"] = False
1104
+ return model_kwargs
1105
+
1106
+ def prepare_inputs_for_generation(
1107
+ self,
1108
+ input_ids: torch.LongTensor,
1109
+ images: Optional[torch.Tensor] = None,
1110
+ past_key_values: Optional[torch.Tensor] = None,
1111
+ attention_mask: Optional[torch.Tensor] = None,
1112
+ position_ids: Optional[torch.Tensor] = None,
1113
+ use_cache: Optional[bool] = None,
1114
+ is_first_forward: bool = True,
1115
+ **kwargs
1116
+ ) -> dict:
1117
+ # only last token for input_ids if past is not None
1118
+ if position_ids is None:
1119
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
1120
+ if attention_mask is not None:
1121
+ image_size: int = self.config.vision_config['image_size']
1122
+ patch_size: int = self.config.vision_config['patch_size']
1123
+ num_patches = (image_size // patch_size // 2) ** 2
1124
+ new_attention_masks = []
1125
+
1126
+ # if not image, use this default id
1127
+ eoi_token_pos = 6
1128
+ boi_token_pos = 4
1129
+
1130
+ for i in range(len(input_ids)):
1131
+ input_id = input_ids[i].tolist()
1132
+ if not is_empty(images):
1133
+ boi_token_pos, eoi_token_pos = input_id.index(self.config.boi_token_id), input_id.index(
1134
+ self.config.eoi_token_id)
1135
+ assert eoi_token_pos - boi_token_pos == 2
1136
+ new_attention_masks.append(torch.cat(
1137
+ (attention_mask[i, :boi_token_pos + 1], attention_mask.new_ones(num_patches),
1138
+ attention_mask[i, eoi_token_pos:])
1139
+ ))
1140
+ attention_mask = torch.stack(new_attention_masks, dim=0)
1141
+ if not is_first_forward:
1142
+ if past_key_values is not None:
1143
+ position_ids = position_ids[..., -1:]
1144
+ input_ids = input_ids[:, -1:]
1145
+ return {
1146
+ "input_ids": input_ids,
1147
+ "images": images,
1148
+ "past_key_values": past_key_values,
1149
+ "position_ids": position_ids,
1150
+ "attention_mask": attention_mask,
1151
+ "return_last_logit": True,
1152
+ "use_cache": use_cache
1153
+ }
1154
+
1155
+ def forward(
1156
+ self,
1157
+ input_ids: Optional[torch.Tensor] = None,
1158
+ images: List[List[torch.Tensor]] = None,
1159
+ position_ids: Optional[torch.Tensor] = None,
1160
+ attention_mask: Optional[torch.Tensor] = None,
1161
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1162
+ inputs_embeds: Optional[torch.Tensor] = None,
1163
+ labels: Optional[torch.Tensor] = None,
1164
+ use_cache: Optional[bool] = None,
1165
+ output_attentions: Optional[bool] = None,
1166
+ output_hidden_states: Optional[bool] = None,
1167
+ return_dict: Optional[bool] = None,
1168
+ return_last_logit: Optional[bool] = False,
1169
+ ):
1170
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1171
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1172
+
1173
+ transformer_outputs = self.transformer(
1174
+ input_ids=input_ids,
1175
+ images=images,
1176
+ position_ids=position_ids,
1177
+ attention_mask=attention_mask,
1178
+ past_key_values=past_key_values,
1179
+ inputs_embeds=inputs_embeds,
1180
+ use_cache=use_cache,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+
1185
+ hidden_states = transformer_outputs[0]
1186
+ if return_last_logit:
1187
+ hidden_states = hidden_states[:, -1:]
1188
+ lm_logits = self.transformer.output_layer(hidden_states)
1189
+
1190
+ loss = None
1191
+ if labels is not None:
1192
+ lm_logits = lm_logits.to(torch.float32)
1193
+
1194
+ # Shift so that tokens < n predict n
1195
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1196
+ shift_labels = labels[..., 1:].contiguous()
1197
+ # Flatten the tokens
1198
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1199
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1200
+
1201
+ lm_logits = lm_logits.to(hidden_states.dtype)
1202
+ loss = loss.to(hidden_states.dtype)
1203
+
1204
+ if not return_dict:
1205
+ output = (lm_logits,) + transformer_outputs[1:]
1206
+ return ((loss,) + output) if loss is not None else output
1207
+
1208
+ return CausalLMOutputWithPast(
1209
+ loss=loss,
1210
+ logits=lm_logits,
1211
+ past_key_values=transformer_outputs.past_key_values,
1212
+ hidden_states=transformer_outputs.hidden_states,
1213
+ attentions=transformer_outputs.attentions,
1214
+ )
1215
+
1216
+ @staticmethod
1217
+ def _reorder_cache(
1218
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1219
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1220
+ """
1221
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1222
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1223
+ beam_idx at every generation step.
1224
+
1225
+ Output shares the same memory storage as `past`.
1226
+ """
1227
+ return tuple(
1228
+ (
1229
+ layer_past[0].index_select(0, beam_idx.to(layer_past[0].device)),
1230
+ layer_past[1].index_select(0, beam_idx.to(layer_past[1].device)),
1231
+ )
1232
+ for layer_past in past
1233
+ )
1234
+
1235
+ def process_response(self, output, history):
1236
+ content = ""
1237
+ history = deepcopy(history)
1238
+ for response in output.split("<|assistant|>"):
1239
+ if "\n" in response:
1240
+ metadata, content = response.split("\n", maxsplit=1)
1241
+ else:
1242
+ metadata, content = "", response
1243
+ if not metadata.strip():
1244
+ content = content.strip()
1245
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1246
+ content = content.replace("[[训练时间]]", "2023年")
1247
+ else:
1248
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1249
+ if history[0]["role"] == "system" and "tools" in history[0]:
1250
+ parameters = json.loads(content)
1251
+ content = {"name": metadata.strip(), "parameters": parameters}
1252
+ else:
1253
+ content = {"name": metadata.strip(), "content": content}
1254
+ return content, history
1255
+
1256
+ @torch.inference_mode()
1257
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
1258
+ max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1259
+ **kwargs):
1260
+ if history is None:
1261
+ history = []
1262
+ if logits_processor is None:
1263
+ logits_processor = LogitsProcessorList()
1264
+ logits_processor.append(InvalidScoreLogitsProcessor())
1265
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1266
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1267
+ message = {"role": role, "content": query}
1268
+ if image is not None:
1269
+ message["image"] = image
1270
+ history.append(message)
1271
+ inputs = tokenizer.apply_chat_template(history, add_generation_prompt=True, tokenize=True,
1272
+ return_tensors="pt", return_dict=True)
1273
+ inputs = inputs.to(self.device)
1274
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
1275
+ tokenizer.convert_tokens_to_ids("<|observation|>")]
1276
+ outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
1277
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1278
+ response = tokenizer.decode(outputs)
1279
+ response, history = self.process_response(response, history)
1280
+ return response, history
1281
+
1282
+ @torch.inference_mode()
1283
+ def stream_chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
1284
+ past_key_values=None, max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
1285
+ logits_processor=None, return_past_key_values=False, **kwargs):
1286
+ if history is None:
1287
+ history = []
1288
+ if logits_processor is None:
1289
+ logits_processor = LogitsProcessorList()
1290
+ logits_processor.append(InvalidScoreLogitsProcessor())
1291
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
1292
+ tokenizer.convert_tokens_to_ids("<|observation|>")]
1293
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1294
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1295
+ message = {"role": role, "content": "query"}
1296
+ if image is not None:
1297
+ message["image"] = image
1298
+ if past_key_values is None:
1299
+ inputs = tokenizer.apply_chat_template(history + [message],
1300
+ add_generation_prompt=True, tokenize=True, return_tensors="pt",
1301
+ return_dict=True)
1302
+ else:
1303
+ inputs = tokenizer.apply_chat_template([message], add_special_tokens=False,
1304
+ add_generation_prompt=True, tokenize=True, return_tensors="pt",
1305
+ return_dict=True)
1306
+ inputs = inputs.to(self.device)
1307
+ if past_key_values is not None:
1308
+ past_length = past_key_values[0][0].shape[2]
1309
+ if self.transformer.pre_seq_len is not None:
1310
+ past_length -= self.transformer.pre_seq_len
1311
+ inputs.position_ids += past_length
1312
+ attention_mask = inputs.attention_mask
1313
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1314
+ inputs['attention_mask'] = attention_mask
1315
+ history.append({"role": role, "content": query})
1316
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1317
+ eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
1318
+ **gen_kwargs):
1319
+ if return_past_key_values:
1320
+ outputs, past_key_values = outputs
1321
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1322
+ response = tokenizer.decode(outputs)
1323
+ if response and response[-1] != "�":
1324
+ response, new_history = self.process_response(response, history)
1325
+ if return_past_key_values:
1326
+ yield response, new_history, past_key_values
1327
+ else:
1328
+ yield response, new_history
1329
+
1330
+ @torch.inference_mode()
1331
+ def stream_generate(
1332
+ self,
1333
+ input_ids,
1334
+ generation_config: Optional[GenerationConfig] = None,
1335
+ logits_processor: Optional[LogitsProcessorList] = None,
1336
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1337
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1338
+ return_past_key_values=False,
1339
+ **kwargs,
1340
+ ):
1341
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1342
+
1343
+ if generation_config is None:
1344
+ generation_config = self.generation_config
1345
+ generation_config = copy.deepcopy(generation_config)
1346
+ model_kwargs = generation_config.update(**kwargs)
1347
+ model_kwargs["use_cache"] = generation_config.use_cache
1348
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1349
+
1350
+ if isinstance(eos_token_id, int):
1351
+ eos_token_id = [eos_token_id]
1352
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1353
+
1354
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1355
+ if has_default_max_length and generation_config.max_new_tokens is None:
1356
+ warnings.warn(
1357
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1358
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1359
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1360
+ UserWarning,
1361
+ )
1362
+ elif generation_config.max_new_tokens is not None:
1363
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1364
+ if not has_default_max_length:
1365
+ logger.warn(
1366
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1367
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1368
+ "Please refer to the documentation for more information. "
1369
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1370
+ UserWarning,
1371
+ )
1372
+
1373
+ if input_ids_seq_length >= generation_config.max_length:
1374
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1375
+ logger.warning(
1376
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1377
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1378
+ " increasing `max_new_tokens`."
1379
+ )
1380
+
1381
+ # 2. Set generation parameters if not already defined
1382
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1383
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1384
+
1385
+ logits_processor = self._get_logits_processor(
1386
+ generation_config=generation_config,
1387
+ input_ids_seq_length=input_ids_seq_length,
1388
+ encoder_input_ids=input_ids,
1389
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1390
+ logits_processor=logits_processor,
1391
+ )
1392
+
1393
+ stopping_criteria = self._get_stopping_criteria(
1394
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1395
+ )
1396
+ logits_warper = self._get_logits_warper(generation_config)
1397
+
1398
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1399
+ scores = None
1400
+ while True:
1401
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1402
+ # forward pass to get next token
1403
+ outputs = self(
1404
+ **model_inputs,
1405
+ return_dict=True,
1406
+ output_attentions=False,
1407
+ output_hidden_states=False,
1408
+ )
1409
+
1410
+ next_token_logits = outputs.logits[:, -1, :]
1411
+
1412
+ # pre-process distribution
1413
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1414
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1415
+
1416
+ # sample
1417
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1418
+ if generation_config.do_sample:
1419
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1420
+ else:
1421
+ next_tokens = torch.argmax(probs, dim=-1)
1422
+ # update generated ids, model inputs, and length for next step
1423
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1424
+ model_kwargs = self._update_model_kwargs_for_generation(
1425
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1426
+ )
1427
+ unfinished_sequences = unfinished_sequences.mul(
1428
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1429
+ )
1430
+ if return_past_key_values:
1431
+ yield input_ids, outputs.past_key_values
1432
+ else:
1433
+ yield input_ids
1434
+ # stop when each sentence is finished, or if we exceed the maximum length
1435
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1436
+ break
1437
+
1438
+
1439
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1440
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1441
+ super().__init__(config)
1442
+
1443
+ self.num_labels = config.num_labels
1444
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1445
+
1446
+ self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
1447
+ if config.classifier_dropout is not None:
1448
+ self.dropout = nn.Dropout(config.classifier_dropout)
1449
+ else:
1450
+ self.dropout = None
1451
+ self.config = config
1452
+
1453
+ def forward(
1454
+ self,
1455
+ input_ids: Optional[torch.LongTensor] = None,
1456
+ position_ids: Optional[torch.LongTensor] = None,
1457
+ attention_mask: Optional[torch.Tensor] = None,
1458
+ full_attention_mask: Optional[torch.Tensor] = None,
1459
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1460
+ inputs_embeds: Optional[torch.LongTensor] = None,
1461
+ labels: Optional[torch.LongTensor] = None,
1462
+ use_cache: Optional[bool] = None,
1463
+ output_hidden_states: Optional[bool] = None,
1464
+ return_dict: Optional[bool] = None,
1465
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1466
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1467
+
1468
+ transformer_outputs = self.transformer(
1469
+ input_ids=input_ids,
1470
+ position_ids=position_ids,
1471
+ attention_mask=attention_mask,
1472
+ full_attention_mask=full_attention_mask,
1473
+ past_key_values=past_key_values,
1474
+ inputs_embeds=inputs_embeds,
1475
+ use_cache=use_cache,
1476
+ output_hidden_states=output_hidden_states,
1477
+ return_dict=return_dict,
1478
+ )
1479
+
1480
+ hidden_states = transformer_outputs[0]
1481
+ pooled_hidden_states = hidden_states[-1]
1482
+ if self.dropout is not None:
1483
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1484
+ logits = self.classifier_head(pooled_hidden_states)
1485
+
1486
+ loss = None
1487
+ if labels is not None:
1488
+ if self.config.problem_type is None:
1489
+ if self.num_labels == 1:
1490
+ self.config.problem_type = "regression"
1491
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1492
+ self.config.problem_type = "single_label_classification"
1493
+ else:
1494
+ self.config.problem_type = "multi_label_classification"
1495
+
1496
+ if self.config.problem_type == "regression":
1497
+ loss_fct = MSELoss()
1498
+ if self.num_labels == 1:
1499
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1500
+ else:
1501
+ loss = loss_fct(logits.float(), labels)
1502
+ elif self.config.problem_type == "single_label_classification":
1503
+ loss_fct = CrossEntropyLoss()
1504
+ loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
1505
+ elif self.config.problem_type == "multi_label_classification":
1506
+ loss_fct = BCEWithLogitsLoss()
1507
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1508
+
1509
+ if not return_dict:
1510
+ output = (logits,) + transformer_outputs[1:]
1511
+ return ((loss,) + output) if loss is not None else output
1512
+
1513
+ return SequenceClassifierOutputWithPast(
1514
+ loss=loss,
1515
+ logits=logits,
1516
+ past_key_values=transformer_outputs.past_key_values,
1517
+ hidden_states=transformer_outputs.hidden_states,
1518
+ attentions=transformer_outputs.attentions,
1519
+ )
coin_model_funtuned_tokenization_chatglm.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging, 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 = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]
135
+ return prefix_tokens
136
+
137
+ def build_single_message(self, role, metadata, message, tokenize=True, message_prefix=None):
138
+ assert role in ["system", "user", "assistant", "observation"], role
139
+ if tokenize:
140
+ role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",
141
+ disallowed_special=())
142
+ message_tokens = self.tokenizer.encode(message, disallowed_special=())
143
+ if message_prefix is not None:
144
+ message_tokens = message_prefix + message_tokens
145
+ tokens = role_tokens + message_tokens
146
+ return tokens
147
+ else:
148
+ return str(f"<|{role}|>{metadata}\n{message}")
149
+
150
+ def apply_chat_template(
151
+ self,
152
+ conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]], "Conversation"],
153
+ add_generation_prompt: bool = False,
154
+ tokenize: bool = True,
155
+ padding: bool = False,
156
+ truncation: bool = False,
157
+ max_length: Optional[int] = None,
158
+ return_tensors: Optional[Union[str, TensorType]] = None,
159
+ return_dict: bool = False,
160
+ tokenizer_kwargs: Optional[Dict[str, Any]] = None,
161
+ add_special_tokens: bool = True,
162
+ **kwargs,
163
+ ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
164
+
165
+ if return_dict and not tokenize:
166
+ raise ValueError(
167
+ "`return_dict=True` is incompatible with `tokenize=False`, because there is no dict "
168
+ "of tokenizer outputs to return."
169
+ )
170
+
171
+ def handle_single_conversation(conversation):
172
+ input_ids = self.get_prefix_tokens() if add_special_tokens else []
173
+ input_message = "[gMASK]<sop>" if add_special_tokens else ""
174
+ input_image = None
175
+ transform = transforms.Compose(
176
+ [
177
+ transforms.Resize(
178
+ (self.image_size, self.image_size), interpolation=transforms.InterpolationMode.BICUBIC
179
+ ),
180
+ transforms.ToTensor(),
181
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
182
+ ]
183
+ )
184
+ for item in conversation:
185
+ if item.get("tools"):
186
+ tools = item["tools"]
187
+ content = "你是一个名为 GLM-4 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,你的任务是针对用户的问题和要求提供适当的答复和支持。"
188
+ for tool in tools:
189
+ if tool["type"] == "function":
190
+ function = tool["function"]
191
+ content += f"\n\n## {function['name']}\n\n{json.dumps(function, ensure_ascii=False, indent=4)}"
192
+ content += "\n在调用上述函数时,请使用 Json 格式表示调用的参数。"
193
+ elif tool["type"] == "python":
194
+ content += "\n\n## python\n\n当你向 `python` 发送包含 Python 代码的消息时,该代码将会在一个有状态的 Jupyter notebook 环境中执行。\n`python` 返回代码执行的输出,或在执行 60 秒后返回超时。\n`/mnt/data` 将会持久化存储你的文件。在此会话中,`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用,这些在线内容的访问将不会成功。"
195
+ elif tool["type"] == "simple_browser":
196
+ content += "\n\n## simple_browser\n\n你可以使用 `simple_browser` 工具。该工具支持以下函数:\n`search(query: str, recency_days: int)`:使用搜索引擎进行查询并显示结果,可以使用 `recency_days` 参数控制搜索内容的时效性。\n`mclick(ids: list[int])`:获取一系列指定 id 的页面内容。每次调用时,须选择3-10个页面。选择多个角度的页面,同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的,你也可以多打开一些可能有用的页面而不用担心内容过多。\n`open_url(url: str)`:打开指定的 URL。\n\n使用 `【{引用 id}†{引用文本}】` 来引用内容。\n\n操作步骤:1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。\n 如果用户提供了 URL,也可以用 `open_url` 直接打开页面。\n如果初次搜索结果没有找到合适的信息,也可以再次使用 `search` 进行搜索。"
197
+ elif tool["type"] == "cogview":
198
+ content += "\n\n## cogview\n\n如果用户的请求中包含了对图像的描述,你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述,规则:\n- 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。\n- 应当尽可能详细地描述图像生成的需求,需求描述约 100 英文单词。\n- 保持用户原始描述的意图。不要虚构内容或者没见过的人物。\n- 如无特殊说明,所在地为中国,持有中国立场并遵循中国社会主义价值观。"
199
+ else:
200
+ raise NotImplementedError(f"Unknown tool type {tool['type']}")
201
+ input = self.build_single_message("system", "", content, tokenize=tokenize)
202
+ if tokenize:
203
+ input_ids.extend(input)
204
+ else:
205
+ input_message += input
206
+ message = ""
207
+ message_prefix = None
208
+ if item.get("image"):
209
+ assert input_image is None, "Multiple images are not supported"
210
+ input_image = transform(item["image"])
211
+ message_prefix = self.convert_tokens_to_ids(
212
+ ["<|begin_of_image|>", "<|endoftext|>", "<|end_of_image|>"])
213
+ if item.get("content"):
214
+ message += item["content"]
215
+ if message or message_prefix:
216
+ input = self.build_single_message(
217
+ item["role"],
218
+ item.get("metadata", ""),
219
+ message,
220
+ tokenize=tokenize,
221
+ message_prefix=message_prefix
222
+ )
223
+ if tokenize:
224
+ input_ids.extend(input)
225
+ else:
226
+ input_message += input
227
+ if add_generation_prompt:
228
+ if tokenize:
229
+ input_ids.extend([self.convert_tokens_to_ids("<|assistant|>")])
230
+ else:
231
+ input_message += "<|assistant|>"
232
+ return {"input": input_ids if tokenize else input_message, "image": input_image}
233
+
234
+ # Main logic to handle different conversation formats
235
+ if isinstance(conversation, list) and all(isinstance(i, dict) for i in conversation):
236
+ result = handle_single_conversation(conversation)
237
+ input_ids = result["input"]
238
+ input_images = [result["image"]]
239
+ elif isinstance(conversation, list) and all(isinstance(i, list) for i in conversation):
240
+ results = [handle_single_conversation(c) for c in conversation]
241
+ input_ids = [item["input"] for item in results]
242
+ input_images = [item["image"] for item in results]
243
+ elif hasattr(conversation, "messages"):
244
+ result = handle_single_conversation(conversation.messages)
245
+ input_ids = result["input"]
246
+ input_images = [result["image"]]
247
+ else:
248
+ raise ValueError("Invalid conversation format")
249
+
250
+ if tokenize:
251
+ output = self.batch_encode_plus(
252
+ [input_ids] if isinstance(input_ids[0], int) else input_ids,
253
+ padding=padding,
254
+ truncation=truncation,
255
+ max_length=max_length,
256
+ return_tensors=return_tensors,
257
+ is_split_into_words=True,
258
+ add_special_tokens=False
259
+ )
260
+ if return_dict:
261
+ found_image = False
262
+ for image in input_images:
263
+ if image is not None:
264
+ found_image = True
265
+ break
266
+ if found_image:
267
+ output["images"] = torch.stack(input_images)
268
+ return output
269
+ else:
270
+ return output["input_ids"]
271
+ else:
272
+ return input_ids
273
+
274
+
275
+ def build_inputs_with_special_tokens(
276
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
277
+ ) -> List[int]:
278
+ """
279
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
280
+ adding special tokens. A BERT sequence has the following format:
281
+
282
+ - single sequence: `[CLS] X [SEP]`
283
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
284
+
285
+ Args:
286
+ token_ids_0 (`List[int]`):
287
+ List of IDs to which the special tokens will be added.
288
+ token_ids_1 (`List[int]`, *optional*):
289
+ Optional second list of IDs for sequence pairs.
290
+
291
+ Returns:
292
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
293
+ """
294
+ prefix_tokens = self.get_prefix_tokens()
295
+ token_ids_0 = prefix_tokens + token_ids_0
296
+ if token_ids_1 is not None:
297
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
298
+ return token_ids_0
299
+
300
+ def _pad(
301
+ self,
302
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
303
+ max_length: Optional[int] = None,
304
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
305
+ pad_to_multiple_of: Optional[int] = 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 max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
341
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
342
+
343
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
344
+
345
+ # Initialize attention mask if not present.
346
+ if "attention_mask" not in encoded_inputs:
347
+ encoded_inputs["attention_mask"] = [1] * seq_length
348
+
349
+ if "position_ids" not in encoded_inputs:
350
+ encoded_inputs["position_ids"] = list(range(seq_length))
351
+
352
+ if needs_to_be_padded:
353
+ difference = max_length - len(required_input)
354
+
355
+ if "attention_mask" in encoded_inputs:
356
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
357
+ if "position_ids" in encoded_inputs:
358
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
359
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
360
+
361
+ return encoded_inputs
coin_model_funtuned_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
+ }
coin_model_funtuned_visual.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def standard_attention(query_layer, key_layer, value_layer, scaling_attention_score=True):
10
+ if scaling_attention_score:
11
+ query_layer = query_layer / math.sqrt(query_layer.shape[-1])
12
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
13
+
14
+ attention_probs = F.softmax(attention_scores, dim=-1)
15
+
16
+ context_layer = torch.matmul(attention_probs, value_layer)
17
+ return context_layer
18
+
19
+ def attention_fn_default(query_layer, key_layer, value_layer, scaling_attention_score=True):
20
+ if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score:
21
+ # Pytorch 2.0 attention uses very much memory if attention_mask is float, and has NaN bug if attention_mask is None.
22
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
23
+ query_layer, key_layer, value_layer,
24
+ attn_mask=None,
25
+ dropout_p=0.,
26
+ is_causal=False
27
+ )
28
+ return attn_output
29
+ else:
30
+ return standard_attention(
31
+ query_layer, key_layer, value_layer, scaling_attention_score=scaling_attention_score
32
+ )
33
+
34
+ class PatchEmbedding(nn.Module):
35
+ def __init__(self, config):
36
+ super().__init__()
37
+ self.proj = nn.Conv2d(config.in_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size)
38
+ self.cls_embedding = nn.Parameter(torch.zeros(1, config.hidden_size))
39
+ self.position_embedding = nn.Embedding(config.num_positions, config.hidden_size)
40
+
41
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
42
+ x = self.proj(images)
43
+ x = x.flatten(2).transpose(1, 2)
44
+ cls_token = self.cls_embedding.expand(x.shape[0], -1, -1)
45
+ x = torch.cat((cls_token, x), dim=1)
46
+ x += self.position_embedding.weight.unsqueeze(0)
47
+ return x
48
+
49
+
50
+ class Attention(nn.Module):
51
+ def __init__(self, config):
52
+ super().__init__()
53
+ self.num_heads = config.num_heads
54
+ head_dim = config.hidden_size // config.num_heads
55
+ self.scale = head_dim ** -0.5
56
+ self.query_key_value = nn.Linear(config.hidden_size, config.hidden_size * 3)
57
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
58
+ self.output_dropout = torch.nn.Dropout(config.dropout_prob)
59
+
60
+ def forward(self, x: "tensor(B, L, D)") -> "tensor(B, L, D)":
61
+ B, L, _ = x.shape
62
+ qkv = self.query_key_value(x)
63
+ qkv = qkv.reshape(B, L, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, H, L, D
64
+ q, k, v = qkv[0], qkv[1], qkv[2]
65
+
66
+ out = attention_fn_default(
67
+ q, k, v
68
+ )
69
+ output = self.dense(out.transpose(1, 2).reshape(B, L, -1))
70
+ output = self.output_dropout(output)
71
+ return output
72
+
73
+ def attention(self, q, k, v):
74
+ attn_weights = torch.matmul(q * self.scale, k.transpose(-2, -1))
75
+ attn_weights = attn_weights.softmax(dim=-1)
76
+ output = torch.matmul(attn_weights, v)
77
+ return output
78
+
79
+
80
+ class MLP(nn.Module):
81
+ def __init__(self, config):
82
+ super().__init__()
83
+ self.config = config
84
+ self.activation_fn = ACT2FN[config.hidden_act]
85
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
86
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
87
+
88
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
89
+ x = self.fc1(x)
90
+ x = self.activation_fn(x)
91
+ x = self.fc2(x)
92
+ return x
93
+
94
+
95
+ class TransformerLayer(nn.Module):
96
+ def __init__(self, config):
97
+ super().__init__()
98
+ self.input_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
99
+ self.attention = Attention(config)
100
+ self.mlp = MLP(config)
101
+ self.post_attention_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
102
+
103
+ def forward(self, hidden_states):
104
+ attention_input = hidden_states
105
+ attention_output = self.input_layernorm(self.attention(attention_input))
106
+ hidden_states = attention_input + attention_output
107
+ mlp_input = hidden_states
108
+ mlp_output = self.post_attention_layernorm(self.mlp(mlp_input))
109
+ output = mlp_input + mlp_output
110
+ return output
111
+
112
+
113
+ class Transformer(nn.Module):
114
+ def __init__(self, config):
115
+ super().__init__()
116
+ self.layers = nn.ModuleList([TransformerLayer(config) for _ in range(config.num_hidden_layers)])
117
+
118
+ def forward(self, hidden_states):
119
+ for layer_module in self.layers:
120
+ hidden_states = layer_module(hidden_states)
121
+ return hidden_states
122
+
123
+
124
+ class GLU(nn.Module):
125
+ def __init__(self, config, in_features):
126
+ super().__init__()
127
+ self.linear_proj = nn.Linear(in_features, config.hidden_size, bias=False)
128
+ self.norm1 = nn.LayerNorm(config.hidden_size)
129
+ self.act1 = nn.GELU()
130
+ self.act2 = nn.functional.silu
131
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.ffn_hidden_size, bias=False)
132
+ self.gate_proj = nn.Linear(config.hidden_size, config.ffn_hidden_size, bias=False)
133
+ self.dense_4h_to_h = nn.Linear(config.ffn_hidden_size, config.hidden_size, bias=False)
134
+
135
+ def forward(self, x):
136
+ x = self.linear_proj(x)
137
+ x = self.act1(self.norm1(x))
138
+ x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
139
+ x = self.dense_4h_to_h(x)
140
+ return x
141
+
142
+
143
+ class EVA2CLIPModel(nn.Module):
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ vision_config = Namespace(**config.vision_config)
147
+ self.patch_embedding = PatchEmbedding(vision_config)
148
+ self.transformer = Transformer(vision_config)
149
+ self.linear_proj = GLU(config, in_features=config.hidden_size)
150
+ self.conv = nn.Conv2d(in_channels=vision_config.hidden_size, out_channels=config.hidden_size, kernel_size=2, stride=2)
151
+ self.boi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
152
+ self.eoi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
153
+ self.scaling_factor = vision_config.scaling_factor
154
+
155
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
156
+ x = self.patch_embedding(images)
157
+ x = self.transformer(x)
158
+ x = x[:, 1:]
159
+
160
+ b, s, h = x.shape
161
+ grid_size = int(s**0.5)
162
+ x = x.view(b, grid_size, grid_size, h).permute(0, 3, 1, 2)
163
+ x = self.conv(x)
164
+
165
+ x = x.flatten(2).transpose(1, 2)
166
+ x = self.linear_proj(x)
167
+ boi = self.boi.expand(x.shape[0], -1, -1)
168
+ eoi = self.eoi.expand(x.shape[0], -1, -1)
169
+ x = torch.cat((boi, x, eoi), dim=1)
170
+ x = x / self.scaling_factor
171
+ return x
model-00001-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5f7c4461ec292196389492c8ba97de591d9eaed6f214608f3ee875e0a5e3442
3
+ size 1945161760
model-00002-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5413314e163920b6a3563a5a8b5016204171cf78f00c60426eec503fa12273ee
3
+ size 1815217640
model-00003-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f069db54d8e01d0c8126abccd5eba80ad1fd9f1ecbc9c83d422609d0a971a23
3
+ size 1968291912
model-00004-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7263d40c35f58a39c3d01bd35c7b43e7fc38a29e5cf18d4cd54baafcd5995312
3
+ size 1927406992
model-00005-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cba45f7b0bda438f74b95a9beb5bfc9d0bd80015c2b67d85f585be85a0e91b7c
3
+ size 1815217672
model-00006-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c865a6bbb37362a13cefa732193ae6c5c1151106b61bfe6d7fd730778aca808
3
+ size 1968291952
model-00007-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a55c2cb3be400a256b441946fa9d8b6402fe6f7708467325569ed23f2e530ef8
3
+ size 1927406992
model-00009-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bff55c70098795914510320a7c994d8d8c108b9e2b95c429cddee5fcef3e5d4
3
+ size 1968291952
model-00010-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c08d3cc18a5fb1c9dd2e0d90e334bad0a38db4fdfc2604e5165f8fac58e61499
3
+ size 1971932440
model-00011-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df12f8ce20711ef2f3aa93f9c5c75b47bdb31ce5a4baff967267a63fd63e9483
3
+ size 1957054176
model-00012-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d14427429d21c245eabd966d145069247cf7c721905b18181faae4e7ec90966c
3
+ size 1982747048
model-00013-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e583e560b38e6b69e3b6b6b0d6ac1d10bc4a63534fa48021eb7089feb0b9f7f8
3
+ size 1957054280
model-00014-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36bf2fd8ba6b480964bf724a9027a7ffbf2930fd3bb2244d6df2469a12b7f02c
3
+ size 1982747048
model-00015-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1eb45e9f635e09a3ea4b3ee9db6ae612fce6537dd82d20acc927eb8244f21858
3
+ size 810746296
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a493598071550244b2ee7f26118f3edec2150b9dfa967929a99052ac83fe716
3
+ size 2623634