4n3mone commited on
Commit
73c6851
1 Parent(s): c13ba48

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