vcadillo commited on
Commit
638b1c2
1 Parent(s): 25e4c5c

Upload ChatGLMForConditionalGeneration

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "glm-4v-9b-4-bits",
3
+ "add_bias_linear": false,
4
+ "add_qkv_bias": true,
5
+ "apply_query_key_layer_scaling": true,
6
+ "apply_residual_connection_post_layernorm": false,
7
+ "architectures": [
8
+ "ChatGLMForConditionalGeneration"
9
+ ],
10
+ "attention_dropout": 0.0,
11
+ "attention_softmax_in_fp32": true,
12
+ "auto_map": {
13
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
14
+ "AutoModel": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForConditionalGeneration",
15
+ "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
16
+ "AutoModelForSeq2SeqLM": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForConditionalGeneration",
17
+ "AutoModelForSequenceClassification": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForSequenceClassification"
18
+ },
19
+ "bias_dropout_fusion": true,
20
+ "boi_token_id": 151339,
21
+ "classifier_dropout": null,
22
+ "eoi_token_id": 151340,
23
+ "eos_token_id": [
24
+ 151329,
25
+ 151336,
26
+ 151338
27
+ ],
28
+ "ffn_hidden_size": 13696,
29
+ "fp32_residual_connection": false,
30
+ "hidden_dropout": 0.0,
31
+ "hidden_size": 4096,
32
+ "kv_channels": 128,
33
+ "layernorm_epsilon": 1.5625e-07,
34
+ "model_type": "chatglm",
35
+ "multi_query_attention": true,
36
+ "multi_query_group_num": 2,
37
+ "num_attention_heads": 32,
38
+ "num_layers": 40,
39
+ "original_rope": true,
40
+ "pad_token_id": 151329,
41
+ "padded_vocab_size": 151552,
42
+ "post_layer_norm": true,
43
+ "pre_seq_len": null,
44
+ "prefix_projection": false,
45
+ "quantization_config": {
46
+ "_load_in_4bit": true,
47
+ "_load_in_8bit": false,
48
+ "bnb_4bit_compute_dtype": "float16",
49
+ "bnb_4bit_quant_storage": "uint8",
50
+ "bnb_4bit_quant_type": "nf4",
51
+ "bnb_4bit_use_double_quant": false,
52
+ "llm_int8_enable_fp32_cpu_offload": false,
53
+ "llm_int8_has_fp16_weight": false,
54
+ "llm_int8_skip_modules": null,
55
+ "llm_int8_threshold": 6.0,
56
+ "load_in_4bit": true,
57
+ "load_in_8bit": false,
58
+ "quant_method": "bitsandbytes"
59
+ },
60
+ "rmsnorm": true,
61
+ "rope_ratio": 1,
62
+ "seq_length": 8192,
63
+ "tie_word_embeddings": false,
64
+ "torch_dtype": "float16",
65
+ "transformers_version": "4.41.2",
66
+ "use_cache": true,
67
+ "vision_config": {
68
+ "dropout_prob": 0.0,
69
+ "hidden_act": "gelu",
70
+ "hidden_size": 1792,
71
+ "image_size": 1120,
72
+ "in_channels": 3,
73
+ "intermediate_size": 15360,
74
+ "layer_norm_eps": 1e-06,
75
+ "num_heads": 16,
76
+ "num_hidden_layers": 63,
77
+ "num_positions": 6401,
78
+ "patch_size": 14,
79
+ "scaling_factor": 8
80
+ },
81
+ "vocab_size": 151552
82
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ model_type = "chatglm"
6
+
7
+ def __init__(
8
+ self,
9
+ num_layers=28,
10
+ padded_vocab_size=65024,
11
+ hidden_size=4096,
12
+ ffn_hidden_size=13696,
13
+ kv_channels=128,
14
+ num_attention_heads=32,
15
+ seq_length=2048,
16
+ hidden_dropout=0.0,
17
+ classifier_dropout=None,
18
+ attention_dropout=0.0,
19
+ layernorm_epsilon=1e-5,
20
+ rmsnorm=True,
21
+ apply_residual_connection_post_layernorm=False,
22
+ post_layer_norm=True,
23
+ add_bias_linear=False,
24
+ add_qkv_bias=False,
25
+ bias_dropout_fusion=True,
26
+ multi_query_attention=False,
27
+ multi_query_group_num=1,
28
+ rope_ratio=1,
29
+ apply_query_key_layer_scaling=True,
30
+ attention_softmax_in_fp32=True,
31
+ fp32_residual_connection=False,
32
+ pre_seq_len=None,
33
+ prefix_projection=False,
34
+ boi_token_id=None,
35
+ eoi_token_id=None,
36
+ **kwargs
37
+ ):
38
+ self.num_layers = num_layers
39
+ self.vocab_size = padded_vocab_size
40
+ self.padded_vocab_size = padded_vocab_size
41
+ self.hidden_size = hidden_size
42
+ self.ffn_hidden_size = ffn_hidden_size
43
+ self.kv_channels = kv_channels
44
+ self.num_attention_heads = num_attention_heads
45
+ self.seq_length = seq_length
46
+ self.hidden_dropout = hidden_dropout
47
+ self.classifier_dropout = classifier_dropout
48
+ self.attention_dropout = attention_dropout
49
+ self.layernorm_epsilon = layernorm_epsilon
50
+ self.rmsnorm = rmsnorm
51
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
52
+ self.post_layer_norm = post_layer_norm
53
+ self.add_bias_linear = add_bias_linear
54
+ self.add_qkv_bias = add_qkv_bias
55
+ self.bias_dropout_fusion = bias_dropout_fusion
56
+ self.multi_query_attention = multi_query_attention
57
+ self.multi_query_group_num = multi_query_group_num
58
+ self.rope_ratio = rope_ratio
59
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
60
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
61
+ self.fp32_residual_connection = fp32_residual_connection
62
+ self.pre_seq_len = pre_seq_len
63
+ self.prefix_projection = prefix_projection
64
+ self.boi_token_id = boi_token_id
65
+ self.eoi_token_id = eoi_token_id
66
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": [
4
+ 151329,
5
+ 151336,
6
+ 151338
7
+ ],
8
+ "pad_token_id": 151329,
9
+ "transformers_version": "4.41.2"
10
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09b7aad011b04d5ffacb8023e078e0700f798133f71cbd1743c906df2ac7b2ad
3
+ size 4996695244
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4d7c3d9a81915546f1f30451061ad700ac4208412d50d26ea49250119cc0196
3
+ size 3782170696
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_chatglm.py ADDED
@@ -0,0 +1,1357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
25
+ from transformers.generation.logits_process import LogitsProcessor
26
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
27
+
28
+ from .configuration_chatglm import ChatGLMConfig
29
+ from .visual import EVA2CLIPModel
30
+
31
+ # flags required to enable jit fusion kernels
32
+
33
+ if sys.platform != 'darwin':
34
+ torch._C._jit_set_profiling_mode(False)
35
+ torch._C._jit_set_profiling_executor(False)
36
+ torch._C._jit_override_can_fuse_on_cpu(True)
37
+ torch._C._jit_override_can_fuse_on_gpu(True)
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ LANGUAGE_TOKEN_TYPE = 0
42
+ VISION_TOKEN_TYPE = 1
43
+
44
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
45
+ _CONFIG_FOR_DOC = "ChatGLMConfig"
46
+
47
+ def default_init(cls, *args, **kwargs):
48
+ return cls(*args, **kwargs)
49
+
50
+
51
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
52
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
53
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
54
+ scores.zero_()
55
+ scores[..., 198] = 5e4
56
+ return scores
57
+
58
+
59
+ class PrefixEncoder(torch.nn.Module):
60
+ """
61
+ The torch.nn model to encode the prefix
62
+ Input shape: (batch-size, prefix-length)
63
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
64
+ """
65
+
66
+ def __init__(self, config: ChatGLMConfig):
67
+ super().__init__()
68
+ self.prefix_projection = config.prefix_projection
69
+ if self.prefix_projection:
70
+ # Use a two-layer MLP to encode the prefix
71
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
72
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
73
+ self.trans = torch.nn.Sequential(
74
+ torch.nn.Linear(kv_size, config.hidden_size),
75
+ torch.nn.Tanh(),
76
+ torch.nn.Linear(config.hidden_size, kv_size)
77
+ )
78
+ else:
79
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
80
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
81
+
82
+ def forward(self, prefix: torch.Tensor):
83
+ if self.prefix_projection:
84
+ prefix_tokens = self.embedding(prefix)
85
+ past_key_values = self.trans(prefix_tokens)
86
+ else:
87
+ past_key_values = self.embedding(prefix)
88
+ return past_key_values
89
+
90
+
91
+ def split_tensor_along_last_dim(
92
+ tensor: torch.Tensor,
93
+ num_partitions: int,
94
+ contiguous_split_chunks: bool = False,
95
+ ) -> List[torch.Tensor]:
96
+ """Split a tensor along its last dimension.
97
+
98
+ Arguments:
99
+ tensor: input tensor.
100
+ num_partitions: number of partitions to split the tensor
101
+ contiguous_split_chunks: If True, make each chunk contiguous
102
+ in memory.
103
+
104
+ Returns:
105
+ A list of Tensors
106
+ """
107
+ # Get the size and dimension.
108
+ last_dim = tensor.dim() - 1
109
+ last_dim_size = tensor.size()[last_dim] // num_partitions
110
+ # Split.
111
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
112
+ # Note: torch.split does not create contiguous tensors by default.
113
+ if contiguous_split_chunks:
114
+ return tuple(chunk.contiguous() for chunk in tensor_list)
115
+
116
+ return tensor_list
117
+
118
+
119
+ class RotaryEmbedding(nn.Module):
120
+ def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
121
+ super().__init__()
122
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
123
+ self.register_buffer("inv_freq", inv_freq)
124
+ self.dim = dim
125
+ self.original_impl = original_impl
126
+ self.rope_ratio = rope_ratio
127
+
128
+ def impl(self, seq_length: int, dim: int, device: torch.device, dtype: torch.dtype):
129
+ base = 10000 * self.rope_ratio
130
+ inv_freq = 1.0 / (
131
+ base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
132
+ seq = torch.arange(seq_length, device=inv_freq.device, dtype=torch.float32)
133
+ freqs = torch.outer(seq, inv_freq)
134
+ # first part even vector components, second part odd vector components,
135
+ # 2 * dim in dimension size
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ return emb
138
+
139
+ def forward_impl(
140
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
141
+ ):
142
+ """Enhanced Transformer with Rotary Position Embedding.
143
+
144
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
145
+ transformers/rope/__init__.py. MIT License:
146
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
147
+ """
148
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
149
+ base = base * self.rope_ratio
150
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
151
+
152
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
153
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
154
+
155
+ # Calculate the product of position index and $\theta_i$
156
+ idx_theta = torch.outer(seq_idx, theta).float()
157
+
158
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
159
+
160
+ # this is to mimic the behaviour of complex32, else we will get different results
161
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
162
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
163
+ return cache
164
+
165
+ def forward(self, max_seq_len, offset=0):
166
+ if self.original_impl:
167
+ return self.forward_impl(
168
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
169
+ )
170
+ else:
171
+ return self.impl(max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device)
172
+
173
+
174
+ @torch.jit.script
175
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
176
+ # x: [b, np, sq, hn]
177
+ b, np, sq, hn = x.size(0), x.size(1), x.size(2), x.size(3)
178
+ rot_dim = rope_cache.shape[-2] * 2
179
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
180
+ # truncate to support variable sizes
181
+ rope_cache = rope_cache[:, :sq]
182
+ xshaped = x.reshape(b, np, sq, rot_dim // 2, 2)
183
+ rope_cache = rope_cache.view(-1, 1, sq, xshaped.size(3), 2)
184
+ x_out2 = torch.stack(
185
+ [
186
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
187
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
188
+ ],
189
+ -1,
190
+ )
191
+ x_out2 = x_out2.flatten(3)
192
+ return torch.cat((x_out2, x_pass), dim=-1)
193
+
194
+
195
+ class RMSNorm(torch.nn.Module):
196
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
197
+ super().__init__()
198
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
199
+ self.eps = eps
200
+
201
+ def forward(self, hidden_states: torch.Tensor):
202
+ input_dtype = hidden_states.dtype
203
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
204
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
205
+
206
+ return (self.weight * hidden_states).to(input_dtype)
207
+
208
+
209
+ class CoreAttention(torch.nn.Module):
210
+ def __init__(self, config: ChatGLMConfig, layer_number):
211
+ super(CoreAttention, self).__init__()
212
+
213
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
214
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
215
+ if self.apply_query_key_layer_scaling:
216
+ self.attention_softmax_in_fp32 = True
217
+ self.layer_number = max(1, layer_number)
218
+
219
+ projection_size = config.kv_channels * config.num_attention_heads
220
+
221
+ # Per attention head and per partition values.
222
+ self.hidden_size_per_partition = projection_size
223
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
224
+ self.num_attention_heads_per_partition = config.num_attention_heads
225
+
226
+ coeff = None
227
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
228
+ if self.apply_query_key_layer_scaling:
229
+ coeff = self.layer_number
230
+ self.norm_factor *= coeff
231
+ self.coeff = coeff
232
+
233
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
234
+
235
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
236
+ pytorch_major_version = int(torch.__version__.split('.')[0])
237
+ if pytorch_major_version >= 2:
238
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
239
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
240
+ is_causal=True)
241
+ else:
242
+ if attention_mask is not None:
243
+ attention_mask = ~attention_mask
244
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
245
+ attention_mask)
246
+ context_layer = context_layer.transpose(1, 2).contiguous()
247
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
248
+ context_layer = context_layer.reshape(*new_context_layer_shape)
249
+ else:
250
+ # Raw attention scores
251
+
252
+ # [b, np, sq, sk]
253
+ output_size = (query_layer.size(0), query_layer.size(1), query_layer.size(2), key_layer.size(2))
254
+
255
+ # [b, np, sq, hn] -> [b * np, sq, hn]
256
+ query_layer = query_layer.view(output_size[0] * output_size[1], output_size[2], -1)
257
+ # [b, np, sk, hn] -> [b * np, sk, hn]
258
+ key_layer = key_layer.view(output_size[0] * output_size[1], output_size[3], -1)
259
+
260
+ # preallocting input tensor: [b * np, sq, sk]
261
+ matmul_input_buffer = torch.empty(
262
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
263
+ device=query_layer.device
264
+ )
265
+
266
+ # Raw attention scores. [b * np, sq, sk]
267
+ matmul_result = torch.baddbmm(
268
+ matmul_input_buffer,
269
+ query_layer, # [b * np, sq, hn]
270
+ key_layer.transpose(1, 2), # [b * np, hn, sk]
271
+ beta=0.0,
272
+ alpha=(1.0 / self.norm_factor),
273
+ )
274
+
275
+ # change view to [b, np, sq, sk]
276
+ attention_scores = matmul_result.view(*output_size)
277
+
278
+ # ===========================
279
+ # Attention probs and dropout
280
+ # ===========================
281
+
282
+ # attention scores and attention mask [b, np, sq, sk]
283
+ if self.attention_softmax_in_fp32:
284
+ attention_scores = attention_scores.float()
285
+ if self.coeff is not None:
286
+ attention_scores = attention_scores * self.coeff
287
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
288
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
289
+ device=attention_scores.device, dtype=torch.bool)
290
+ attention_mask.tril_()
291
+ attention_mask = ~attention_mask
292
+ if attention_mask is not None:
293
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
294
+ attention_probs = F.softmax(attention_scores, dim=-1)
295
+ attention_probs = attention_probs.type_as(value_layer)
296
+
297
+ # This is actually dropping out entire tokens to attend to, which might
298
+ # seem a bit unusual, but is taken from the original Transformer paper.
299
+ attention_probs = self.attention_dropout(attention_probs)
300
+ # =========================
301
+ # Context layer. [sq, b, hp]
302
+ # =========================
303
+
304
+ # value_layer -> context layer.
305
+ # [sk, b, np, hn] --> [b, np, sq, hn]
306
+
307
+ # context layer shape: [b, np, sq, hn]
308
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
309
+ # change view [b * np, sk, hn]
310
+ value_layer = value_layer.view(output_size[0] * output_size[1], value_layer.size(2), -1)
311
+ # change view [b * np, sq, sk]
312
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
313
+ # matmul: [b * np, sq, hn]
314
+ context_layer = torch.bmm(attention_probs, value_layer)
315
+ # change view [b, np, sq, hn]
316
+ context_layer = context_layer.view(*output_size)
317
+ # [b, np, sq, hn] --> [b, sq, np, hn]
318
+ context_layer = context_layer.transpose(1, 2).contiguous()
319
+ # [b, sq, np, hn] --> [b, sq, hp]
320
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
321
+ context_layer = context_layer.reshape(*new_context_layer_shape)
322
+
323
+ return context_layer
324
+
325
+
326
+ class SelfAttention(torch.nn.Module):
327
+ """Parallel self-attention layer abstract class.
328
+
329
+ Self-attention layer takes input with size [s, b, h]
330
+ and returns output of the same size.
331
+ """
332
+
333
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
334
+ super(SelfAttention, self).__init__()
335
+ self.layer_number = max(1, layer_number)
336
+
337
+ self.projection_size = config.kv_channels * config.num_attention_heads
338
+
339
+ # Per attention head and per partition values.
340
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
341
+ self.num_attention_heads_per_partition = config.num_attention_heads
342
+
343
+ self.multi_query_attention = config.multi_query_attention
344
+ self.qkv_hidden_size = 3 * self.projection_size
345
+ self.original_rope = config.original_rope
346
+ if self.multi_query_attention:
347
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
348
+ self.qkv_hidden_size = (
349
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
350
+ )
351
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
352
+ bias=config.add_bias_linear or config.add_qkv_bias,
353
+ device=device, **_config_to_kwargs(config)
354
+ )
355
+
356
+ self.core_attention = CoreAttention(config, self.layer_number)
357
+
358
+ # Output.
359
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
360
+ device=device, **_config_to_kwargs(config)
361
+ )
362
+
363
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
364
+ if self.multi_query_attention:
365
+ num_attention_heads = self.num_multi_query_groups_per_partition
366
+ else:
367
+ num_attention_heads = self.num_attention_heads_per_partition
368
+ return torch.empty(
369
+ inference_max_sequence_len,
370
+ batch_size,
371
+ num_attention_heads,
372
+ self.hidden_size_per_attention_head,
373
+ dtype=dtype,
374
+ device=device,
375
+ )
376
+
377
+ def forward(
378
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
379
+ ):
380
+ # hidden_states: [b, sq, h]
381
+
382
+ # =================================================
383
+ # Pre-allocate memory for key-values for inference.
384
+ # =================================================
385
+ # =====================
386
+ # Query, Key, and Value
387
+ # =====================
388
+
389
+ # Attention heads [b, sq, h] --> [b, sq, (np * 3 * hn)]
390
+ mixed_x_layer = self.query_key_value(hidden_states)
391
+
392
+ if self.multi_query_attention:
393
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
394
+ [
395
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
396
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
397
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
398
+ ],
399
+ dim=-1,
400
+ )
401
+ query_layer = query_layer.view(
402
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
403
+ )
404
+ key_layer = key_layer.view(
405
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
406
+ )
407
+ value_layer = value_layer.view(
408
+ value_layer.size()[:-1]
409
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
410
+ )
411
+ else:
412
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
413
+ (self.num_attention_heads_per_partition,
414
+ 3 * self.hidden_size_per_attention_head)
415
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
416
+
417
+ # [b, sq, np, 3 * hn] --> 3 [b, sq, np, hn]
418
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
419
+
420
+ # [b, sq, np, hn] -> [b, np, sq, hn]
421
+ query_layer, key_layer, value_layer = [k.transpose(1, 2) for k in [query_layer, key_layer, value_layer]]
422
+
423
+ # apply relative positional encoding (rotary embedding)
424
+ if rotary_pos_emb is not None:
425
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
426
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
427
+
428
+ # adjust key and value for inference
429
+ if kv_cache is not None:
430
+ cache_k, cache_v = kv_cache
431
+ key_layer = torch.cat((cache_k, key_layer), dim=2)
432
+ value_layer = torch.cat((cache_v, value_layer), dim=2)
433
+ if use_cache:
434
+ kv_cache = (key_layer, value_layer)
435
+ else:
436
+ kv_cache = None
437
+
438
+ if self.multi_query_attention:
439
+ key_layer = key_layer.unsqueeze(2)
440
+ key_layer = key_layer.expand(
441
+ -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
442
+ )
443
+ key_layer = key_layer.contiguous().view(
444
+ key_layer.size()[:1] + (self.num_attention_heads_per_partition,) + key_layer.size()[3:]
445
+ )
446
+ value_layer = value_layer.unsqueeze(2)
447
+ value_layer = value_layer.expand(
448
+ -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
449
+ )
450
+ value_layer = value_layer.contiguous().view(
451
+ value_layer.size()[:1] + (self.num_attention_heads_per_partition,) + value_layer.size()[3:]
452
+ )
453
+
454
+ # ==================================
455
+ # core attention computation
456
+ # ==================================
457
+
458
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
459
+
460
+ # =================
461
+ # Output. [sq, b, h]
462
+ # =================
463
+
464
+ output = self.dense(context_layer)
465
+
466
+ return output, kv_cache
467
+
468
+
469
+ def _config_to_kwargs(args):
470
+ common_kwargs = {
471
+ "dtype": args.torch_dtype,
472
+ }
473
+ return common_kwargs
474
+
475
+
476
+ class MLP(torch.nn.Module):
477
+ """MLP.
478
+
479
+ MLP will take the input with h hidden state, project it to 4*h
480
+ hidden dimension, perform nonlinear transformation, and project the
481
+ state back into h hidden dimension.
482
+ """
483
+
484
+ def __init__(self, config: ChatGLMConfig, device=None):
485
+ super(MLP, self).__init__()
486
+
487
+ self.add_bias = config.add_bias_linear
488
+
489
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
490
+ self.dense_h_to_4h = nn.Linear(
491
+ config.hidden_size,
492
+ config.ffn_hidden_size * 2,
493
+ bias=self.add_bias,
494
+ device=device,
495
+ **_config_to_kwargs(config)
496
+ )
497
+
498
+ def swiglu(x):
499
+ x = torch.chunk(x, 2, dim=-1)
500
+ return F.silu(x[0]) * x[1]
501
+
502
+ self.activation_func = swiglu
503
+
504
+ # Project back to h.
505
+ self.dense_4h_to_h = nn.Linear(
506
+ config.ffn_hidden_size,
507
+ config.hidden_size,
508
+ bias=self.add_bias,
509
+ device=device,
510
+ **_config_to_kwargs(config)
511
+ )
512
+
513
+ def forward(self, hidden_states):
514
+ # [s, b, 4hp]
515
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
516
+ intermediate_parallel = self.activation_func(intermediate_parallel)
517
+ # [s, b, h]
518
+ output = self.dense_4h_to_h(intermediate_parallel)
519
+ return output
520
+
521
+
522
+ class GLMBlock(torch.nn.Module):
523
+ """A single transformer layer.
524
+
525
+ Transformer layer takes input with size [s, b, h] and returns an
526
+ output of the same size.
527
+ """
528
+
529
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
530
+ super(GLMBlock, self).__init__()
531
+ self.layer_number = layer_number
532
+
533
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
534
+
535
+ self.fp32_residual_connection = config.fp32_residual_connection
536
+
537
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
538
+ # Layernorm on the input data.
539
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
540
+ dtype=config.torch_dtype)
541
+
542
+ # Self attention.
543
+ self.self_attention = SelfAttention(config, layer_number, device=device)
544
+ self.hidden_dropout = config.hidden_dropout
545
+
546
+ # Layernorm on the attention output
547
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
548
+ dtype=config.torch_dtype)
549
+
550
+ # MLP
551
+ self.mlp = MLP(config, device=device)
552
+
553
+ def forward(
554
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
555
+ ):
556
+ # hidden_states: [s, b, h]
557
+
558
+ # Layer norm at the beginning of the transformer layer.
559
+ layernorm_output = self.input_layernorm(hidden_states)
560
+ # Self attention.
561
+ attention_output, kv_cache = self.self_attention(
562
+ layernorm_output,
563
+ attention_mask,
564
+ rotary_pos_emb,
565
+ kv_cache=kv_cache,
566
+ use_cache=use_cache
567
+ )
568
+
569
+ # Residual connection.
570
+ if self.apply_residual_connection_post_layernorm:
571
+ residual = layernorm_output
572
+ else:
573
+ residual = hidden_states
574
+
575
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
576
+ layernorm_input = residual + layernorm_input
577
+
578
+ # Layer norm post the self attention.
579
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
580
+
581
+ # MLP.
582
+ mlp_output = self.mlp(layernorm_output)
583
+
584
+ # Second residual connection.
585
+ if self.apply_residual_connection_post_layernorm:
586
+ residual = layernorm_output
587
+ else:
588
+ residual = layernorm_input
589
+
590
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
591
+ output = residual + output
592
+
593
+ return output, kv_cache
594
+
595
+
596
+ class GLMTransformer(torch.nn.Module):
597
+ """Transformer class."""
598
+
599
+ def __init__(self, config: ChatGLMConfig, device=None):
600
+ super(GLMTransformer, self).__init__()
601
+
602
+ self.fp32_residual_connection = config.fp32_residual_connection
603
+ self.post_layer_norm = config.post_layer_norm
604
+
605
+ # Number of layers.
606
+ self.num_layers = config.num_layers
607
+
608
+ # Transformer layers.
609
+ def build_layer(layer_number):
610
+ return GLMBlock(config, layer_number, device=device)
611
+
612
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
613
+
614
+ if self.post_layer_norm:
615
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
616
+ # Final layer norm before output.
617
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
618
+ dtype=config.torch_dtype)
619
+
620
+ self.gradient_checkpointing = False
621
+
622
+ def _get_layer(self, layer_number):
623
+ return self.layers[layer_number]
624
+
625
+ def forward(
626
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
627
+ use_cache: Optional[bool] = True,
628
+ output_hidden_states: Optional[bool] = False,
629
+ ):
630
+ if not kv_caches:
631
+ kv_caches = [None for _ in range(self.num_layers)]
632
+ presents = () if use_cache else None
633
+ if self.gradient_checkpointing and self.training:
634
+ if use_cache:
635
+ logger.warning_once(
636
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
637
+ )
638
+ use_cache = False
639
+
640
+ all_self_attentions = None
641
+ all_hidden_states = () if output_hidden_states else None
642
+ for index in range(self.num_layers):
643
+ if output_hidden_states:
644
+ all_hidden_states = all_hidden_states + (hidden_states,)
645
+
646
+ layer = self._get_layer(index)
647
+ if self.gradient_checkpointing and self.training:
648
+ layer_ret = torch.utils.checkpoint.checkpoint(
649
+ layer,
650
+ hidden_states,
651
+ attention_mask,
652
+ rotary_pos_emb,
653
+ kv_caches[index],
654
+ use_cache,
655
+ use_reentrant=False
656
+ )
657
+ else:
658
+ layer_ret = layer(
659
+ hidden_states,
660
+ attention_mask,
661
+ rotary_pos_emb,
662
+ kv_cache=kv_caches[index],
663
+ use_cache=use_cache
664
+ )
665
+ hidden_states, kv_cache = layer_ret
666
+ if use_cache:
667
+ presents = presents + (kv_cache,)
668
+
669
+ if output_hidden_states:
670
+ all_hidden_states = all_hidden_states + (hidden_states,)
671
+
672
+ # Final layer norm.
673
+ if self.post_layer_norm:
674
+ hidden_states = self.final_layernorm(hidden_states)
675
+
676
+ return hidden_states, presents, all_hidden_states, all_self_attentions
677
+
678
+
679
+ class ChatGLMPreTrainedModel(PreTrainedModel):
680
+ """
681
+ An abstract class to handle weights initialization and
682
+ a simple interface for downloading and loading pretrained models.
683
+ """
684
+
685
+ is_parallelizable = False
686
+ supports_gradient_checkpointing = True
687
+ config_class = ChatGLMConfig
688
+ base_model_prefix = "transformer"
689
+ _no_split_modules = ["GLMBlock"]
690
+
691
+ def _init_weights(self, module: nn.Module):
692
+ """Initialize the weights."""
693
+ return
694
+
695
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
696
+ batch_size, seq_length = input_ids.shape
697
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
698
+ full_attention_mask.tril_()
699
+ past_length = 0
700
+ if past_key_values:
701
+ past_length = past_key_values[0][0].shape[2]
702
+ if past_length:
703
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
704
+ device=input_ids.device), full_attention_mask), dim=-1)
705
+ if padding_mask is not None:
706
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
707
+ if not past_length and padding_mask is not None:
708
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
709
+ full_attention_mask = (full_attention_mask < 0.5).bool()
710
+ full_attention_mask.unsqueeze_(1)
711
+ return full_attention_mask
712
+
713
+ def get_position_ids(self, input_ids, device):
714
+ batch_size, seq_length = input_ids.shape
715
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
716
+ return position_ids
717
+
718
+ def get_multimodal_position_ids(self, input_ids, device):
719
+ batch_size, seq_length = input_ids.shape
720
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
721
+
722
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
723
+ if not self.supports_gradient_checkpointing:
724
+ raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
725
+
726
+
727
+ class Embedding(torch.nn.Module):
728
+ """Language model embeddings."""
729
+
730
+ def __init__(self, config: ChatGLMConfig, device=None):
731
+ super(Embedding, self).__init__()
732
+
733
+ self.hidden_size = config.hidden_size
734
+ # Word embeddings (parallel).
735
+ self.word_embeddings = nn.Embedding(
736
+ config.padded_vocab_size,
737
+ self.hidden_size,
738
+ dtype=config.torch_dtype,
739
+ device=device
740
+ )
741
+ self.fp32_residual_connection = config.fp32_residual_connection
742
+
743
+ def forward(self, input_ids):
744
+ # Embeddings.
745
+ words_embeddings = self.word_embeddings(input_ids)
746
+ embeddings = words_embeddings
747
+ # If the input flag for fp32 residual connection is set, convert for float.
748
+ if self.fp32_residual_connection:
749
+ embeddings = embeddings.float()
750
+ return embeddings
751
+
752
+
753
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
754
+ if images_list is None or len(images_list) == 0:
755
+ return True
756
+ for image_list in images_list:
757
+ if image_list is not None:
758
+ return False
759
+ return True
760
+
761
+
762
+ class ChatGLMModel(ChatGLMPreTrainedModel):
763
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
764
+ super().__init__(config)
765
+ if empty_init:
766
+ init_method = skip_init
767
+ else:
768
+ init_method = default_init
769
+ init_kwargs = {}
770
+ if device is not None:
771
+ init_kwargs["device"] = device
772
+ self.embedding = init_method(Embedding, config, **init_kwargs)
773
+ self.num_layers = config.num_layers
774
+ self.multi_query_group_num = config.multi_query_group_num
775
+ self.kv_channels = config.kv_channels
776
+
777
+ # Rotary positional embeddings
778
+ self.seq_length = config.seq_length
779
+ rotary_dim = (
780
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
781
+ )
782
+
783
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio,
784
+ original_impl=config.original_rope,
785
+ device=device, dtype=config.torch_dtype)
786
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
787
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
788
+ dtype=config.torch_dtype, **init_kwargs)
789
+ self.pre_seq_len = config.pre_seq_len
790
+ self.prefix_projection = config.prefix_projection
791
+ if self.pre_seq_len is not None:
792
+ for param in self.parameters():
793
+ param.requires_grad = False
794
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
795
+ self.prefix_encoder = PrefixEncoder(config)
796
+ self.dropout = torch.nn.Dropout(0.1)
797
+
798
+ self.vision = EVA2CLIPModel(config)
799
+
800
+ def get_input_embeddings(self):
801
+ return self.embedding.word_embeddings
802
+
803
+ def set_input_embeddings(self, value):
804
+ self.embedding.word_embeddings = value
805
+
806
+ def get_prompt(self, batch_size, device, dtype=torch.half):
807
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
808
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
809
+ past_key_values = past_key_values.view(
810
+ batch_size,
811
+ self.pre_seq_len,
812
+ self.pre_seq_len,
813
+ self.num_layers * 2,
814
+ self.multi_query_group_num,
815
+ self.kv_channels
816
+ )
817
+ # seq_len, b, nh, hidden_size
818
+ past_key_values = self.dropout(past_key_values)
819
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
820
+ return past_key_values
821
+
822
+ def forward(
823
+ self,
824
+ input_ids: torch.LongTensor = None,
825
+ images: torch.Tensor = None,
826
+ position_ids: Optional[torch.Tensor] = None,
827
+ attention_mask: Optional[torch.BoolTensor] = None,
828
+ full_attention_mask: Optional[torch.BoolTensor] = None,
829
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
830
+ inputs_embeds: Optional[torch.Tensor] = None,
831
+ use_cache: Optional[bool] = None,
832
+ output_hidden_states: Optional[bool] = None,
833
+ return_dict: Optional[bool] = None,
834
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
835
+ """take care of image_encode, position_ids and (attention_mask = None is fine)"""
836
+
837
+ # generate mode with past_key_values. the image features are already mapped
838
+ if past_key_values is None:
839
+ # not allow for inputs_embeds, because we want to process image feature
840
+ assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
841
+ if not is_empty(images): # multi-modality
842
+ image_size: int = self.config.vision_config['image_size']
843
+ patch_size: int = self.config.vision_config['patch_size']
844
+ num_patches = (image_size // patch_size // 2) ** 2
845
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
846
+ inputs_embeds = self.embedding(input_ids)
847
+
848
+ images = images.to(dtype=inputs_embeds.dtype)
849
+ images_features = self.vision(images)
850
+
851
+ if position_ids is None:
852
+ position_ids = self.get_position_ids(input_ids, device=inputs_embeds.device)
853
+ new_input_embeds, new_position_ids = [], []
854
+
855
+ for i in range(len(input_ids)):
856
+ input_id = input_ids[i].tolist()
857
+ boi_token_pos, eoi_token_pos = input_id.index(self.config.boi_token_id), input_id.index(
858
+ self.config.eoi_token_id)
859
+ assert eoi_token_pos - boi_token_pos == 2
860
+ new_input_embeds.append(torch.cat(
861
+ (inputs_embeds[i, :boi_token_pos], images_features[i], inputs_embeds[i, eoi_token_pos + 1:])))
862
+ new_position_ids.append(torch.cat(
863
+ (position_ids[i, :boi_token_pos + 1], position_ids[i, boi_token_pos + 1].repeat(num_patches),
864
+ position_ids[i, eoi_token_pos:])
865
+ ))
866
+ inputs_embeds = torch.stack(new_input_embeds, dim=0)
867
+ position_ids = torch.stack(new_position_ids, dim=0)
868
+
869
+ output_hidden_states = (
870
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
871
+ )
872
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
873
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
874
+
875
+ batch_size, seq_length = input_ids.shape
876
+
877
+ if inputs_embeds is None:
878
+ inputs_embeds = self.embedding(input_ids)
879
+
880
+ if self.pre_seq_len is not None:
881
+ if past_key_values is None:
882
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
883
+ dtype=inputs_embeds.dtype)
884
+ if attention_mask is not None:
885
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
886
+ attention_mask], dim=-1)
887
+
888
+ if full_attention_mask is None:
889
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
890
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
891
+
892
+ # Rotary positional embeddings
893
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
894
+ if position_ids is not None:
895
+ rotary_pos_emb = rotary_pos_emb[position_ids]
896
+ else:
897
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
898
+
899
+ # Run encoder.
900
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
901
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
902
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
903
+ )
904
+
905
+ if not return_dict:
906
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
907
+
908
+ return BaseModelOutputWithPast(
909
+ last_hidden_state=hidden_states,
910
+ past_key_values=presents,
911
+ hidden_states=all_hidden_states,
912
+ attentions=all_self_attentions,
913
+ )
914
+
915
+
916
+ def _history_to_prompt(history, query):
917
+ prompt = ''
918
+ flag = False
919
+ for i, (old_query, response) in enumerate(history):
920
+ prompt += ('<|user|>' if flag else '') + old_query + "<|assistant|>" + response + "<|endoftext|>"
921
+ flag = True
922
+ prompt += '{}{}<|assistant|>'.format('<|user|>' if flag else '', query)
923
+ return prompt
924
+
925
+
926
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
927
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
928
+ super().__init__(config)
929
+
930
+ self.max_sequence_length = config.max_length
931
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
932
+ self.config = config
933
+
934
+ def _update_model_kwargs_for_generation(
935
+ self,
936
+ outputs: ModelOutput,
937
+ model_kwargs: Dict[str, Any],
938
+ is_encoder_decoder: bool = False,
939
+ standardize_cache_format: bool = False,
940
+ ) -> Dict[str, Any]:
941
+ # update past_key_values
942
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
943
+ outputs, standardize_cache_format=standardize_cache_format
944
+ )
945
+
946
+ # update attention mask
947
+ if "attention_mask" in model_kwargs:
948
+ attention_mask = model_kwargs["attention_mask"]
949
+ model_kwargs["attention_mask"] = torch.cat(
950
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
951
+ )
952
+
953
+ # update position ids
954
+ if "position_ids" in model_kwargs:
955
+ position_ids = model_kwargs["position_ids"]
956
+ new_position_id = position_ids[..., -1:].clone()
957
+ new_position_id += 1
958
+ model_kwargs["position_ids"] = torch.cat(
959
+ [position_ids, new_position_id], dim=-1
960
+ )
961
+
962
+ model_kwargs["is_first_forward"] = False
963
+ return model_kwargs
964
+
965
+ def prepare_inputs_for_generation(
966
+ self,
967
+ input_ids: torch.LongTensor,
968
+ images: Optional[torch.Tensor] = None,
969
+ past_key_values: Optional[torch.Tensor] = None,
970
+ attention_mask: Optional[torch.Tensor] = None,
971
+ position_ids: Optional[torch.Tensor] = None,
972
+ use_cache: Optional[bool] = None,
973
+ is_first_forward: bool = True,
974
+ **kwargs
975
+ ) -> dict:
976
+ # only last token for input_ids if past is not None
977
+ if position_ids is None:
978
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
979
+ if not is_first_forward:
980
+ if past_key_values is not None:
981
+ position_ids = position_ids[..., -1:]
982
+ input_ids = input_ids[:, -1:]
983
+ return {
984
+ "input_ids": input_ids,
985
+ "images": images,
986
+ "past_key_values": past_key_values,
987
+ "position_ids": position_ids,
988
+ "attention_mask": attention_mask,
989
+ "return_last_logit": True,
990
+ "use_cache": use_cache
991
+ }
992
+
993
+ def forward(
994
+ self,
995
+ input_ids: Optional[torch.Tensor] = None,
996
+ images: List[List[torch.Tensor]] = None,
997
+ position_ids: Optional[torch.Tensor] = None,
998
+ attention_mask: Optional[torch.Tensor] = None,
999
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1000
+ inputs_embeds: Optional[torch.Tensor] = None,
1001
+ labels: Optional[torch.Tensor] = None,
1002
+ use_cache: Optional[bool] = None,
1003
+ output_attentions: Optional[bool] = None,
1004
+ output_hidden_states: Optional[bool] = None,
1005
+ return_dict: Optional[bool] = None,
1006
+ return_last_logit: Optional[bool] = False,
1007
+ ):
1008
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1009
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1010
+
1011
+ transformer_outputs = self.transformer(
1012
+ input_ids=input_ids,
1013
+ images=images,
1014
+ position_ids=position_ids,
1015
+ attention_mask=attention_mask,
1016
+ past_key_values=past_key_values,
1017
+ inputs_embeds=inputs_embeds,
1018
+ use_cache=use_cache,
1019
+ output_hidden_states=output_hidden_states,
1020
+ return_dict=return_dict,
1021
+ )
1022
+
1023
+ hidden_states = transformer_outputs[0]
1024
+ if return_last_logit:
1025
+ hidden_states = hidden_states[:, -1:]
1026
+ lm_logits = self.transformer.output_layer(hidden_states)
1027
+
1028
+ loss = None
1029
+ if labels is not None:
1030
+ lm_logits = lm_logits.to(torch.float32)
1031
+
1032
+ # Shift so that tokens < n predict n
1033
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1034
+ shift_labels = labels[..., 1:].contiguous()
1035
+ # Flatten the tokens
1036
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1037
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1038
+
1039
+ lm_logits = lm_logits.to(hidden_states.dtype)
1040
+ loss = loss.to(hidden_states.dtype)
1041
+
1042
+ if not return_dict:
1043
+ output = (lm_logits,) + transformer_outputs[1:]
1044
+ return ((loss,) + output) if loss is not None else output
1045
+
1046
+ return CausalLMOutputWithPast(
1047
+ loss=loss,
1048
+ logits=lm_logits,
1049
+ past_key_values=transformer_outputs.past_key_values,
1050
+ hidden_states=transformer_outputs.hidden_states,
1051
+ attentions=transformer_outputs.attentions,
1052
+ )
1053
+
1054
+ @staticmethod
1055
+ def _reorder_cache(
1056
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1057
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1058
+ """
1059
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1060
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1061
+ beam_idx at every generation step.
1062
+
1063
+ Output shares the same memory storage as `past`.
1064
+ """
1065
+ return tuple(
1066
+ (
1067
+ layer_past[0].index_select(0, beam_idx.to(layer_past[0].device)),
1068
+ layer_past[1].index_select(0, beam_idx.to(layer_past[1].device)),
1069
+ )
1070
+ for layer_past in past
1071
+ )
1072
+
1073
+ def process_response(self, output, history):
1074
+ content = ""
1075
+ history = deepcopy(history)
1076
+ for response in output.split("<|assistant|>"):
1077
+ if "\n" in response:
1078
+ metadata, content = response.split("\n", maxsplit=1)
1079
+ else:
1080
+ metadata, content = "", response
1081
+ if not metadata.strip():
1082
+ content = content.strip()
1083
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1084
+ content = content.replace("[[训练时间]]", "2023年")
1085
+ else:
1086
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1087
+ if history[0]["role"] == "system" and "tools" in history[0]:
1088
+ parameters = json.loads(content)
1089
+ content = {"name": metadata.strip(), "parameters": parameters}
1090
+ else:
1091
+ content = {"name": metadata.strip(), "content": content}
1092
+ return content, history
1093
+
1094
+ @torch.inference_mode()
1095
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
1096
+ max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1097
+ **kwargs):
1098
+ if history is None:
1099
+ history = []
1100
+ if logits_processor is None:
1101
+ logits_processor = LogitsProcessorList()
1102
+ logits_processor.append(InvalidScoreLogitsProcessor())
1103
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1104
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1105
+ message = {"role": role, "content": query}
1106
+ if image is not None:
1107
+ message["image"] = image
1108
+ history.append(message)
1109
+ inputs = tokenizer.apply_chat_template(history, add_generation_prompt=True, tokenize=True,
1110
+ return_tensors="pt", return_dict=True)
1111
+ inputs = inputs.to(self.device)
1112
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
1113
+ tokenizer.convert_tokens_to_ids("<|observation|>")]
1114
+ outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
1115
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1116
+ response = tokenizer.decode(outputs)
1117
+ response, history = self.process_response(response, history)
1118
+ return response, history
1119
+
1120
+ @torch.inference_mode()
1121
+ def stream_chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
1122
+ past_key_values=None, max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
1123
+ logits_processor=None, return_past_key_values=False, **kwargs):
1124
+ if history is None:
1125
+ history = []
1126
+ if logits_processor is None:
1127
+ logits_processor = LogitsProcessorList()
1128
+ logits_processor.append(InvalidScoreLogitsProcessor())
1129
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
1130
+ tokenizer.convert_tokens_to_ids("<|observation|>")]
1131
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1132
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1133
+ message = {"role": role, "content": "query"}
1134
+ if image is not None:
1135
+ message["image"] = image
1136
+ if past_key_values is None:
1137
+ inputs = tokenizer.apply_chat_template(history + [message],
1138
+ add_generation_prompt=True, tokenize=True, return_tensors="pt",
1139
+ return_dict=True)
1140
+ else:
1141
+ inputs = tokenizer.apply_chat_template([message], add_special_tokens=False,
1142
+ add_generation_prompt=True, tokenize=True, return_tensors="pt",
1143
+ return_dict=True)
1144
+ inputs = inputs.to(self.device)
1145
+ if past_key_values is not None:
1146
+ past_length = past_key_values[0][0].shape[2]
1147
+ if self.transformer.pre_seq_len is not None:
1148
+ past_length -= self.transformer.pre_seq_len
1149
+ inputs.position_ids += past_length
1150
+ attention_mask = inputs.attention_mask
1151
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1152
+ inputs['attention_mask'] = attention_mask
1153
+ history.append({"role": role, "content": query})
1154
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1155
+ eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
1156
+ **gen_kwargs):
1157
+ if return_past_key_values:
1158
+ outputs, past_key_values = outputs
1159
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1160
+ response = tokenizer.decode(outputs)
1161
+ if response and response[-1] != "�":
1162
+ response, new_history = self.process_response(response, history)
1163
+ if return_past_key_values:
1164
+ yield response, new_history, past_key_values
1165
+ else:
1166
+ yield response, new_history
1167
+
1168
+ @torch.inference_mode()
1169
+ def stream_generate(
1170
+ self,
1171
+ input_ids,
1172
+ generation_config: Optional[GenerationConfig] = None,
1173
+ logits_processor: Optional[LogitsProcessorList] = None,
1174
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1175
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1176
+ return_past_key_values=False,
1177
+ **kwargs,
1178
+ ):
1179
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1180
+
1181
+ if generation_config is None:
1182
+ generation_config = self.generation_config
1183
+ generation_config = copy.deepcopy(generation_config)
1184
+ model_kwargs = generation_config.update(**kwargs)
1185
+ model_kwargs["use_cache"] = generation_config.use_cache
1186
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1187
+
1188
+ if isinstance(eos_token_id, int):
1189
+ eos_token_id = [eos_token_id]
1190
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1191
+
1192
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1193
+ if has_default_max_length and generation_config.max_new_tokens is None:
1194
+ warnings.warn(
1195
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1196
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1197
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1198
+ UserWarning,
1199
+ )
1200
+ elif generation_config.max_new_tokens is not None:
1201
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1202
+ if not has_default_max_length:
1203
+ logger.warn(
1204
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1205
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1206
+ "Please refer to the documentation for more information. "
1207
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1208
+ UserWarning,
1209
+ )
1210
+
1211
+ if input_ids_seq_length >= generation_config.max_length:
1212
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1213
+ logger.warning(
1214
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1215
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1216
+ " increasing `max_new_tokens`."
1217
+ )
1218
+
1219
+ # 2. Set generation parameters if not already defined
1220
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1221
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1222
+
1223
+ logits_processor = self._get_logits_processor(
1224
+ generation_config=generation_config,
1225
+ input_ids_seq_length=input_ids_seq_length,
1226
+ encoder_input_ids=input_ids,
1227
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1228
+ logits_processor=logits_processor,
1229
+ )
1230
+
1231
+ stopping_criteria = self._get_stopping_criteria(
1232
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1233
+ )
1234
+ logits_warper = self._get_logits_warper(generation_config)
1235
+
1236
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1237
+ scores = None
1238
+ while True:
1239
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1240
+ # forward pass to get next token
1241
+ outputs = self(
1242
+ **model_inputs,
1243
+ return_dict=True,
1244
+ output_attentions=False,
1245
+ output_hidden_states=False,
1246
+ )
1247
+
1248
+ next_token_logits = outputs.logits[:, -1, :]
1249
+
1250
+ # pre-process distribution
1251
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1252
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1253
+
1254
+ # sample
1255
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1256
+ if generation_config.do_sample:
1257
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1258
+ else:
1259
+ next_tokens = torch.argmax(probs, dim=-1)
1260
+ # update generated ids, model inputs, and length for next step
1261
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1262
+ model_kwargs = self._update_model_kwargs_for_generation(
1263
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1264
+ )
1265
+ unfinished_sequences = unfinished_sequences.mul(
1266
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1267
+ )
1268
+ if return_past_key_values:
1269
+ yield input_ids, outputs.past_key_values
1270
+ else:
1271
+ yield input_ids
1272
+ # stop when each sentence is finished, or if we exceed the maximum length
1273
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1274
+ break
1275
+
1276
+
1277
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1278
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1279
+ super().__init__(config)
1280
+
1281
+ self.num_labels = config.num_labels
1282
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1283
+
1284
+ self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
1285
+ if config.classifier_dropout is not None:
1286
+ self.dropout = nn.Dropout(config.classifier_dropout)
1287
+ else:
1288
+ self.dropout = None
1289
+ self.config = config
1290
+
1291
+ def forward(
1292
+ self,
1293
+ input_ids: Optional[torch.LongTensor] = None,
1294
+ position_ids: Optional[torch.LongTensor] = None,
1295
+ attention_mask: Optional[torch.Tensor] = None,
1296
+ full_attention_mask: Optional[torch.Tensor] = None,
1297
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1298
+ inputs_embeds: Optional[torch.LongTensor] = None,
1299
+ labels: Optional[torch.LongTensor] = None,
1300
+ use_cache: Optional[bool] = None,
1301
+ output_hidden_states: Optional[bool] = None,
1302
+ return_dict: Optional[bool] = None,
1303
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1304
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1305
+
1306
+ transformer_outputs = self.transformer(
1307
+ input_ids=input_ids,
1308
+ position_ids=position_ids,
1309
+ attention_mask=attention_mask,
1310
+ full_attention_mask=full_attention_mask,
1311
+ past_key_values=past_key_values,
1312
+ inputs_embeds=inputs_embeds,
1313
+ use_cache=use_cache,
1314
+ output_hidden_states=output_hidden_states,
1315
+ return_dict=return_dict,
1316
+ )
1317
+
1318
+ hidden_states = transformer_outputs[0]
1319
+ pooled_hidden_states = hidden_states[-1]
1320
+ if self.dropout is not None:
1321
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1322
+ logits = self.classifier_head(pooled_hidden_states)
1323
+
1324
+ loss = None
1325
+ if labels is not None:
1326
+ if self.config.problem_type is None:
1327
+ if self.num_labels == 1:
1328
+ self.config.problem_type = "regression"
1329
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1330
+ self.config.problem_type = "single_label_classification"
1331
+ else:
1332
+ self.config.problem_type = "multi_label_classification"
1333
+
1334
+ if self.config.problem_type == "regression":
1335
+ loss_fct = MSELoss()
1336
+ if self.num_labels == 1:
1337
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1338
+ else:
1339
+ loss = loss_fct(logits.float(), labels)
1340
+ elif self.config.problem_type == "single_label_classification":
1341
+ loss_fct = CrossEntropyLoss()
1342
+ loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
1343
+ elif self.config.problem_type == "multi_label_classification":
1344
+ loss_fct = BCEWithLogitsLoss()
1345
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1346
+
1347
+ if not return_dict:
1348
+ output = (logits,) + transformer_outputs[1:]
1349
+ return ((loss,) + output) if loss is not None else output
1350
+
1351
+ return SequenceClassifierOutputWithPast(
1352
+ loss=loss,
1353
+ logits=logits,
1354
+ past_key_values=transformer_outputs.past_key_values,
1355
+ hidden_states=transformer_outputs.hidden_states,
1356
+ attentions=transformer_outputs.attentions,
1357
+ )
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