Upload 14 files
Browse files- .gitattributes +35 -35
- README.md +75 -0
- config.json +82 -0
- configuration_chatglm.py +66 -0
- generation_config.json +10 -0
- model-00001-of-00002.safetensors +3 -0
- model-00001-of-00002.safetensors.baiduyun.uploading.cfg +0 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_chatglm.py +1358 -0
- tokenization_chatglm.py +361 -0
- tokenizer.model +3 -0
- tokenizer_config.json +134 -0
- visual.py +171 -0
.gitattributes
CHANGED
@@ -1,35 +1,35 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# GLM-4V-9B-4bits
|
2 |
+
|
3 |
+
|
4 |
+
## Quick Start
|
5 |
+
|
6 |
+
```python
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from PIL import Image
|
10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
11 |
+
|
12 |
+
device = "cuda"
|
13 |
+
|
14 |
+
tokenizer = AutoTokenizer.from_pretrained("vcadillo/glm-4v-9b-4-bits", trust_remote_code=True)
|
15 |
+
|
16 |
+
query = 'discribe this image'
|
17 |
+
image = Image.open("your image").convert('RGB')
|
18 |
+
inputs = tokenizer.apply_chat_template([{"role": "user", "image": image, "content": query}],
|
19 |
+
add_generation_prompt=True, tokenize=True, return_tensors="pt",
|
20 |
+
return_dict=True) # chat mode
|
21 |
+
|
22 |
+
inputs = inputs.to(device)
|
23 |
+
model = AutoModelForCausalLM.from_pretrained(
|
24 |
+
"vcadillo/glm-4v-9b-4-bits",
|
25 |
+
torch_dtype=torch.bfloat16,
|
26 |
+
low_cpu_mem_usage=True,
|
27 |
+
trust_remote_code=True,
|
28 |
+
device_map='auto',
|
29 |
+
).eval()
|
30 |
+
|
31 |
+
gen_kwargs = {"max_length": 2500, "do_sample": True, "top_k": 1}
|
32 |
+
with torch.no_grad():
|
33 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
34 |
+
outputs = outputs[:, inputs['input_ids'].shape[1]:]
|
35 |
+
print(tokenizer.decode(outputs[0]))
|
36 |
+
```
|
37 |
+
|
38 |
+
## License
|
39 |
+
|
40 |
+
The use of the GLM-4 model weights needs to comply with the [LICENSE](LICENSE).
|
41 |
+
|
42 |
+
## Citation
|
43 |
+
|
44 |
+
If you find our work helpful, please consider citing the following papers.
|
45 |
+
|
46 |
+
```
|
47 |
+
@article{zeng2022glm,
|
48 |
+
title={Glm-130b: An open bilingual pre-trained model},
|
49 |
+
author={Zeng, Aohan and Liu, Xiao and Du, Zhengxiao and Wang, Zihan and Lai, Hanyu and Ding, Ming and Yang, Zhuoyi and Xu, Yifan and Zheng, Wendi and Xia, Xiao and others},
|
50 |
+
journal={arXiv preprint arXiv:2210.02414},
|
51 |
+
year={2022}
|
52 |
+
}
|
53 |
+
```
|
54 |
+
|
55 |
+
```
|
56 |
+
@inproceedings{du2022glm,
|
57 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
58 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
59 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
60 |
+
pages={320--335},
|
61 |
+
year={2022}
|
62 |
+
}
|
63 |
+
```
|
64 |
+
|
65 |
+
```
|
66 |
+
@misc{wang2023cogvlm,
|
67 |
+
title={CogVLM: Visual Expert for Pretrained Language Models},
|
68 |
+
author={Weihan Wang and Qingsong Lv and Wenmeng Yu and Wenyi Hong and Ji Qi and Yan Wang and Junhui Ji and Zhuoyi Yang and Lei Zhao and Xixuan Song and Jiazheng Xu and Bin Xu and Juanzi Li and Yuxiao Dong and Ming Ding and Jie Tang},
|
69 |
+
year={2023},
|
70 |
+
eprint={2311.03079},
|
71 |
+
archivePrefix={arXiv},
|
72 |
+
primaryClass={cs.CV}
|
73 |
+
}
|
74 |
+
```
|
75 |
+
|
config.json
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "glm-4v-9b-4-bits",
|
3 |
+
"add_bias_linear": false,
|
4 |
+
"add_qkv_bias": true,
|
5 |
+
"apply_query_key_layer_scaling": true,
|
6 |
+
"apply_residual_connection_post_layernorm": false,
|
7 |
+
"architectures": [
|
8 |
+
"ChatGLMForConditionalGeneration"
|
9 |
+
],
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"attention_softmax_in_fp32": true,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
14 |
+
"AutoModel": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForConditionalGeneration",
|
15 |
+
"AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
16 |
+
"AutoModelForSeq2SeqLM": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForConditionalGeneration",
|
17 |
+
"AutoModelForSequenceClassification": "THUDM/glm-4v-9b--modeling_chatglm.ChatGLMForSequenceClassification"
|
18 |
+
},
|
19 |
+
"bias_dropout_fusion": true,
|
20 |
+
"boi_token_id": 151339,
|
21 |
+
"classifier_dropout": null,
|
22 |
+
"eoi_token_id": 151340,
|
23 |
+
"eos_token_id": [
|
24 |
+
151329,
|
25 |
+
151336,
|
26 |
+
151338
|
27 |
+
],
|
28 |
+
"ffn_hidden_size": 13696,
|
29 |
+
"fp32_residual_connection": false,
|
30 |
+
"hidden_dropout": 0.0,
|
31 |
+
"hidden_size": 4096,
|
32 |
+
"kv_channels": 128,
|
33 |
+
"layernorm_epsilon": 1.5625e-07,
|
34 |
+
"model_type": "chatglm",
|
35 |
+
"multi_query_attention": true,
|
36 |
+
"multi_query_group_num": 2,
|
37 |
+
"num_attention_heads": 32,
|
38 |
+
"num_layers": 40,
|
39 |
+
"original_rope": true,
|
40 |
+
"pad_token_id": 151329,
|
41 |
+
"padded_vocab_size": 151552,
|
42 |
+
"post_layer_norm": true,
|
43 |
+
"pre_seq_len": null,
|
44 |
+
"prefix_projection": false,
|
45 |
+
"quantization_config": {
|
46 |
+
"_load_in_4bit": true,
|
47 |
+
"_load_in_8bit": false,
|
48 |
+
"bnb_4bit_compute_dtype": "float16",
|
49 |
+
"bnb_4bit_quant_storage": "uint8",
|
50 |
+
"bnb_4bit_quant_type": "nf4",
|
51 |
+
"bnb_4bit_use_double_quant": false,
|
52 |
+
"llm_int8_enable_fp32_cpu_offload": false,
|
53 |
+
"llm_int8_has_fp16_weight": false,
|
54 |
+
"llm_int8_skip_modules": null,
|
55 |
+
"llm_int8_threshold": 6.0,
|
56 |
+
"load_in_4bit": true,
|
57 |
+
"load_in_8bit": false,
|
58 |
+
"quant_method": "bitsandbytes"
|
59 |
+
},
|
60 |
+
"rmsnorm": true,
|
61 |
+
"rope_ratio": 1,
|
62 |
+
"seq_length": 8192,
|
63 |
+
"tie_word_embeddings": false,
|
64 |
+
"torch_dtype": "float16",
|
65 |
+
"transformers_version": "4.41.2",
|
66 |
+
"use_cache": true,
|
67 |
+
"vision_config": {
|
68 |
+
"dropout_prob": 0.0,
|
69 |
+
"hidden_act": "gelu",
|
70 |
+
"hidden_size": 1792,
|
71 |
+
"image_size": 1120,
|
72 |
+
"in_channels": 3,
|
73 |
+
"intermediate_size": 15360,
|
74 |
+
"layer_norm_eps": 1e-06,
|
75 |
+
"num_heads": 16,
|
76 |
+
"num_hidden_layers": 63,
|
77 |
+
"num_positions": 6401,
|
78 |
+
"patch_size": 14,
|
79 |
+
"scaling_factor": 8
|
80 |
+
},
|
81 |
+
"vocab_size": 151552
|
82 |
+
}
|
configuration_chatglm.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class ChatGLMConfig(PretrainedConfig):
|
5 |
+
model_type = "chatglm"
|
6 |
+
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
num_layers=28,
|
10 |
+
padded_vocab_size=65024,
|
11 |
+
hidden_size=4096,
|
12 |
+
ffn_hidden_size=13696,
|
13 |
+
kv_channels=128,
|
14 |
+
num_attention_heads=32,
|
15 |
+
seq_length=2048,
|
16 |
+
hidden_dropout=0.0,
|
17 |
+
classifier_dropout=None,
|
18 |
+
attention_dropout=0.0,
|
19 |
+
layernorm_epsilon=1e-5,
|
20 |
+
rmsnorm=True,
|
21 |
+
apply_residual_connection_post_layernorm=False,
|
22 |
+
post_layer_norm=True,
|
23 |
+
add_bias_linear=False,
|
24 |
+
add_qkv_bias=False,
|
25 |
+
bias_dropout_fusion=True,
|
26 |
+
multi_query_attention=False,
|
27 |
+
multi_query_group_num=1,
|
28 |
+
rope_ratio=1,
|
29 |
+
apply_query_key_layer_scaling=True,
|
30 |
+
attention_softmax_in_fp32=True,
|
31 |
+
fp32_residual_connection=False,
|
32 |
+
pre_seq_len=None,
|
33 |
+
prefix_projection=False,
|
34 |
+
boi_token_id=None,
|
35 |
+
eoi_token_id=None,
|
36 |
+
**kwargs
|
37 |
+
):
|
38 |
+
self.num_layers = num_layers
|
39 |
+
self.vocab_size = padded_vocab_size
|
40 |
+
self.padded_vocab_size = padded_vocab_size
|
41 |
+
self.hidden_size = hidden_size
|
42 |
+
self.ffn_hidden_size = ffn_hidden_size
|
43 |
+
self.kv_channels = kv_channels
|
44 |
+
self.num_attention_heads = num_attention_heads
|
45 |
+
self.seq_length = seq_length
|
46 |
+
self.hidden_dropout = hidden_dropout
|
47 |
+
self.classifier_dropout = classifier_dropout
|
48 |
+
self.attention_dropout = attention_dropout
|
49 |
+
self.layernorm_epsilon = layernorm_epsilon
|
50 |
+
self.rmsnorm = rmsnorm
|
51 |
+
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
52 |
+
self.post_layer_norm = post_layer_norm
|
53 |
+
self.add_bias_linear = add_bias_linear
|
54 |
+
self.add_qkv_bias = add_qkv_bias
|
55 |
+
self.bias_dropout_fusion = bias_dropout_fusion
|
56 |
+
self.multi_query_attention = multi_query_attention
|
57 |
+
self.multi_query_group_num = multi_query_group_num
|
58 |
+
self.rope_ratio = rope_ratio
|
59 |
+
self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
|
60 |
+
self.attention_softmax_in_fp32 = attention_softmax_in_fp32
|
61 |
+
self.fp32_residual_connection = fp32_residual_connection
|
62 |
+
self.pre_seq_len = pre_seq_len
|
63 |
+
self.prefix_projection = prefix_projection
|
64 |
+
self.boi_token_id = boi_token_id
|
65 |
+
self.eoi_token_id = eoi_token_id
|
66 |
+
super().__init__(**kwargs)
|
generation_config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"eos_token_id": [
|
4 |
+
151329,
|
5 |
+
151336,
|
6 |
+
151338
|
7 |
+
],
|
8 |
+
"pad_token_id": 151329,
|
9 |
+
"transformers_version": "4.41.2"
|
10 |
+
}
|
model-00001-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:09b7aad011b04d5ffacb8023e078e0700f798133f71cbd1743c906df2ac7b2ad
|
3 |
+
size 4996695244
|
model-00001-of-00002.safetensors.baiduyun.uploading.cfg
ADDED
Binary file (451 Bytes). View file
|
|
model-00002-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a4d7c3d9a81915546f1f30451061ad700ac4208412d50d26ea49250119cc0196
|
3 |
+
size 3782170696
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_chatglm.py
ADDED
@@ -0,0 +1,1358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch ChatGLM model. """
|
2 |
+
import json
|
3 |
+
import math
|
4 |
+
import copy
|
5 |
+
import warnings
|
6 |
+
import re
|
7 |
+
import sys
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.utils.checkpoint
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from torch import nn
|
13 |
+
from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
|
14 |
+
from torch.nn.utils import skip_init
|
15 |
+
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
16 |
+
from copy import deepcopy
|
17 |
+
|
18 |
+
from transformers.modeling_outputs import (
|
19 |
+
BaseModelOutputWithPast,
|
20 |
+
CausalLMOutputWithPast,
|
21 |
+
SequenceClassifierOutputWithPast,
|
22 |
+
)
|
23 |
+
from transformers.modeling_utils import PreTrainedModel
|
24 |
+
from transformers.utils import logging
|
25 |
+
from transformers.generation.logits_process import LogitsProcessor
|
26 |
+
from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
|
27 |
+
|
28 |
+
from .configuration_chatglm import ChatGLMConfig
|
29 |
+
from .visual import EVA2CLIPModel
|
30 |
+
|
31 |
+
# flags required to enable jit fusion kernels
|
32 |
+
|
33 |
+
if sys.platform != 'darwin':
|
34 |
+
torch._C._jit_set_profiling_mode(False)
|
35 |
+
torch._C._jit_set_profiling_executor(False)
|
36 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
37 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
LANGUAGE_TOKEN_TYPE = 0
|
42 |
+
VISION_TOKEN_TYPE = 1
|
43 |
+
|
44 |
+
_CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
|
45 |
+
_CONFIG_FOR_DOC = "ChatGLMConfig"
|
46 |
+
|
47 |
+
def default_init(cls, *args, **kwargs):
|
48 |
+
return cls(*args, **kwargs)
|
49 |
+
|
50 |
+
|
51 |
+
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
52 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
53 |
+
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
54 |
+
scores.zero_()
|
55 |
+
scores[..., 198] = 5e4
|
56 |
+
return scores
|
57 |
+
|
58 |
+
|
59 |
+
class PrefixEncoder(torch.nn.Module):
|
60 |
+
"""
|
61 |
+
The torch.nn model to encode the prefix
|
62 |
+
Input shape: (batch-size, prefix-length)
|
63 |
+
Output shape: (batch-size, prefix-length, 2*layers*hidden)
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self, config: ChatGLMConfig):
|
67 |
+
super().__init__()
|
68 |
+
self.prefix_projection = config.prefix_projection
|
69 |
+
if self.prefix_projection:
|
70 |
+
# Use a two-layer MLP to encode the prefix
|
71 |
+
kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
|
72 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
|
73 |
+
self.trans = torch.nn.Sequential(
|
74 |
+
torch.nn.Linear(kv_size, config.hidden_size),
|
75 |
+
torch.nn.Tanh(),
|
76 |
+
torch.nn.Linear(config.hidden_size, kv_size)
|
77 |
+
)
|
78 |
+
else:
|
79 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len,
|
80 |
+
config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
|
81 |
+
|
82 |
+
def forward(self, prefix: torch.Tensor):
|
83 |
+
if self.prefix_projection:
|
84 |
+
prefix_tokens = self.embedding(prefix)
|
85 |
+
past_key_values = self.trans(prefix_tokens)
|
86 |
+
else:
|
87 |
+
past_key_values = self.embedding(prefix)
|
88 |
+
return past_key_values
|
89 |
+
|
90 |
+
|
91 |
+
def split_tensor_along_last_dim(
|
92 |
+
tensor: torch.Tensor,
|
93 |
+
num_partitions: int,
|
94 |
+
contiguous_split_chunks: bool = False,
|
95 |
+
) -> List[torch.Tensor]:
|
96 |
+
"""Split a tensor along its last dimension.
|
97 |
+
|
98 |
+
Arguments:
|
99 |
+
tensor: input tensor.
|
100 |
+
num_partitions: number of partitions to split the tensor
|
101 |
+
contiguous_split_chunks: If True, make each chunk contiguous
|
102 |
+
in memory.
|
103 |
+
|
104 |
+
Returns:
|
105 |
+
A list of Tensors
|
106 |
+
"""
|
107 |
+
# Get the size and dimension.
|
108 |
+
last_dim = tensor.dim() - 1
|
109 |
+
last_dim_size = tensor.size()[last_dim] // num_partitions
|
110 |
+
# Split.
|
111 |
+
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
|
112 |
+
# Note: torch.split does not create contiguous tensors by default.
|
113 |
+
if contiguous_split_chunks:
|
114 |
+
return tuple(chunk.contiguous() for chunk in tensor_list)
|
115 |
+
|
116 |
+
return tensor_list
|
117 |
+
|
118 |
+
|
119 |
+
class RotaryEmbedding(nn.Module):
|
120 |
+
def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
|
121 |
+
super().__init__()
|
122 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
|
123 |
+
self.register_buffer("inv_freq", inv_freq)
|
124 |
+
self.dim = dim
|
125 |
+
self.original_impl = original_impl
|
126 |
+
self.rope_ratio = rope_ratio
|
127 |
+
|
128 |
+
def impl(self, seq_length: int, dim: int, device: torch.device, dtype: torch.dtype):
|
129 |
+
base = 10000 * self.rope_ratio
|
130 |
+
inv_freq = 1.0 / (
|
131 |
+
base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
|
132 |
+
seq = torch.arange(seq_length, device=inv_freq.device, dtype=torch.float32)
|
133 |
+
freqs = torch.outer(seq, inv_freq)
|
134 |
+
# first part even vector components, second part odd vector components,
|
135 |
+
# 2 * dim in dimension size
|
136 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
137 |
+
return emb
|
138 |
+
|
139 |
+
def forward_impl(
|
140 |
+
self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
|
141 |
+
):
|
142 |
+
"""Enhanced Transformer with Rotary Position Embedding.
|
143 |
+
|
144 |
+
Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
|
145 |
+
transformers/rope/__init__.py. MIT License:
|
146 |
+
https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
|
147 |
+
"""
|
148 |
+
# $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
|
149 |
+
base = base * self.rope_ratio
|
150 |
+
theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
|
151 |
+
|
152 |
+
# Create position indexes `[0, 1, ..., seq_len - 1]`
|
153 |
+
seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
|
154 |
+
|
155 |
+
# Calculate the product of position index and $\theta_i$
|
156 |
+
idx_theta = torch.outer(seq_idx, theta).float()
|
157 |
+
|
158 |
+
cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
|
159 |
+
|
160 |
+
# this is to mimic the behaviour of complex32, else we will get different results
|
161 |
+
if dtype in (torch.float16, torch.bfloat16, torch.int8):
|
162 |
+
cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
|
163 |
+
return cache
|
164 |
+
|
165 |
+
def forward(self, max_seq_len, offset=0):
|
166 |
+
if self.original_impl:
|
167 |
+
return self.forward_impl(
|
168 |
+
max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
|
169 |
+
)
|
170 |
+
else:
|
171 |
+
return self.impl(max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device)
|
172 |
+
|
173 |
+
|
174 |
+
@torch.jit.script
|
175 |
+
def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
|
176 |
+
# x: [b, np, sq, hn]
|
177 |
+
b, np, sq, hn = x.size(0), x.size(1), x.size(2), x.size(3)
|
178 |
+
rot_dim = rope_cache.shape[-2] * 2
|
179 |
+
x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
|
180 |
+
# truncate to support variable sizes
|
181 |
+
rope_cache = rope_cache[:, :sq]
|
182 |
+
xshaped = x.reshape(b, np, sq, rot_dim // 2, 2)
|
183 |
+
rope_cache = rope_cache.view(-1, 1, sq, xshaped.size(3), 2)
|
184 |
+
x_out2 = torch.stack(
|
185 |
+
[
|
186 |
+
xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
|
187 |
+
xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
|
188 |
+
],
|
189 |
+
-1,
|
190 |
+
)
|
191 |
+
x_out2 = x_out2.flatten(3)
|
192 |
+
return torch.cat((x_out2, x_pass), dim=-1)
|
193 |
+
|
194 |
+
|
195 |
+
class RMSNorm(torch.nn.Module):
|
196 |
+
def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
|
197 |
+
super().__init__()
|
198 |
+
self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
|
199 |
+
self.eps = eps
|
200 |
+
|
201 |
+
def forward(self, hidden_states: torch.Tensor):
|
202 |
+
input_dtype = hidden_states.dtype
|
203 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
204 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
|
205 |
+
|
206 |
+
return (self.weight * hidden_states).to(input_dtype)
|
207 |
+
|
208 |
+
|
209 |
+
class CoreAttention(torch.nn.Module):
|
210 |
+
def __init__(self, config: ChatGLMConfig, layer_number):
|
211 |
+
super(CoreAttention, self).__init__()
|
212 |
+
|
213 |
+
self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
|
214 |
+
self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
|
215 |
+
if self.apply_query_key_layer_scaling:
|
216 |
+
self.attention_softmax_in_fp32 = True
|
217 |
+
self.layer_number = max(1, layer_number)
|
218 |
+
|
219 |
+
projection_size = config.kv_channels * config.num_attention_heads
|
220 |
+
|
221 |
+
# Per attention head and per partition values.
|
222 |
+
self.hidden_size_per_partition = projection_size
|
223 |
+
self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
|
224 |
+
self.num_attention_heads_per_partition = config.num_attention_heads
|
225 |
+
|
226 |
+
coeff = None
|
227 |
+
self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
|
228 |
+
if self.apply_query_key_layer_scaling:
|
229 |
+
coeff = self.layer_number
|
230 |
+
self.norm_factor *= coeff
|
231 |
+
self.coeff = coeff
|
232 |
+
|
233 |
+
self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
|
234 |
+
|
235 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask):
|
236 |
+
pytorch_major_version = int(torch.__version__.split('.')[0])
|
237 |
+
if pytorch_major_version >= 2:
|
238 |
+
if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
|
239 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
|
240 |
+
is_causal=True)
|
241 |
+
else:
|
242 |
+
if attention_mask is not None:
|
243 |
+
attention_mask = ~attention_mask
|
244 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
|
245 |
+
attention_mask)
|
246 |
+
context_layer = context_layer.transpose(1, 2).contiguous()
|
247 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
|
248 |
+
context_layer = context_layer.reshape(*new_context_layer_shape)
|
249 |
+
else:
|
250 |
+
# Raw attention scores
|
251 |
+
|
252 |
+
# [b, np, sq, sk]
|
253 |
+
output_size = (query_layer.size(0), query_layer.size(1), query_layer.size(2), key_layer.size(2))
|
254 |
+
|
255 |
+
# [b, np, sq, hn] -> [b * np, sq, hn]
|
256 |
+
query_layer = query_layer.view(output_size[0] * output_size[1], output_size[2], -1)
|
257 |
+
# [b, np, sk, hn] -> [b * np, sk, hn]
|
258 |
+
key_layer = key_layer.view(output_size[0] * output_size[1], output_size[3], -1)
|
259 |
+
|
260 |
+
# preallocting input tensor: [b * np, sq, sk]
|
261 |
+
matmul_input_buffer = torch.empty(
|
262 |
+
output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
|
263 |
+
device=query_layer.device
|
264 |
+
)
|
265 |
+
|
266 |
+
# Raw attention scores. [b * np, sq, sk]
|
267 |
+
matmul_result = torch.baddbmm(
|
268 |
+
matmul_input_buffer,
|
269 |
+
query_layer, # [b * np, sq, hn]
|
270 |
+
key_layer.transpose(1, 2), # [b * np, hn, sk]
|
271 |
+
beta=0.0,
|
272 |
+
alpha=(1.0 / self.norm_factor),
|
273 |
+
)
|
274 |
+
|
275 |
+
# change view to [b, np, sq, sk]
|
276 |
+
attention_scores = matmul_result.view(*output_size)
|
277 |
+
|
278 |
+
# ===========================
|
279 |
+
# Attention probs and dropout
|
280 |
+
# ===========================
|
281 |
+
|
282 |
+
# attention scores and attention mask [b, np, sq, sk]
|
283 |
+
if self.attention_softmax_in_fp32:
|
284 |
+
attention_scores = attention_scores.float()
|
285 |
+
if self.coeff is not None:
|
286 |
+
attention_scores = attention_scores * self.coeff
|
287 |
+
if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
|
288 |
+
attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
|
289 |
+
device=attention_scores.device, dtype=torch.bool)
|
290 |
+
attention_mask.tril_()
|
291 |
+
attention_mask = ~attention_mask
|
292 |
+
if attention_mask is not None:
|
293 |
+
attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
|
294 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
295 |
+
attention_probs = attention_probs.type_as(value_layer)
|
296 |
+
|
297 |
+
# This is actually dropping out entire tokens to attend to, which might
|
298 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
299 |
+
attention_probs = self.attention_dropout(attention_probs)
|
300 |
+
# =========================
|
301 |
+
# Context layer. [sq, b, hp]
|
302 |
+
# =========================
|
303 |
+
|
304 |
+
# value_layer -> context layer.
|
305 |
+
# [sk, b, np, hn] --> [b, np, sq, hn]
|
306 |
+
|
307 |
+
# context layer shape: [b, np, sq, hn]
|
308 |
+
output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
|
309 |
+
# change view [b * np, sk, hn]
|
310 |
+
value_layer = value_layer.view(output_size[0] * output_size[1], value_layer.size(2), -1)
|
311 |
+
# change view [b * np, sq, sk]
|
312 |
+
attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
|
313 |
+
# matmul: [b * np, sq, hn]
|
314 |
+
context_layer = torch.bmm(attention_probs, value_layer)
|
315 |
+
# change view [b, np, sq, hn]
|
316 |
+
context_layer = context_layer.view(*output_size)
|
317 |
+
# [b, np, sq, hn] --> [b, sq, np, hn]
|
318 |
+
context_layer = context_layer.transpose(1, 2).contiguous()
|
319 |
+
# [b, sq, np, hn] --> [b, sq, hp]
|
320 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
|
321 |
+
context_layer = context_layer.reshape(*new_context_layer_shape)
|
322 |
+
|
323 |
+
return context_layer
|
324 |
+
|
325 |
+
|
326 |
+
class SelfAttention(torch.nn.Module):
|
327 |
+
"""Parallel self-attention layer abstract class.
|
328 |
+
|
329 |
+
Self-attention layer takes input with size [s, b, h]
|
330 |
+
and returns output of the same size.
|
331 |
+
"""
|
332 |
+
|
333 |
+
def __init__(self, config: ChatGLMConfig, layer_number, device=None):
|
334 |
+
super(SelfAttention, self).__init__()
|
335 |
+
self.layer_number = max(1, layer_number)
|
336 |
+
|
337 |
+
self.projection_size = config.kv_channels * config.num_attention_heads
|
338 |
+
|
339 |
+
# Per attention head and per partition values.
|
340 |
+
self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
|
341 |
+
self.num_attention_heads_per_partition = config.num_attention_heads
|
342 |
+
|
343 |
+
self.multi_query_attention = config.multi_query_attention
|
344 |
+
self.qkv_hidden_size = 3 * self.projection_size
|
345 |
+
self.original_rope = config.original_rope
|
346 |
+
if self.multi_query_attention:
|
347 |
+
self.num_multi_query_groups_per_partition = config.multi_query_group_num
|
348 |
+
self.qkv_hidden_size = (
|
349 |
+
self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
|
350 |
+
)
|
351 |
+
self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
|
352 |
+
bias=config.add_bias_linear or config.add_qkv_bias,
|
353 |
+
device=device, **_config_to_kwargs(config)
|
354 |
+
)
|
355 |
+
|
356 |
+
self.core_attention = CoreAttention(config, self.layer_number)
|
357 |
+
|
358 |
+
# Output.
|
359 |
+
self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
|
360 |
+
device=device, **_config_to_kwargs(config)
|
361 |
+
)
|
362 |
+
|
363 |
+
def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
|
364 |
+
if self.multi_query_attention:
|
365 |
+
num_attention_heads = self.num_multi_query_groups_per_partition
|
366 |
+
else:
|
367 |
+
num_attention_heads = self.num_attention_heads_per_partition
|
368 |
+
return torch.empty(
|
369 |
+
inference_max_sequence_len,
|
370 |
+
batch_size,
|
371 |
+
num_attention_heads,
|
372 |
+
self.hidden_size_per_attention_head,
|
373 |
+
dtype=dtype,
|
374 |
+
device=device,
|
375 |
+
)
|
376 |
+
|
377 |
+
def forward(
|
378 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
|
379 |
+
):
|
380 |
+
# hidden_states: [b, sq, h]
|
381 |
+
|
382 |
+
# =================================================
|
383 |
+
# Pre-allocate memory for key-values for inference.
|
384 |
+
# =================================================
|
385 |
+
# =====================
|
386 |
+
# Query, Key, and Value
|
387 |
+
# =====================
|
388 |
+
|
389 |
+
# Attention heads [b, sq, h] --> [b, sq, (np * 3 * hn)]
|
390 |
+
mixed_x_layer = self.query_key_value(hidden_states)
|
391 |
+
|
392 |
+
if self.multi_query_attention:
|
393 |
+
(query_layer, key_layer, value_layer) = mixed_x_layer.split(
|
394 |
+
[
|
395 |
+
self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
|
396 |
+
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
397 |
+
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
398 |
+
],
|
399 |
+
dim=-1,
|
400 |
+
)
|
401 |
+
query_layer = query_layer.view(
|
402 |
+
query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
|
403 |
+
)
|
404 |
+
key_layer = key_layer.view(
|
405 |
+
key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
|
406 |
+
)
|
407 |
+
value_layer = value_layer.view(
|
408 |
+
value_layer.size()[:-1]
|
409 |
+
+ (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
|
410 |
+
)
|
411 |
+
else:
|
412 |
+
new_tensor_shape = mixed_x_layer.size()[:-1] + \
|
413 |
+
(self.num_attention_heads_per_partition,
|
414 |
+
3 * self.hidden_size_per_attention_head)
|
415 |
+
mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
|
416 |
+
|
417 |
+
# [b, sq, np, 3 * hn] --> 3 [b, sq, np, hn]
|
418 |
+
(query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
|
419 |
+
|
420 |
+
# [b, sq, np, hn] -> [b, np, sq, hn]
|
421 |
+
query_layer, key_layer, value_layer = [k.transpose(1, 2) for k in [query_layer, key_layer, value_layer]]
|
422 |
+
|
423 |
+
# apply relative positional encoding (rotary embedding)
|
424 |
+
if rotary_pos_emb is not None:
|
425 |
+
query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
|
426 |
+
key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
|
427 |
+
|
428 |
+
# adjust key and value for inference
|
429 |
+
if kv_cache is not None:
|
430 |
+
cache_k, cache_v = kv_cache
|
431 |
+
key_layer = torch.cat((cache_k, key_layer), dim=2)
|
432 |
+
value_layer = torch.cat((cache_v, value_layer), dim=2)
|
433 |
+
if use_cache:
|
434 |
+
kv_cache = (key_layer, value_layer)
|
435 |
+
else:
|
436 |
+
kv_cache = None
|
437 |
+
|
438 |
+
if self.multi_query_attention:
|
439 |
+
key_layer = key_layer.unsqueeze(2)
|
440 |
+
key_layer = key_layer.expand(
|
441 |
+
-1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
|
442 |
+
)
|
443 |
+
key_layer = key_layer.contiguous().view(
|
444 |
+
key_layer.size()[:1] + (self.num_attention_heads_per_partition,) + key_layer.size()[3:]
|
445 |
+
)
|
446 |
+
value_layer = value_layer.unsqueeze(2)
|
447 |
+
value_layer = value_layer.expand(
|
448 |
+
-1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
|
449 |
+
)
|
450 |
+
value_layer = value_layer.contiguous().view(
|
451 |
+
value_layer.size()[:1] + (self.num_attention_heads_per_partition,) + value_layer.size()[3:]
|
452 |
+
)
|
453 |
+
|
454 |
+
# ==================================
|
455 |
+
# core attention computation
|
456 |
+
# ==================================
|
457 |
+
|
458 |
+
context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
|
459 |
+
|
460 |
+
# =================
|
461 |
+
# Output. [sq, b, h]
|
462 |
+
# =================
|
463 |
+
|
464 |
+
output = self.dense(context_layer)
|
465 |
+
|
466 |
+
return output, kv_cache
|
467 |
+
|
468 |
+
|
469 |
+
def _config_to_kwargs(args):
|
470 |
+
common_kwargs = {
|
471 |
+
"dtype": args.torch_dtype,
|
472 |
+
}
|
473 |
+
return common_kwargs
|
474 |
+
|
475 |
+
|
476 |
+
class MLP(torch.nn.Module):
|
477 |
+
"""MLP.
|
478 |
+
|
479 |
+
MLP will take the input with h hidden state, project it to 4*h
|
480 |
+
hidden dimension, perform nonlinear transformation, and project the
|
481 |
+
state back into h hidden dimension.
|
482 |
+
"""
|
483 |
+
|
484 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
485 |
+
super(MLP, self).__init__()
|
486 |
+
|
487 |
+
self.add_bias = config.add_bias_linear
|
488 |
+
|
489 |
+
# Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
|
490 |
+
self.dense_h_to_4h = nn.Linear(
|
491 |
+
config.hidden_size,
|
492 |
+
config.ffn_hidden_size * 2,
|
493 |
+
bias=self.add_bias,
|
494 |
+
device=device,
|
495 |
+
**_config_to_kwargs(config)
|
496 |
+
)
|
497 |
+
|
498 |
+
def swiglu(x):
|
499 |
+
x = torch.chunk(x, 2, dim=-1)
|
500 |
+
return F.silu(x[0]) * x[1]
|
501 |
+
|
502 |
+
self.activation_func = swiglu
|
503 |
+
|
504 |
+
# Project back to h.
|
505 |
+
self.dense_4h_to_h = nn.Linear(
|
506 |
+
config.ffn_hidden_size,
|
507 |
+
config.hidden_size,
|
508 |
+
bias=self.add_bias,
|
509 |
+
device=device,
|
510 |
+
**_config_to_kwargs(config)
|
511 |
+
)
|
512 |
+
|
513 |
+
def forward(self, hidden_states):
|
514 |
+
# [s, b, 4hp]
|
515 |
+
intermediate_parallel = self.dense_h_to_4h(hidden_states)
|
516 |
+
intermediate_parallel = self.activation_func(intermediate_parallel)
|
517 |
+
# [s, b, h]
|
518 |
+
output = self.dense_4h_to_h(intermediate_parallel)
|
519 |
+
return output
|
520 |
+
|
521 |
+
|
522 |
+
class GLMBlock(torch.nn.Module):
|
523 |
+
"""A single transformer layer.
|
524 |
+
|
525 |
+
Transformer layer takes input with size [s, b, h] and returns an
|
526 |
+
output of the same size.
|
527 |
+
"""
|
528 |
+
|
529 |
+
def __init__(self, config: ChatGLMConfig, layer_number, device=None):
|
530 |
+
super(GLMBlock, self).__init__()
|
531 |
+
self.layer_number = layer_number
|
532 |
+
|
533 |
+
self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
|
534 |
+
|
535 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
536 |
+
|
537 |
+
LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
|
538 |
+
# Layernorm on the input data.
|
539 |
+
self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
540 |
+
dtype=config.torch_dtype)
|
541 |
+
|
542 |
+
# Self attention.
|
543 |
+
self.self_attention = SelfAttention(config, layer_number, device=device)
|
544 |
+
self.hidden_dropout = config.hidden_dropout
|
545 |
+
|
546 |
+
# Layernorm on the attention output
|
547 |
+
self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
548 |
+
dtype=config.torch_dtype)
|
549 |
+
|
550 |
+
# MLP
|
551 |
+
self.mlp = MLP(config, device=device)
|
552 |
+
|
553 |
+
def forward(
|
554 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
|
555 |
+
):
|
556 |
+
# hidden_states: [s, b, h]
|
557 |
+
|
558 |
+
# Layer norm at the beginning of the transformer layer.
|
559 |
+
layernorm_output = self.input_layernorm(hidden_states)
|
560 |
+
# Self attention.
|
561 |
+
attention_output, kv_cache = self.self_attention(
|
562 |
+
layernorm_output,
|
563 |
+
attention_mask,
|
564 |
+
rotary_pos_emb,
|
565 |
+
kv_cache=kv_cache,
|
566 |
+
use_cache=use_cache
|
567 |
+
)
|
568 |
+
|
569 |
+
# Residual connection.
|
570 |
+
if self.apply_residual_connection_post_layernorm:
|
571 |
+
residual = layernorm_output
|
572 |
+
else:
|
573 |
+
residual = hidden_states
|
574 |
+
|
575 |
+
layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
|
576 |
+
layernorm_input = residual + layernorm_input
|
577 |
+
|
578 |
+
# Layer norm post the self attention.
|
579 |
+
layernorm_output = self.post_attention_layernorm(layernorm_input)
|
580 |
+
|
581 |
+
# MLP.
|
582 |
+
mlp_output = self.mlp(layernorm_output)
|
583 |
+
|
584 |
+
# Second residual connection.
|
585 |
+
if self.apply_residual_connection_post_layernorm:
|
586 |
+
residual = layernorm_output
|
587 |
+
else:
|
588 |
+
residual = layernorm_input
|
589 |
+
|
590 |
+
output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
|
591 |
+
output = residual + output
|
592 |
+
|
593 |
+
return output, kv_cache
|
594 |
+
|
595 |
+
|
596 |
+
class GLMTransformer(torch.nn.Module):
|
597 |
+
"""Transformer class."""
|
598 |
+
|
599 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
600 |
+
super(GLMTransformer, self).__init__()
|
601 |
+
|
602 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
603 |
+
self.post_layer_norm = config.post_layer_norm
|
604 |
+
|
605 |
+
# Number of layers.
|
606 |
+
self.num_layers = config.num_layers
|
607 |
+
|
608 |
+
# Transformer layers.
|
609 |
+
def build_layer(layer_number):
|
610 |
+
return GLMBlock(config, layer_number, device=device)
|
611 |
+
|
612 |
+
self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
|
613 |
+
|
614 |
+
if self.post_layer_norm:
|
615 |
+
LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
|
616 |
+
# Final layer norm before output.
|
617 |
+
self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
618 |
+
dtype=config.torch_dtype)
|
619 |
+
|
620 |
+
self.gradient_checkpointing = False
|
621 |
+
|
622 |
+
def _get_layer(self, layer_number):
|
623 |
+
return self.layers[layer_number]
|
624 |
+
|
625 |
+
def forward(
|
626 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
|
627 |
+
use_cache: Optional[bool] = True,
|
628 |
+
output_hidden_states: Optional[bool] = False,
|
629 |
+
):
|
630 |
+
if not kv_caches:
|
631 |
+
kv_caches = [None for _ in range(self.num_layers)]
|
632 |
+
presents = () if use_cache else None
|
633 |
+
if self.gradient_checkpointing and self.training:
|
634 |
+
if use_cache:
|
635 |
+
logger.warning_once(
|
636 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
637 |
+
)
|
638 |
+
use_cache = False
|
639 |
+
|
640 |
+
all_self_attentions = None
|
641 |
+
all_hidden_states = () if output_hidden_states else None
|
642 |
+
for index in range(self.num_layers):
|
643 |
+
if output_hidden_states:
|
644 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
645 |
+
|
646 |
+
layer = self._get_layer(index)
|
647 |
+
if self.gradient_checkpointing and self.training:
|
648 |
+
layer_ret = torch.utils.checkpoint.checkpoint(
|
649 |
+
layer,
|
650 |
+
hidden_states,
|
651 |
+
attention_mask,
|
652 |
+
rotary_pos_emb,
|
653 |
+
kv_caches[index],
|
654 |
+
use_cache,
|
655 |
+
use_reentrant=False
|
656 |
+
)
|
657 |
+
else:
|
658 |
+
layer_ret = layer(
|
659 |
+
hidden_states,
|
660 |
+
attention_mask,
|
661 |
+
rotary_pos_emb,
|
662 |
+
kv_cache=kv_caches[index],
|
663 |
+
use_cache=use_cache
|
664 |
+
)
|
665 |
+
hidden_states, kv_cache = layer_ret
|
666 |
+
if use_cache:
|
667 |
+
presents = presents + (kv_cache,)
|
668 |
+
|
669 |
+
if output_hidden_states:
|
670 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
671 |
+
|
672 |
+
# Final layer norm.
|
673 |
+
if self.post_layer_norm:
|
674 |
+
hidden_states = self.final_layernorm(hidden_states)
|
675 |
+
|
676 |
+
return hidden_states, presents, all_hidden_states, all_self_attentions
|
677 |
+
|
678 |
+
|
679 |
+
class ChatGLMPreTrainedModel(PreTrainedModel):
|
680 |
+
"""
|
681 |
+
An abstract class to handle weights initialization and
|
682 |
+
a simple interface for downloading and loading pretrained models.
|
683 |
+
"""
|
684 |
+
|
685 |
+
is_parallelizable = False
|
686 |
+
supports_gradient_checkpointing = True
|
687 |
+
config_class = ChatGLMConfig
|
688 |
+
base_model_prefix = "transformer"
|
689 |
+
_no_split_modules = ["GLMBlock"]
|
690 |
+
|
691 |
+
def _init_weights(self, module: nn.Module):
|
692 |
+
"""Initialize the weights."""
|
693 |
+
return
|
694 |
+
|
695 |
+
def get_masks(self, input_ids, past_key_values, padding_mask=None):
|
696 |
+
batch_size, seq_length = input_ids.shape
|
697 |
+
full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
|
698 |
+
full_attention_mask.tril_()
|
699 |
+
past_length = 0
|
700 |
+
if past_key_values:
|
701 |
+
past_length = past_key_values[0][0].shape[2]
|
702 |
+
if past_length:
|
703 |
+
full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
|
704 |
+
device=input_ids.device), full_attention_mask), dim=-1)
|
705 |
+
if padding_mask is not None:
|
706 |
+
full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
|
707 |
+
if not past_length and padding_mask is not None:
|
708 |
+
full_attention_mask -= padding_mask.unsqueeze(-1) - 1
|
709 |
+
full_attention_mask = (full_attention_mask < 0.5).bool()
|
710 |
+
full_attention_mask.unsqueeze_(1)
|
711 |
+
return full_attention_mask
|
712 |
+
|
713 |
+
def get_position_ids(self, input_ids, device):
|
714 |
+
batch_size, seq_length = input_ids.shape
|
715 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
|
716 |
+
return position_ids
|
717 |
+
|
718 |
+
def get_multimodal_position_ids(self, input_ids, device):
|
719 |
+
batch_size, seq_length = input_ids.shape
|
720 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
|
721 |
+
|
722 |
+
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
|
723 |
+
if not self.supports_gradient_checkpointing:
|
724 |
+
raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
|
725 |
+
|
726 |
+
|
727 |
+
class Embedding(torch.nn.Module):
|
728 |
+
"""Language model embeddings."""
|
729 |
+
|
730 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
731 |
+
super(Embedding, self).__init__()
|
732 |
+
|
733 |
+
self.hidden_size = config.hidden_size
|
734 |
+
# Word embeddings (parallel).
|
735 |
+
self.word_embeddings = nn.Embedding(
|
736 |
+
config.padded_vocab_size,
|
737 |
+
self.hidden_size,
|
738 |
+
dtype=config.torch_dtype,
|
739 |
+
device=device
|
740 |
+
)
|
741 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
742 |
+
|
743 |
+
def forward(self, input_ids):
|
744 |
+
# Embeddings.
|
745 |
+
words_embeddings = self.word_embeddings(input_ids)
|
746 |
+
embeddings = words_embeddings
|
747 |
+
# If the input flag for fp32 residual connection is set, convert for float.
|
748 |
+
if self.fp32_residual_connection:
|
749 |
+
embeddings = embeddings.float()
|
750 |
+
return embeddings
|
751 |
+
|
752 |
+
|
753 |
+
def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
|
754 |
+
if images_list is None or len(images_list) == 0:
|
755 |
+
return True
|
756 |
+
for image_list in images_list:
|
757 |
+
if image_list is not None:
|
758 |
+
return False
|
759 |
+
return True
|
760 |
+
|
761 |
+
|
762 |
+
class ChatGLMModel(ChatGLMPreTrainedModel):
|
763 |
+
def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
|
764 |
+
super().__init__(config)
|
765 |
+
if empty_init:
|
766 |
+
init_method = skip_init
|
767 |
+
else:
|
768 |
+
init_method = default_init
|
769 |
+
init_kwargs = {}
|
770 |
+
if device is not None:
|
771 |
+
init_kwargs["device"] = device
|
772 |
+
self.embedding = init_method(Embedding, config, **init_kwargs)
|
773 |
+
self.num_layers = config.num_layers
|
774 |
+
self.multi_query_group_num = config.multi_query_group_num
|
775 |
+
self.kv_channels = config.kv_channels
|
776 |
+
|
777 |
+
# Rotary positional embeddings
|
778 |
+
self.seq_length = config.seq_length
|
779 |
+
rotary_dim = (
|
780 |
+
config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
|
781 |
+
)
|
782 |
+
|
783 |
+
self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio,
|
784 |
+
original_impl=config.original_rope,
|
785 |
+
device=device, dtype=config.torch_dtype)
|
786 |
+
self.encoder = init_method(GLMTransformer, config, **init_kwargs)
|
787 |
+
self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
|
788 |
+
dtype=config.torch_dtype, **init_kwargs)
|
789 |
+
self.pre_seq_len = config.pre_seq_len
|
790 |
+
self.prefix_projection = config.prefix_projection
|
791 |
+
if self.pre_seq_len is not None:
|
792 |
+
for param in self.parameters():
|
793 |
+
param.requires_grad = False
|
794 |
+
self.prefix_tokens = torch.arange(self.pre_seq_len).long()
|
795 |
+
self.prefix_encoder = PrefixEncoder(config)
|
796 |
+
self.dropout = torch.nn.Dropout(0.1)
|
797 |
+
|
798 |
+
self.vision = EVA2CLIPModel(config)
|
799 |
+
|
800 |
+
def get_input_embeddings(self):
|
801 |
+
return self.embedding.word_embeddings
|
802 |
+
|
803 |
+
def set_input_embeddings(self, value):
|
804 |
+
self.embedding.word_embeddings = value
|
805 |
+
|
806 |
+
def get_prompt(self, batch_size, device, dtype=torch.half):
|
807 |
+
prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
|
808 |
+
past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
|
809 |
+
past_key_values = past_key_values.view(
|
810 |
+
batch_size,
|
811 |
+
self.pre_seq_len,
|
812 |
+
self.pre_seq_len,
|
813 |
+
self.num_layers * 2,
|
814 |
+
self.multi_query_group_num,
|
815 |
+
self.kv_channels
|
816 |
+
)
|
817 |
+
# seq_len, b, nh, hidden_size
|
818 |
+
past_key_values = self.dropout(past_key_values)
|
819 |
+
past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
|
820 |
+
return past_key_values
|
821 |
+
|
822 |
+
def forward(
|
823 |
+
self,
|
824 |
+
input_ids: torch.LongTensor = None,
|
825 |
+
images: torch.Tensor = None,
|
826 |
+
position_ids: Optional[torch.Tensor] = None,
|
827 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
828 |
+
full_attention_mask: Optional[torch.BoolTensor] = None,
|
829 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
830 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
831 |
+
use_cache: Optional[bool] = None,
|
832 |
+
output_hidden_states: Optional[bool] = None,
|
833 |
+
return_dict: Optional[bool] = None,
|
834 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
835 |
+
"""take care of image_encode, position_ids and (attention_mask = None is fine)"""
|
836 |
+
|
837 |
+
# generate mode with past_key_values. the image features are already mapped
|
838 |
+
if past_key_values is None:
|
839 |
+
# not allow for inputs_embeds, because we want to process image feature
|
840 |
+
assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
|
841 |
+
if not is_empty(images): # multi-modality
|
842 |
+
image_size: int = self.config.vision_config['image_size']
|
843 |
+
patch_size: int = self.config.vision_config['patch_size']
|
844 |
+
num_patches = (image_size // patch_size // 2) ** 2
|
845 |
+
assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
|
846 |
+
inputs_embeds = self.embedding(input_ids)
|
847 |
+
|
848 |
+
images = images.to(dtype=inputs_embeds.dtype)
|
849 |
+
images_features = self.vision(images)
|
850 |
+
|
851 |
+
if position_ids is None:
|
852 |
+
position_ids = self.get_position_ids(input_ids, device=inputs_embeds.device)
|
853 |
+
new_input_embeds, new_position_ids = [], []
|
854 |
+
|
855 |
+
for i in range(len(input_ids)):
|
856 |
+
input_id = input_ids[i].tolist()
|
857 |
+
boi_token_pos, eoi_token_pos = input_id.index(self.config.boi_token_id), input_id.index(
|
858 |
+
self.config.eoi_token_id)
|
859 |
+
assert eoi_token_pos - boi_token_pos == 2
|
860 |
+
new_input_embeds.append(torch.cat(
|
861 |
+
(inputs_embeds[i, :boi_token_pos], images_features[i].to(inputs_embeds.device), inputs_embeds[i, eoi_token_pos + 1:])))
|
862 |
+
|
863 |
+
new_position_ids.append(torch.cat(
|
864 |
+
(position_ids[i, :boi_token_pos + 1], position_ids[i, boi_token_pos + 1].repeat(num_patches),
|
865 |
+
position_ids[i, eoi_token_pos:])
|
866 |
+
))
|
867 |
+
inputs_embeds = torch.stack(new_input_embeds, dim=0)
|
868 |
+
position_ids = torch.stack(new_position_ids, dim=0)
|
869 |
+
|
870 |
+
output_hidden_states = (
|
871 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
872 |
+
)
|
873 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
874 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
875 |
+
|
876 |
+
batch_size, seq_length = input_ids.shape
|
877 |
+
|
878 |
+
if inputs_embeds is None:
|
879 |
+
inputs_embeds = self.embedding(input_ids)
|
880 |
+
|
881 |
+
if self.pre_seq_len is not None:
|
882 |
+
if past_key_values is None:
|
883 |
+
past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
|
884 |
+
dtype=inputs_embeds.dtype)
|
885 |
+
if attention_mask is not None:
|
886 |
+
attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
|
887 |
+
attention_mask], dim=-1)
|
888 |
+
|
889 |
+
if full_attention_mask is None:
|
890 |
+
if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
|
891 |
+
full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
|
892 |
+
|
893 |
+
# Rotary positional embeddings
|
894 |
+
rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
|
895 |
+
if position_ids is not None:
|
896 |
+
rotary_pos_emb = rotary_pos_emb[position_ids]
|
897 |
+
else:
|
898 |
+
rotary_pos_emb = rotary_pos_emb[None, :seq_length]
|
899 |
+
|
900 |
+
# Run encoder.
|
901 |
+
hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
|
902 |
+
inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
|
903 |
+
kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
|
904 |
+
)
|
905 |
+
|
906 |
+
if not return_dict:
|
907 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
908 |
+
|
909 |
+
return BaseModelOutputWithPast(
|
910 |
+
last_hidden_state=hidden_states,
|
911 |
+
past_key_values=presents,
|
912 |
+
hidden_states=all_hidden_states,
|
913 |
+
attentions=all_self_attentions,
|
914 |
+
)
|
915 |
+
|
916 |
+
|
917 |
+
def _history_to_prompt(history, query):
|
918 |
+
prompt = ''
|
919 |
+
flag = False
|
920 |
+
for i, (old_query, response) in enumerate(history):
|
921 |
+
prompt += ('<|user|>' if flag else '') + old_query + "<|assistant|>" + response + "<|endoftext|>"
|
922 |
+
flag = True
|
923 |
+
prompt += '{}{}<|assistant|>'.format('<|user|>' if flag else '', query)
|
924 |
+
return prompt
|
925 |
+
|
926 |
+
|
927 |
+
class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
928 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
|
929 |
+
super().__init__(config)
|
930 |
+
|
931 |
+
self.max_sequence_length = config.max_length
|
932 |
+
self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
|
933 |
+
self.config = config
|
934 |
+
|
935 |
+
def _update_model_kwargs_for_generation(
|
936 |
+
self,
|
937 |
+
outputs: ModelOutput,
|
938 |
+
model_kwargs: Dict[str, Any],
|
939 |
+
is_encoder_decoder: bool = False,
|
940 |
+
standardize_cache_format: bool = False,
|
941 |
+
) -> Dict[str, Any]:
|
942 |
+
# update past_key_values
|
943 |
+
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
|
944 |
+
outputs, standardize_cache_format=standardize_cache_format
|
945 |
+
)
|
946 |
+
|
947 |
+
# update attention mask
|
948 |
+
if "attention_mask" in model_kwargs:
|
949 |
+
attention_mask = model_kwargs["attention_mask"]
|
950 |
+
model_kwargs["attention_mask"] = torch.cat(
|
951 |
+
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
|
952 |
+
)
|
953 |
+
|
954 |
+
# update position ids
|
955 |
+
if "position_ids" in model_kwargs:
|
956 |
+
position_ids = model_kwargs["position_ids"]
|
957 |
+
new_position_id = position_ids[..., -1:].clone()
|
958 |
+
new_position_id += 1
|
959 |
+
model_kwargs["position_ids"] = torch.cat(
|
960 |
+
[position_ids, new_position_id], dim=-1
|
961 |
+
)
|
962 |
+
|
963 |
+
model_kwargs["is_first_forward"] = False
|
964 |
+
return model_kwargs
|
965 |
+
|
966 |
+
def prepare_inputs_for_generation(
|
967 |
+
self,
|
968 |
+
input_ids: torch.LongTensor,
|
969 |
+
images: Optional[torch.Tensor] = None,
|
970 |
+
past_key_values: Optional[torch.Tensor] = None,
|
971 |
+
attention_mask: Optional[torch.Tensor] = None,
|
972 |
+
position_ids: Optional[torch.Tensor] = None,
|
973 |
+
use_cache: Optional[bool] = None,
|
974 |
+
is_first_forward: bool = True,
|
975 |
+
**kwargs
|
976 |
+
) -> dict:
|
977 |
+
# only last token for input_ids if past is not None
|
978 |
+
if position_ids is None:
|
979 |
+
position_ids = self.get_position_ids(input_ids, device=input_ids.device)
|
980 |
+
if not is_first_forward:
|
981 |
+
if past_key_values is not None:
|
982 |
+
position_ids = position_ids[..., -1:]
|
983 |
+
input_ids = input_ids[:, -1:]
|
984 |
+
return {
|
985 |
+
"input_ids": input_ids,
|
986 |
+
"images": images,
|
987 |
+
"past_key_values": past_key_values,
|
988 |
+
"position_ids": position_ids,
|
989 |
+
"attention_mask": attention_mask,
|
990 |
+
"return_last_logit": True,
|
991 |
+
"use_cache": use_cache
|
992 |
+
}
|
993 |
+
|
994 |
+
def forward(
|
995 |
+
self,
|
996 |
+
input_ids: Optional[torch.Tensor] = None,
|
997 |
+
images: List[List[torch.Tensor]] = None,
|
998 |
+
position_ids: Optional[torch.Tensor] = None,
|
999 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1000 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
1001 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1002 |
+
labels: Optional[torch.Tensor] = None,
|
1003 |
+
use_cache: Optional[bool] = None,
|
1004 |
+
output_attentions: Optional[bool] = None,
|
1005 |
+
output_hidden_states: Optional[bool] = None,
|
1006 |
+
return_dict: Optional[bool] = None,
|
1007 |
+
return_last_logit: Optional[bool] = False,
|
1008 |
+
):
|
1009 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1010 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1011 |
+
|
1012 |
+
transformer_outputs = self.transformer(
|
1013 |
+
input_ids=input_ids,
|
1014 |
+
images=images,
|
1015 |
+
position_ids=position_ids,
|
1016 |
+
attention_mask=attention_mask,
|
1017 |
+
past_key_values=past_key_values,
|
1018 |
+
inputs_embeds=inputs_embeds,
|
1019 |
+
use_cache=use_cache,
|
1020 |
+
output_hidden_states=output_hidden_states,
|
1021 |
+
return_dict=return_dict,
|
1022 |
+
)
|
1023 |
+
|
1024 |
+
hidden_states = transformer_outputs[0]
|
1025 |
+
if return_last_logit:
|
1026 |
+
hidden_states = hidden_states[:, -1:]
|
1027 |
+
lm_logits = self.transformer.output_layer(hidden_states)
|
1028 |
+
|
1029 |
+
loss = None
|
1030 |
+
if labels is not None:
|
1031 |
+
lm_logits = lm_logits.to(torch.float32)
|
1032 |
+
|
1033 |
+
# Shift so that tokens < n predict n
|
1034 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1035 |
+
shift_labels = labels[..., 1:].contiguous()
|
1036 |
+
# Flatten the tokens
|
1037 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
1038 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1039 |
+
|
1040 |
+
lm_logits = lm_logits.to(hidden_states.dtype)
|
1041 |
+
loss = loss.to(hidden_states.dtype)
|
1042 |
+
|
1043 |
+
if not return_dict:
|
1044 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1045 |
+
return ((loss,) + output) if loss is not None else output
|
1046 |
+
|
1047 |
+
return CausalLMOutputWithPast(
|
1048 |
+
loss=loss,
|
1049 |
+
logits=lm_logits,
|
1050 |
+
past_key_values=transformer_outputs.past_key_values,
|
1051 |
+
hidden_states=transformer_outputs.hidden_states,
|
1052 |
+
attentions=transformer_outputs.attentions,
|
1053 |
+
)
|
1054 |
+
|
1055 |
+
@staticmethod
|
1056 |
+
def _reorder_cache(
|
1057 |
+
past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
1058 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
1059 |
+
"""
|
1060 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
1061 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
1062 |
+
beam_idx at every generation step.
|
1063 |
+
|
1064 |
+
Output shares the same memory storage as `past`.
|
1065 |
+
"""
|
1066 |
+
return tuple(
|
1067 |
+
(
|
1068 |
+
layer_past[0].index_select(0, beam_idx.to(layer_past[0].device)),
|
1069 |
+
layer_past[1].index_select(0, beam_idx.to(layer_past[1].device)),
|
1070 |
+
)
|
1071 |
+
for layer_past in past
|
1072 |
+
)
|
1073 |
+
|
1074 |
+
def process_response(self, output, history):
|
1075 |
+
content = ""
|
1076 |
+
history = deepcopy(history)
|
1077 |
+
for response in output.split("<|assistant|>"):
|
1078 |
+
if "\n" in response:
|
1079 |
+
metadata, content = response.split("\n", maxsplit=1)
|
1080 |
+
else:
|
1081 |
+
metadata, content = "", response
|
1082 |
+
if not metadata.strip():
|
1083 |
+
content = content.strip()
|
1084 |
+
history.append({"role": "assistant", "metadata": metadata, "content": content})
|
1085 |
+
content = content.replace("[[训练时间]]", "2023年")
|
1086 |
+
else:
|
1087 |
+
history.append({"role": "assistant", "metadata": metadata, "content": content})
|
1088 |
+
if history[0]["role"] == "system" and "tools" in history[0]:
|
1089 |
+
parameters = json.loads(content)
|
1090 |
+
content = {"name": metadata.strip(), "parameters": parameters}
|
1091 |
+
else:
|
1092 |
+
content = {"name": metadata.strip(), "content": content}
|
1093 |
+
return content, history
|
1094 |
+
|
1095 |
+
@torch.inference_mode()
|
1096 |
+
def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
|
1097 |
+
max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
|
1098 |
+
**kwargs):
|
1099 |
+
if history is None:
|
1100 |
+
history = []
|
1101 |
+
if logits_processor is None:
|
1102 |
+
logits_processor = LogitsProcessorList()
|
1103 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1104 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
|
1105 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1106 |
+
message = {"role": role, "content": query}
|
1107 |
+
if image is not None:
|
1108 |
+
message["image"] = image
|
1109 |
+
history.append(message)
|
1110 |
+
inputs = tokenizer.apply_chat_template(history, add_generation_prompt=True, tokenize=True,
|
1111 |
+
return_tensors="pt", return_dict=True)
|
1112 |
+
inputs = inputs.to(self.device)
|
1113 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
|
1114 |
+
tokenizer.convert_tokens_to_ids("<|observation|>")]
|
1115 |
+
outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
|
1116 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
|
1117 |
+
response = tokenizer.decode(outputs)
|
1118 |
+
response, history = self.process_response(response, history)
|
1119 |
+
return response, history
|
1120 |
+
|
1121 |
+
@torch.inference_mode()
|
1122 |
+
def stream_chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user", image=None,
|
1123 |
+
past_key_values=None, max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
|
1124 |
+
logits_processor=None, return_past_key_values=False, **kwargs):
|
1125 |
+
if history is None:
|
1126 |
+
history = []
|
1127 |
+
if logits_processor is None:
|
1128 |
+
logits_processor = LogitsProcessorList()
|
1129 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1130 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
|
1131 |
+
tokenizer.convert_tokens_to_ids("<|observation|>")]
|
1132 |
+
gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
|
1133 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1134 |
+
message = {"role": role, "content": "query"}
|
1135 |
+
if image is not None:
|
1136 |
+
message["image"] = image
|
1137 |
+
if past_key_values is None:
|
1138 |
+
inputs = tokenizer.apply_chat_template(history + [message],
|
1139 |
+
add_generation_prompt=True, tokenize=True, return_tensors="pt",
|
1140 |
+
return_dict=True)
|
1141 |
+
else:
|
1142 |
+
inputs = tokenizer.apply_chat_template([message], add_special_tokens=False,
|
1143 |
+
add_generation_prompt=True, tokenize=True, return_tensors="pt",
|
1144 |
+
return_dict=True)
|
1145 |
+
inputs = inputs.to(self.device)
|
1146 |
+
if past_key_values is not None:
|
1147 |
+
past_length = past_key_values[0][0].shape[2]
|
1148 |
+
if self.transformer.pre_seq_len is not None:
|
1149 |
+
past_length -= self.transformer.pre_seq_len
|
1150 |
+
inputs.position_ids += past_length
|
1151 |
+
attention_mask = inputs.attention_mask
|
1152 |
+
attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
|
1153 |
+
inputs['attention_mask'] = attention_mask
|
1154 |
+
history.append({"role": role, "content": query})
|
1155 |
+
for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
|
1156 |
+
eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
|
1157 |
+
**gen_kwargs):
|
1158 |
+
if return_past_key_values:
|
1159 |
+
outputs, past_key_values = outputs
|
1160 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
|
1161 |
+
response = tokenizer.decode(outputs)
|
1162 |
+
if response and response[-1] != "�":
|
1163 |
+
response, new_history = self.process_response(response, history)
|
1164 |
+
if return_past_key_values:
|
1165 |
+
yield response, new_history, past_key_values
|
1166 |
+
else:
|
1167 |
+
yield response, new_history
|
1168 |
+
|
1169 |
+
@torch.inference_mode()
|
1170 |
+
def stream_generate(
|
1171 |
+
self,
|
1172 |
+
input_ids,
|
1173 |
+
generation_config: Optional[GenerationConfig] = None,
|
1174 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1175 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
1176 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
1177 |
+
return_past_key_values=False,
|
1178 |
+
**kwargs,
|
1179 |
+
):
|
1180 |
+
batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
|
1181 |
+
|
1182 |
+
if generation_config is None:
|
1183 |
+
generation_config = self.generation_config
|
1184 |
+
generation_config = copy.deepcopy(generation_config)
|
1185 |
+
model_kwargs = generation_config.update(**kwargs)
|
1186 |
+
model_kwargs["use_cache"] = generation_config.use_cache
|
1187 |
+
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1188 |
+
|
1189 |
+
if isinstance(eos_token_id, int):
|
1190 |
+
eos_token_id = [eos_token_id]
|
1191 |
+
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
|
1192 |
+
|
1193 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
1194 |
+
if has_default_max_length and generation_config.max_new_tokens is None:
|
1195 |
+
warnings.warn(
|
1196 |
+
f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
|
1197 |
+
"This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
|
1198 |
+
" recommend using `max_new_tokens` to control the maximum length of the generation.",
|
1199 |
+
UserWarning,
|
1200 |
+
)
|
1201 |
+
elif generation_config.max_new_tokens is not None:
|
1202 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
|
1203 |
+
if not has_default_max_length:
|
1204 |
+
logger.warn(
|
1205 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
1206 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
1207 |
+
"Please refer to the documentation for more information. "
|
1208 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
|
1209 |
+
UserWarning,
|
1210 |
+
)
|
1211 |
+
|
1212 |
+
if input_ids_seq_length >= generation_config.max_length:
|
1213 |
+
input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
|
1214 |
+
logger.warning(
|
1215 |
+
f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
|
1216 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
1217 |
+
" increasing `max_new_tokens`."
|
1218 |
+
)
|
1219 |
+
|
1220 |
+
# 2. Set generation parameters if not already defined
|
1221 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
1222 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
1223 |
+
|
1224 |
+
logits_processor = self._get_logits_processor(
|
1225 |
+
generation_config=generation_config,
|
1226 |
+
input_ids_seq_length=input_ids_seq_length,
|
1227 |
+
encoder_input_ids=input_ids,
|
1228 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
1229 |
+
logits_processor=logits_processor,
|
1230 |
+
)
|
1231 |
+
|
1232 |
+
stopping_criteria = self._get_stopping_criteria(
|
1233 |
+
generation_config=generation_config, stopping_criteria=stopping_criteria
|
1234 |
+
)
|
1235 |
+
logits_warper = self._get_logits_warper(generation_config)
|
1236 |
+
|
1237 |
+
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
|
1238 |
+
scores = None
|
1239 |
+
while True:
|
1240 |
+
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
1241 |
+
# forward pass to get next token
|
1242 |
+
outputs = self(
|
1243 |
+
**model_inputs,
|
1244 |
+
return_dict=True,
|
1245 |
+
output_attentions=False,
|
1246 |
+
output_hidden_states=False,
|
1247 |
+
)
|
1248 |
+
|
1249 |
+
next_token_logits = outputs.logits[:, -1, :]
|
1250 |
+
|
1251 |
+
# pre-process distribution
|
1252 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
1253 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
1254 |
+
|
1255 |
+
# sample
|
1256 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
1257 |
+
if generation_config.do_sample:
|
1258 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
1259 |
+
else:
|
1260 |
+
next_tokens = torch.argmax(probs, dim=-1)
|
1261 |
+
# update generated ids, model inputs, and length for next step
|
1262 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
1263 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
1264 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
1265 |
+
)
|
1266 |
+
unfinished_sequences = unfinished_sequences.mul(
|
1267 |
+
next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
|
1268 |
+
)
|
1269 |
+
if return_past_key_values:
|
1270 |
+
yield input_ids, outputs.past_key_values
|
1271 |
+
else:
|
1272 |
+
yield input_ids
|
1273 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
1274 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
1275 |
+
break
|
1276 |
+
|
1277 |
+
|
1278 |
+
class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
|
1279 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
|
1280 |
+
super().__init__(config)
|
1281 |
+
|
1282 |
+
self.num_labels = config.num_labels
|
1283 |
+
self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
|
1284 |
+
|
1285 |
+
self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
|
1286 |
+
if config.classifier_dropout is not None:
|
1287 |
+
self.dropout = nn.Dropout(config.classifier_dropout)
|
1288 |
+
else:
|
1289 |
+
self.dropout = None
|
1290 |
+
self.config = config
|
1291 |
+
|
1292 |
+
def forward(
|
1293 |
+
self,
|
1294 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1295 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1296 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1297 |
+
full_attention_mask: Optional[torch.Tensor] = None,
|
1298 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1299 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
1300 |
+
labels: Optional[torch.LongTensor] = None,
|
1301 |
+
use_cache: Optional[bool] = None,
|
1302 |
+
output_hidden_states: Optional[bool] = None,
|
1303 |
+
return_dict: Optional[bool] = None,
|
1304 |
+
) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
|
1305 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1306 |
+
|
1307 |
+
transformer_outputs = self.transformer(
|
1308 |
+
input_ids=input_ids,
|
1309 |
+
position_ids=position_ids,
|
1310 |
+
attention_mask=attention_mask,
|
1311 |
+
full_attention_mask=full_attention_mask,
|
1312 |
+
past_key_values=past_key_values,
|
1313 |
+
inputs_embeds=inputs_embeds,
|
1314 |
+
use_cache=use_cache,
|
1315 |
+
output_hidden_states=output_hidden_states,
|
1316 |
+
return_dict=return_dict,
|
1317 |
+
)
|
1318 |
+
|
1319 |
+
hidden_states = transformer_outputs[0]
|
1320 |
+
pooled_hidden_states = hidden_states[-1]
|
1321 |
+
if self.dropout is not None:
|
1322 |
+
pooled_hidden_states = self.dropout(pooled_hidden_states)
|
1323 |
+
logits = self.classifier_head(pooled_hidden_states)
|
1324 |
+
|
1325 |
+
loss = None
|
1326 |
+
if labels is not None:
|
1327 |
+
if self.config.problem_type is None:
|
1328 |
+
if self.num_labels == 1:
|
1329 |
+
self.config.problem_type = "regression"
|
1330 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1331 |
+
self.config.problem_type = "single_label_classification"
|
1332 |
+
else:
|
1333 |
+
self.config.problem_type = "multi_label_classification"
|
1334 |
+
|
1335 |
+
if self.config.problem_type == "regression":
|
1336 |
+
loss_fct = MSELoss()
|
1337 |
+
if self.num_labels == 1:
|
1338 |
+
loss = loss_fct(logits.squeeze().float(), labels.squeeze())
|
1339 |
+
else:
|
1340 |
+
loss = loss_fct(logits.float(), labels)
|
1341 |
+
elif self.config.problem_type == "single_label_classification":
|
1342 |
+
loss_fct = CrossEntropyLoss()
|
1343 |
+
loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
|
1344 |
+
elif self.config.problem_type == "multi_label_classification":
|
1345 |
+
loss_fct = BCEWithLogitsLoss()
|
1346 |
+
loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
|
1347 |
+
|
1348 |
+
if not return_dict:
|
1349 |
+
output = (logits,) + transformer_outputs[1:]
|
1350 |
+
return ((loss,) + output) if loss is not None else output
|
1351 |
+
|
1352 |
+
return SequenceClassifierOutputWithPast(
|
1353 |
+
loss=loss,
|
1354 |
+
logits=logits,
|
1355 |
+
past_key_values=transformer_outputs.past_key_values,
|
1356 |
+
hidden_states=transformer_outputs.hidden_states,
|
1357 |
+
attentions=transformer_outputs.attentions,
|
1358 |
+
)
|
tokenization_chatglm.py
ADDED
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import regex as re
|
2 |
+
import base64
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import tiktoken
|
6 |
+
import torch
|
7 |
+
from torch import TensorType
|
8 |
+
from typing import List, Optional, Union, Dict, Any
|
9 |
+
from torchvision import transforms
|
10 |
+
from transformers import PreTrainedTokenizer
|
11 |
+
from transformers.utils import logging, PaddingStrategy
|
12 |
+
from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
|
13 |
+
|
14 |
+
|
15 |
+
class ChatGLM4Tokenizer(PreTrainedTokenizer):
|
16 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
17 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
18 |
+
|
19 |
+
def __init__(
|
20 |
+
self,
|
21 |
+
vocab_file,
|
22 |
+
padding_side="left",
|
23 |
+
clean_up_tokenization_spaces=False,
|
24 |
+
encode_special_tokens=False,
|
25 |
+
image_size=None,
|
26 |
+
**kwargs
|
27 |
+
):
|
28 |
+
self.name = "GLM4Tokenizer"
|
29 |
+
self.vocab_file = vocab_file
|
30 |
+
pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
|
31 |
+
self.pat_str = re.compile(pat_str)
|
32 |
+
self.encode_special_tokens = encode_special_tokens
|
33 |
+
self.image_size = image_size
|
34 |
+
|
35 |
+
mergeable_ranks = {}
|
36 |
+
with open(vocab_file) as f:
|
37 |
+
for line in f:
|
38 |
+
token, rank = line.strip().split()
|
39 |
+
rank = int(rank)
|
40 |
+
token = base64.b64decode(token)
|
41 |
+
mergeable_ranks[token] = rank
|
42 |
+
|
43 |
+
self.mergeable_ranks = mergeable_ranks
|
44 |
+
|
45 |
+
self.tokenizer = tiktoken.Encoding(
|
46 |
+
name="my_tokenizer",
|
47 |
+
pat_str=pat_str,
|
48 |
+
mergeable_ranks=mergeable_ranks,
|
49 |
+
special_tokens={}
|
50 |
+
)
|
51 |
+
self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
|
52 |
+
self.n_words = len(self.decoder)
|
53 |
+
|
54 |
+
super().__init__(
|
55 |
+
padding_side=padding_side,
|
56 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
57 |
+
**kwargs
|
58 |
+
)
|
59 |
+
|
60 |
+
@property
|
61 |
+
def vocab_size(self):
|
62 |
+
return self.n_words
|
63 |
+
|
64 |
+
def get_vocab(self):
|
65 |
+
""" Returns vocab as a dict """
|
66 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
67 |
+
vocab.update(self.added_tokens_encoder)
|
68 |
+
return vocab
|
69 |
+
|
70 |
+
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
71 |
+
"""
|
72 |
+
Converts a sequence of tokens in a single string.
|
73 |
+
"""
|
74 |
+
text = ""
|
75 |
+
temp = b""
|
76 |
+
for t in tokens:
|
77 |
+
if isinstance(t, str):
|
78 |
+
if temp:
|
79 |
+
text += temp.decode("utf-8", errors="replace")
|
80 |
+
temp = b""
|
81 |
+
text += t
|
82 |
+
elif isinstance(t, bytes):
|
83 |
+
temp += t
|
84 |
+
else:
|
85 |
+
raise TypeError("token should only be of type types or str")
|
86 |
+
if temp:
|
87 |
+
text += temp.decode("utf-8", errors="replace")
|
88 |
+
return text
|
89 |
+
|
90 |
+
def _tokenize(self, text, **kwargs):
|
91 |
+
tokens = []
|
92 |
+
ids = self.tokenizer.encode(text)
|
93 |
+
for t in ids:
|
94 |
+
tokens.append(self.decoder[t])
|
95 |
+
return tokens
|
96 |
+
|
97 |
+
def _convert_token_to_id(self, token):
|
98 |
+
""" Converts a token (str) in an id using the vocab. """
|
99 |
+
return self.mergeable_ranks[token]
|
100 |
+
|
101 |
+
def _convert_id_to_token(self, index):
|
102 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
103 |
+
return self.decoder.get(index, "")
|
104 |
+
|
105 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
106 |
+
"""
|
107 |
+
Save the vocabulary and special tokens file to a directory.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
save_directory (`str`):
|
111 |
+
The directory in which to save the vocabulary.
|
112 |
+
filename_prefix (`str`, *optional*):
|
113 |
+
An optional prefix to add to the named of the saved files.
|
114 |
+
|
115 |
+
Returns:
|
116 |
+
`Tuple(str)`: Paths to the files saved.
|
117 |
+
"""
|
118 |
+
if os.path.isdir(save_directory):
|
119 |
+
vocab_file = os.path.join(
|
120 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
121 |
+
)
|
122 |
+
else:
|
123 |
+
vocab_file = save_directory
|
124 |
+
|
125 |
+
with open(self.vocab_file, 'rb') as fin:
|
126 |
+
proto_str = fin.read()
|
127 |
+
|
128 |
+
with open(vocab_file, "wb") as writer:
|
129 |
+
writer.write(proto_str)
|
130 |
+
|
131 |
+
return (vocab_file,)
|
132 |
+
|
133 |
+
def get_prefix_tokens(self):
|
134 |
+
prefix_tokens = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]
|
135 |
+
return prefix_tokens
|
136 |
+
|
137 |
+
def build_single_message(self, role, metadata, message, tokenize=True, message_prefix=None):
|
138 |
+
assert role in ["system", "user", "assistant", "observation"], role
|
139 |
+
if tokenize:
|
140 |
+
role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",
|
141 |
+
disallowed_special=())
|
142 |
+
message_tokens = self.tokenizer.encode(message, disallowed_special=())
|
143 |
+
if message_prefix is not None:
|
144 |
+
message_tokens = message_prefix + message_tokens
|
145 |
+
tokens = role_tokens + message_tokens
|
146 |
+
return tokens
|
147 |
+
else:
|
148 |
+
return str(f"<|{role}|>{metadata}\n{message}")
|
149 |
+
|
150 |
+
def apply_chat_template(
|
151 |
+
self,
|
152 |
+
conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]], "Conversation"],
|
153 |
+
add_generation_prompt: bool = False,
|
154 |
+
tokenize: bool = True,
|
155 |
+
padding: bool = False,
|
156 |
+
truncation: bool = False,
|
157 |
+
max_length: Optional[int] = None,
|
158 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
159 |
+
return_dict: bool = False,
|
160 |
+
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
|
161 |
+
add_special_tokens: bool = True,
|
162 |
+
**kwargs,
|
163 |
+
) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
|
164 |
+
|
165 |
+
if return_dict and not tokenize:
|
166 |
+
raise ValueError(
|
167 |
+
"`return_dict=True` is incompatible with `tokenize=False`, because there is no dict "
|
168 |
+
"of tokenizer outputs to return."
|
169 |
+
)
|
170 |
+
|
171 |
+
def handle_single_conversation(conversation):
|
172 |
+
input_ids = self.get_prefix_tokens() if add_special_tokens else []
|
173 |
+
input_message = "[gMASK]<sop>" if add_special_tokens else ""
|
174 |
+
input_image = None
|
175 |
+
transform = transforms.Compose(
|
176 |
+
[
|
177 |
+
transforms.Resize(
|
178 |
+
(self.image_size, self.image_size), interpolation=transforms.InterpolationMode.BICUBIC
|
179 |
+
),
|
180 |
+
transforms.ToTensor(),
|
181 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
182 |
+
]
|
183 |
+
)
|
184 |
+
for item in conversation:
|
185 |
+
if item.get("tools"):
|
186 |
+
tools = item["tools"]
|
187 |
+
content = "你是一个名为 GLM-4 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,你的任务是针对用户的问题和要求提供适当的答复和支持。"
|
188 |
+
for tool in tools:
|
189 |
+
if tool["type"] == "function":
|
190 |
+
function = tool["function"]
|
191 |
+
content += f"\n\n## {function['name']}\n\n{json.dumps(function, ensure_ascii=False, indent=4)}"
|
192 |
+
content += "\n在调用上述函数时,请使用 Json 格式表示调用的参数。"
|
193 |
+
elif tool["type"] == "python":
|
194 |
+
content += "\n\n## python\n\n当你向 `python` 发送包含 Python 代码的消息时,该代码将会在一个有状态的 Jupyter notebook 环境中执行。\n`python` 返回代码执行的输出,或在执行 60 秒后返回超时。\n`/mnt/data` 将会持久化存储你的文件。在此会话中,`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用,这些在线内容的访问将不会成功。"
|
195 |
+
elif tool["type"] == "simple_browser":
|
196 |
+
content += "\n\n## simple_browser\n\n你可以使用 `simple_browser` 工具。该工具支持以下函数:\n`search(query: str, recency_days: int)`:使用搜索引擎进行查询并显示结果,可以使用 `recency_days` 参数控制搜索内容的时效性。\n`mclick(ids: list[int])`:获取一系列指定 id 的页面内容。每次调用时,须选择3-10个页面。选择多个角度的页面,同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的,你也可以多打开一些可能有用的页面而不用担心内容过多。\n`open_url(url: str)`:打开指定的 URL。\n\n使用 `【{引用 id}†{引用文本}】` 来引用内容。\n\n操作步骤:1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。\n 如果用户提供了 URL,也可以用 `open_url` 直接打开页面。\n如果初次搜索结果没有找到合适的信息,也可以再次使用 `search` 进行搜索。"
|
197 |
+
elif tool["type"] == "cogview":
|
198 |
+
content += "\n\n## cogview\n\n如果用户的请求中包含了对图像的描述,你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述,规则:\n- 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。\n- 应当尽可能详细地描述图像生成的需求,需求描述约 100 英文单词。\n- 保持用户原始描述的意图。不要虚构内容或者没见过的人物。\n- 如无特殊说明,所在地为中国,持有中国立场并遵循中国社会主义价值观。"
|
199 |
+
else:
|
200 |
+
raise NotImplementedError(f"Unknown tool type {tool['type']}")
|
201 |
+
input = self.build_single_message("system", "", content, tokenize=tokenize)
|
202 |
+
if tokenize:
|
203 |
+
input_ids.extend(input)
|
204 |
+
else:
|
205 |
+
input_message += input
|
206 |
+
message = ""
|
207 |
+
message_prefix = None
|
208 |
+
if item.get("image"):
|
209 |
+
assert input_image is None, "Multiple images are not supported"
|
210 |
+
input_image = transform(item["image"])
|
211 |
+
message_prefix = self.convert_tokens_to_ids(
|
212 |
+
["<|begin_of_image|>", "<|endoftext|>", "<|end_of_image|>"])
|
213 |
+
if item.get("content"):
|
214 |
+
message += item["content"]
|
215 |
+
if message or message_prefix:
|
216 |
+
input = self.build_single_message(
|
217 |
+
item["role"],
|
218 |
+
item.get("metadata", ""),
|
219 |
+
message,
|
220 |
+
tokenize=tokenize,
|
221 |
+
message_prefix=message_prefix
|
222 |
+
)
|
223 |
+
if tokenize:
|
224 |
+
input_ids.extend(input)
|
225 |
+
else:
|
226 |
+
input_message += input
|
227 |
+
if add_generation_prompt:
|
228 |
+
if tokenize:
|
229 |
+
input_ids.extend([self.convert_tokens_to_ids("<|assistant|>")])
|
230 |
+
else:
|
231 |
+
input_message += "<|assistant|>"
|
232 |
+
return {"input": input_ids if tokenize else input_message, "image": input_image}
|
233 |
+
|
234 |
+
# Main logic to handle different conversation formats
|
235 |
+
if isinstance(conversation, list) and all(isinstance(i, dict) for i in conversation):
|
236 |
+
result = handle_single_conversation(conversation)
|
237 |
+
input_ids = result["input"]
|
238 |
+
input_images = [result["image"]]
|
239 |
+
elif isinstance(conversation, list) and all(isinstance(i, list) for i in conversation):
|
240 |
+
results = [handle_single_conversation(c) for c in conversation]
|
241 |
+
input_ids = [item["input"] for item in results]
|
242 |
+
input_images = [item["image"] for item in results]
|
243 |
+
elif hasattr(conversation, "messages"):
|
244 |
+
result = handle_single_conversation(conversation.messages)
|
245 |
+
input_ids = result["input"]
|
246 |
+
input_images = [result["image"]]
|
247 |
+
else:
|
248 |
+
raise ValueError("Invalid conversation format")
|
249 |
+
|
250 |
+
if tokenize:
|
251 |
+
output = self.batch_encode_plus(
|
252 |
+
[input_ids] if isinstance(input_ids[0], int) else input_ids,
|
253 |
+
padding=padding,
|
254 |
+
truncation=truncation,
|
255 |
+
max_length=max_length,
|
256 |
+
return_tensors=return_tensors,
|
257 |
+
is_split_into_words=True,
|
258 |
+
add_special_tokens=False
|
259 |
+
)
|
260 |
+
if return_dict:
|
261 |
+
found_image = False
|
262 |
+
for image in input_images:
|
263 |
+
if image is not None:
|
264 |
+
found_image = True
|
265 |
+
break
|
266 |
+
if found_image:
|
267 |
+
output["images"] = torch.stack(input_images)
|
268 |
+
return output
|
269 |
+
else:
|
270 |
+
return output["input_ids"]
|
271 |
+
else:
|
272 |
+
return input_ids
|
273 |
+
|
274 |
+
|
275 |
+
def build_inputs_with_special_tokens(
|
276 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
277 |
+
) -> List[int]:
|
278 |
+
"""
|
279 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
280 |
+
adding special tokens. A BERT sequence has the following format:
|
281 |
+
|
282 |
+
- single sequence: `[CLS] X [SEP]`
|
283 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
284 |
+
|
285 |
+
Args:
|
286 |
+
token_ids_0 (`List[int]`):
|
287 |
+
List of IDs to which the special tokens will be added.
|
288 |
+
token_ids_1 (`List[int]`, *optional*):
|
289 |
+
Optional second list of IDs for sequence pairs.
|
290 |
+
|
291 |
+
Returns:
|
292 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
293 |
+
"""
|
294 |
+
prefix_tokens = self.get_prefix_tokens()
|
295 |
+
token_ids_0 = prefix_tokens + token_ids_0
|
296 |
+
if token_ids_1 is not None:
|
297 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
|
298 |
+
return token_ids_0
|
299 |
+
|
300 |
+
def _pad(
|
301 |
+
self,
|
302 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
303 |
+
max_length: Optional[int] = None,
|
304 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
305 |
+
pad_to_multiple_of: Optional[int] = None,
|
306 |
+
return_attention_mask: Optional[bool] = None,
|
307 |
+
) -> dict:
|
308 |
+
"""
|
309 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
310 |
+
|
311 |
+
Args:
|
312 |
+
encoded_inputs:
|
313 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
314 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
315 |
+
Will truncate by taking into account the special tokens.
|
316 |
+
padding_strategy: PaddingStrategy to use for padding.
|
317 |
+
|
318 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
319 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
320 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
321 |
+
The tokenizer padding sides are defined in self.padding_side:
|
322 |
+
|
323 |
+
- 'left': pads on the left of the sequences
|
324 |
+
- 'right': pads on the right of the sequences
|
325 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
326 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
327 |
+
`>= 7.5` (Volta).
|
328 |
+
return_attention_mask:
|
329 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
330 |
+
"""
|
331 |
+
# Load from model defaults
|
332 |
+
assert self.padding_side == "left"
|
333 |
+
|
334 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
335 |
+
seq_length = len(required_input)
|
336 |
+
|
337 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
338 |
+
max_length = len(required_input)
|
339 |
+
|
340 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
341 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
342 |
+
|
343 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
344 |
+
|
345 |
+
# Initialize attention mask if not present.
|
346 |
+
if "attention_mask" not in encoded_inputs:
|
347 |
+
encoded_inputs["attention_mask"] = [1] * seq_length
|
348 |
+
|
349 |
+
if "position_ids" not in encoded_inputs:
|
350 |
+
encoded_inputs["position_ids"] = list(range(seq_length))
|
351 |
+
|
352 |
+
if needs_to_be_padded:
|
353 |
+
difference = max_length - len(required_input)
|
354 |
+
|
355 |
+
if "attention_mask" in encoded_inputs:
|
356 |
+
encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
|
357 |
+
if "position_ids" in encoded_inputs:
|
358 |
+
encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
|
359 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
360 |
+
|
361 |
+
return encoded_inputs
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5a493598071550244b2ee7f26118f3edec2150b9dfa967929a99052ac83fe716
|
3 |
+
size 2623634
|
tokenizer_config.json
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_chatglm.ChatGLM4Tokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"added_tokens_decoder": {
|
9 |
+
"151329": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false,
|
15 |
+
"special": true
|
16 |
+
},
|
17 |
+
"151330": {
|
18 |
+
"content": "[MASK]",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false,
|
23 |
+
"special": true
|
24 |
+
},
|
25 |
+
"151331": {
|
26 |
+
"content": "[gMASK]",
|
27 |
+
"lstrip": false,
|
28 |
+
"normalized": false,
|
29 |
+
"rstrip": false,
|
30 |
+
"single_word": false,
|
31 |
+
"special": true
|
32 |
+
},
|
33 |
+
"151332": {
|
34 |
+
"content": "[sMASK]",
|
35 |
+
"lstrip": false,
|
36 |
+
"normalized": false,
|
37 |
+
"rstrip": false,
|
38 |
+
"single_word": false,
|
39 |
+
"special": true
|
40 |
+
},
|
41 |
+
"151333": {
|
42 |
+
"content": "<sop>",
|
43 |
+
"lstrip": false,
|
44 |
+
"normalized": false,
|
45 |
+
"rstrip": false,
|
46 |
+
"single_word": false,
|
47 |
+
"special": true
|
48 |
+
},
|
49 |
+
"151334": {
|
50 |
+
"content": "<eop>",
|
51 |
+
"lstrip": false,
|
52 |
+
"normalized": false,
|
53 |
+
"rstrip": false,
|
54 |
+
"single_word": false,
|
55 |
+
"special": true
|
56 |
+
},
|
57 |
+
"151335": {
|
58 |
+
"content": "<|system|>",
|
59 |
+
"lstrip": false,
|
60 |
+
"normalized": false,
|
61 |
+
"rstrip": false,
|
62 |
+
"single_word": false,
|
63 |
+
"special": true
|
64 |
+
},
|
65 |
+
"151336": {
|
66 |
+
"content": "<|user|>",
|
67 |
+
"lstrip": false,
|
68 |
+
"normalized": false,
|
69 |
+
"rstrip": false,
|
70 |
+
"single_word": false,
|
71 |
+
"special": true
|
72 |
+
},
|
73 |
+
"151337": {
|
74 |
+
"content": "<|assistant|>",
|
75 |
+
"lstrip": false,
|
76 |
+
"normalized": false,
|
77 |
+
"rstrip": false,
|
78 |
+
"single_word": false,
|
79 |
+
"special": true
|
80 |
+
},
|
81 |
+
"151338": {
|
82 |
+
"content": "<|observation|>",
|
83 |
+
"lstrip": false,
|
84 |
+
"normalized": false,
|
85 |
+
"rstrip": false,
|
86 |
+
"single_word": false,
|
87 |
+
"special": true
|
88 |
+
},
|
89 |
+
"151339": {
|
90 |
+
"content": "<|begin_of_image|>",
|
91 |
+
"lstrip": false,
|
92 |
+
"normalized": false,
|
93 |
+
"rstrip": false,
|
94 |
+
"single_word": false,
|
95 |
+
"special": true
|
96 |
+
},
|
97 |
+
"151340": {
|
98 |
+
"content": "<|end_of_image|>",
|
99 |
+
"lstrip": false,
|
100 |
+
"normalized": false,
|
101 |
+
"rstrip": false,
|
102 |
+
"single_word": false,
|
103 |
+
"special": true
|
104 |
+
},
|
105 |
+
"151341": {
|
106 |
+
"content": "<|begin_of_video|>",
|
107 |
+
"lstrip": false,
|
108 |
+
"normalized": false,
|
109 |
+
"rstrip": false,
|
110 |
+
"single_word": false,
|
111 |
+
"special": true
|
112 |
+
},
|
113 |
+
"151342": {
|
114 |
+
"content": "<|end_of_video|>",
|
115 |
+
"lstrip": false,
|
116 |
+
"normalized": false,
|
117 |
+
"rstrip": false,
|
118 |
+
"single_word": false,
|
119 |
+
"special": true
|
120 |
+
}
|
121 |
+
},
|
122 |
+
"additional_special_tokens": ["<|endoftext|>", "[MASK]", "[gMASK]", "[sMASK]", "<sop>", "<eop>", "<|system|>",
|
123 |
+
"<|user|>", "<|assistant|>", "<|observation|>", "<|begin_of_image|>", "<|end_of_image|>",
|
124 |
+
"<|begin_of_video|>", "<|end_of_video|>"],
|
125 |
+
"clean_up_tokenization_spaces": false,
|
126 |
+
"do_lower_case": false,
|
127 |
+
"eos_token": "<|endoftext|>",
|
128 |
+
"pad_token": "<|endoftext|>",
|
129 |
+
"model_max_length": 1000000000000000019884624838656,
|
130 |
+
"padding_side": "left",
|
131 |
+
"remove_space": false,
|
132 |
+
"tokenizer_class": "ChatGLM4Tokenizer",
|
133 |
+
"image_size": 1120
|
134 |
+
}
|
visual.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from argparse import Namespace
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from transformers.activations import ACT2FN
|
6 |
+
import math
|
7 |
+
from torch.nn import LayerNorm
|
8 |
+
|
9 |
+
def standard_attention(query_layer, key_layer, value_layer, scaling_attention_score=True):
|
10 |
+
if scaling_attention_score:
|
11 |
+
query_layer = query_layer / math.sqrt(query_layer.shape[-1])
|
12 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
13 |
+
|
14 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
15 |
+
|
16 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
17 |
+
return context_layer
|
18 |
+
|
19 |
+
def attention_fn_default(query_layer, key_layer, value_layer, scaling_attention_score=True):
|
20 |
+
if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score:
|
21 |
+
# Pytorch 2.0 attention uses very much memory if attention_mask is float, and has NaN bug if attention_mask is None.
|
22 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
23 |
+
query_layer, key_layer, value_layer,
|
24 |
+
attn_mask=None,
|
25 |
+
dropout_p=0.,
|
26 |
+
is_causal=False
|
27 |
+
)
|
28 |
+
return attn_output
|
29 |
+
else:
|
30 |
+
return standard_attention(
|
31 |
+
query_layer, key_layer, value_layer, scaling_attention_score=scaling_attention_score
|
32 |
+
)
|
33 |
+
|
34 |
+
class PatchEmbedding(nn.Module):
|
35 |
+
def __init__(self, config):
|
36 |
+
super().__init__()
|
37 |
+
self.proj = nn.Conv2d(config.in_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size)
|
38 |
+
self.cls_embedding = nn.Parameter(torch.zeros(1, config.hidden_size))
|
39 |
+
self.position_embedding = nn.Embedding(config.num_positions, config.hidden_size)
|
40 |
+
|
41 |
+
def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
|
42 |
+
x = self.proj(images)
|
43 |
+
x = x.flatten(2).transpose(1, 2)
|
44 |
+
cls_token = self.cls_embedding.expand(x.shape[0], -1, -1)
|
45 |
+
x = torch.cat((cls_token, x), dim=1)
|
46 |
+
x += self.position_embedding.weight.unsqueeze(0)
|
47 |
+
return x
|
48 |
+
|
49 |
+
|
50 |
+
class Attention(nn.Module):
|
51 |
+
def __init__(self, config):
|
52 |
+
super().__init__()
|
53 |
+
self.num_heads = config.num_heads
|
54 |
+
head_dim = config.hidden_size // config.num_heads
|
55 |
+
self.scale = head_dim ** -0.5
|
56 |
+
self.query_key_value = nn.Linear(config.hidden_size, config.hidden_size * 3)
|
57 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
58 |
+
self.output_dropout = torch.nn.Dropout(config.dropout_prob)
|
59 |
+
|
60 |
+
def forward(self, x: "tensor(B, L, D)") -> "tensor(B, L, D)":
|
61 |
+
B, L, _ = x.shape
|
62 |
+
qkv = self.query_key_value(x)
|
63 |
+
qkv = qkv.reshape(B, L, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, H, L, D
|
64 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
65 |
+
|
66 |
+
out = attention_fn_default(
|
67 |
+
q, k, v
|
68 |
+
)
|
69 |
+
output = self.dense(out.transpose(1, 2).reshape(B, L, -1))
|
70 |
+
output = self.output_dropout(output)
|
71 |
+
return output
|
72 |
+
|
73 |
+
def attention(self, q, k, v):
|
74 |
+
attn_weights = torch.matmul(q * self.scale, k.transpose(-2, -1))
|
75 |
+
attn_weights = attn_weights.softmax(dim=-1)
|
76 |
+
output = torch.matmul(attn_weights, v)
|
77 |
+
return output
|
78 |
+
|
79 |
+
|
80 |
+
class MLP(nn.Module):
|
81 |
+
def __init__(self, config):
|
82 |
+
super().__init__()
|
83 |
+
self.config = config
|
84 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
85 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
86 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
87 |
+
|
88 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
89 |
+
x = self.fc1(x)
|
90 |
+
x = self.activation_fn(x)
|
91 |
+
x = self.fc2(x)
|
92 |
+
return x
|
93 |
+
|
94 |
+
|
95 |
+
class TransformerLayer(nn.Module):
|
96 |
+
def __init__(self, config):
|
97 |
+
super().__init__()
|
98 |
+
self.input_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
99 |
+
self.attention = Attention(config)
|
100 |
+
self.mlp = MLP(config)
|
101 |
+
self.post_attention_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
102 |
+
|
103 |
+
def forward(self, hidden_states):
|
104 |
+
attention_input = hidden_states
|
105 |
+
attention_output = self.input_layernorm(self.attention(attention_input))
|
106 |
+
hidden_states = attention_input + attention_output
|
107 |
+
mlp_input = hidden_states
|
108 |
+
mlp_output = self.post_attention_layernorm(self.mlp(mlp_input))
|
109 |
+
output = mlp_input + mlp_output
|
110 |
+
return output
|
111 |
+
|
112 |
+
|
113 |
+
class Transformer(nn.Module):
|
114 |
+
def __init__(self, config):
|
115 |
+
super().__init__()
|
116 |
+
self.layers = nn.ModuleList([TransformerLayer(config) for _ in range(config.num_hidden_layers)])
|
117 |
+
|
118 |
+
def forward(self, hidden_states):
|
119 |
+
for layer_module in self.layers:
|
120 |
+
hidden_states = layer_module(hidden_states)
|
121 |
+
return hidden_states
|
122 |
+
|
123 |
+
|
124 |
+
class GLU(nn.Module):
|
125 |
+
def __init__(self, config, in_features):
|
126 |
+
super().__init__()
|
127 |
+
self.linear_proj = nn.Linear(in_features, config.hidden_size, bias=False)
|
128 |
+
self.norm1 = nn.LayerNorm(config.hidden_size)
|
129 |
+
self.act1 = nn.GELU()
|
130 |
+
self.act2 = nn.functional.silu
|
131 |
+
self.dense_h_to_4h = nn.Linear(config.hidden_size, config.ffn_hidden_size, bias=False)
|
132 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.ffn_hidden_size, bias=False)
|
133 |
+
self.dense_4h_to_h = nn.Linear(config.ffn_hidden_size, config.hidden_size, bias=False)
|
134 |
+
|
135 |
+
def forward(self, x):
|
136 |
+
x = self.linear_proj(x)
|
137 |
+
x = self.act1(self.norm1(x))
|
138 |
+
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
|
139 |
+
x = self.dense_4h_to_h(x)
|
140 |
+
return x
|
141 |
+
|
142 |
+
|
143 |
+
class EVA2CLIPModel(nn.Module):
|
144 |
+
def __init__(self, config):
|
145 |
+
super().__init__()
|
146 |
+
vision_config = Namespace(**config.vision_config)
|
147 |
+
self.patch_embedding = PatchEmbedding(vision_config)
|
148 |
+
self.transformer = Transformer(vision_config)
|
149 |
+
self.linear_proj = GLU(config, in_features=config.hidden_size)
|
150 |
+
self.conv = nn.Conv2d(in_channels=vision_config.hidden_size, out_channels=config.hidden_size, kernel_size=2, stride=2)
|
151 |
+
self.boi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
152 |
+
self.eoi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
153 |
+
self.scaling_factor = vision_config.scaling_factor
|
154 |
+
|
155 |
+
def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
|
156 |
+
x = self.patch_embedding(images)
|
157 |
+
x = self.transformer(x)
|
158 |
+
x = x[:, 1:]
|
159 |
+
|
160 |
+
b, s, h = x.shape
|
161 |
+
grid_size = int(s**0.5)
|
162 |
+
x = x.view(b, grid_size, grid_size, h).permute(0, 3, 1, 2)
|
163 |
+
x = self.conv(x)
|
164 |
+
|
165 |
+
x = x.flatten(2).transpose(1, 2)
|
166 |
+
x = self.linear_proj(x)
|
167 |
+
boi = self.boi.expand(x.shape[0], -1, -1)
|
168 |
+
eoi = self.eoi.expand(x.shape[0], -1, -1)
|
169 |
+
x = torch.cat((boi, x, eoi), dim=1)
|
170 |
+
x = x / self.scaling_factor
|
171 |
+
return x
|