Add files using upload-large-folder tool
Browse files- .gitattributes +3 -0
- .ipynb_checkpoints/Untitled-checkpoint.ipynb +147 -0
- .ipynb_checkpoints/config-checkpoint.json +237 -0
- .ipynb_checkpoints/configuration_qwen2_mla-checkpoint.py +24 -0
- .ipynb_checkpoints/constants-checkpoint.py +12 -0
- .ipynb_checkpoints/conversation-checkpoint.py +592 -0
- .ipynb_checkpoints/mm_utils-checkpoint.py +852 -0
- .ipynb_checkpoints/modeling_qwen2_mla-checkpoint.py +218 -0
- .ipynb_checkpoints/modeling_videochat_flash-checkpoint.py +716 -0
- .ipynb_checkpoints/test-checkpoint.py +43 -0
- .ipynb_checkpoints/tokenizer-checkpoint.json +3 -0
- Untitled.ipynb +208 -0
- __pycache__/configuration_qwen2_mla.cpython-312.pyc +0 -0
- __pycache__/constants.cpython-310.pyc +0 -0
- __pycache__/constants.cpython-312.pyc +0 -0
- __pycache__/conversation.cpython-310.pyc +0 -0
- __pycache__/conversation.cpython-312.pyc +0 -0
- __pycache__/mm_projector_builder.cpython-310.pyc +0 -0
- __pycache__/mm_projector_builder.cpython-312.pyc +0 -0
- __pycache__/mm_utils.cpython-310.pyc +0 -0
- __pycache__/mm_utils.cpython-312.pyc +0 -0
- __pycache__/modeling_qwen2_mla.cpython-312.pyc +0 -0
- __pycache__/modeling_videochat_flash.cpython-310.pyc +0 -0
- __pycache__/modeling_videochat_flash.cpython-312.pyc +0 -0
- __pycache__/vision_tower_builder.cpython-310.pyc +0 -0
- __pycache__/vision_tower_builder.cpython-312.pyc +0 -0
- added_tokens.json +24 -0
- config.json +237 -0
- configuration_qwen2_mla.py +24 -0
- constants.py +12 -0
- conversation.py +592 -0
- generation_config.json +14 -0
- merges.txt +0 -0
- mm_projector_builder.py +165 -0
- mm_utils.py +852 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +625 -0
- modeling_qwen2_mla.py +218 -0
- modeling_videochat_flash.py +716 -0
- special_tokens_map.json +31 -0
- test.mp4 +3 -0
- test.py +43 -0
- tokenizer.json +3 -0
- tokenizer_config.json +209 -0
- vision_tower_builder.py +632 -0
- vocab.json +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* 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
|
|
|
|
|
|
|
|
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
|
36 |
+
test.mp4 filter=lfs diff=lfs merge=lfs -text
|
37 |
+
.ipynb_checkpoints/tokenizer-checkpoint.json filter=lfs diff=lfs merge=lfs -text
|
38 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
.ipynb_checkpoints/Untitled-checkpoint.ipynb
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 7,
|
6 |
+
"id": "64f33f31-f533-41e8-9821-940a5d2ea343",
|
7 |
+
"metadata": {
|
8 |
+
"tags": []
|
9 |
+
},
|
10 |
+
"outputs": [
|
11 |
+
{
|
12 |
+
"name": "stdout",
|
13 |
+
"output_type": "stream",
|
14 |
+
"text": [
|
15 |
+
"Inspecting file: model-00001-of-00004.safetensors\n",
|
16 |
+
"Available keys (tensor names):\n",
|
17 |
+
"\n",
|
18 |
+
"Key: model.layers.0.input_layernorm.weight\n",
|
19 |
+
" Shape: torch.Size([3584])\n",
|
20 |
+
" Dtype: torch.bfloat16\n",
|
21 |
+
" Size: 3584 elements\n",
|
22 |
+
" First few elements: [0.275390625, 0.3046875, 0.26171875, 0.291015625, 0.29296875]\n",
|
23 |
+
"\n",
|
24 |
+
"Key: model.layers.0.mlp.down_proj.weight\n",
|
25 |
+
" Shape: torch.Size([3584, 18944])\n",
|
26 |
+
" Dtype: torch.bfloat16\n",
|
27 |
+
" Size: 67895296 elements\n",
|
28 |
+
" First few elements: [-0.005096435546875, 0.01385498046875, 0.0096435546875, -0.00848388671875, -0.002593994140625]\n",
|
29 |
+
"\n",
|
30 |
+
"Key: model.layers.0.mlp.gate_proj.weight\n",
|
31 |
+
" Shape: torch.Size([18944, 3584])\n",
|
32 |
+
" Dtype: torch.bfloat16\n",
|
33 |
+
" Size: 67895296 elements\n",
|
34 |
+
" First few elements: [0.00286865234375, -0.0201416015625, -0.0216064453125, 0.006622314453125, -0.015625]\n",
|
35 |
+
"\n",
|
36 |
+
"Key: model.layers.0.mlp.up_proj.weight\n",
|
37 |
+
" Shape: torch.Size([18944, 3584])\n",
|
38 |
+
" Dtype: torch.bfloat16\n",
|
39 |
+
" Size: 67895296 elements\n",
|
40 |
+
" First few elements: [0.007537841796875, -0.0111083984375, -0.0024261474609375, -0.006927490234375, -0.02587890625]\n",
|
41 |
+
"\n",
|
42 |
+
"Key: model.layers.0.post_attention_layernorm.weight\n",
|
43 |
+
" Shape: torch.Size([3584])\n",
|
44 |
+
" Dtype: torch.bfloat16\n",
|
45 |
+
" Size: 3584 elements\n",
|
46 |
+
" First few elements: [0.28515625, 0.33203125, 0.259765625, 0.236328125, 0.296875]\n",
|
47 |
+
"\n",
|
48 |
+
"Key: model.layers.0.self_attn.kv_a_proj_with_mqa.bias\n",
|
49 |
+
" Shape: torch.Size([576])\n",
|
50 |
+
" Dtype: torch.bfloat16\n",
|
51 |
+
" Size: 576 elements\n",
|
52 |
+
" First few elements: [3.953125, 0.0634765625, 1.2578125, -1.515625, 0.29296875]\n",
|
53 |
+
"\n",
|
54 |
+
"Key: model.layers.0.self_attn.kv_a_proj_with_mqa.weight\n",
|
55 |
+
" Shape: torch.Size([576, 3584])\n",
|
56 |
+
" Dtype: torch.bfloat16\n",
|
57 |
+
" Size: 2064384 elements\n",
|
58 |
+
" First few elements: [0.0322265625, -0.005157470703125, -0.03173828125, 0.0184326171875, -0.015625]\n",
|
59 |
+
"\n",
|
60 |
+
"Key: model.layers.0.self_attn.kv_b_proj.weight\n",
|
61 |
+
" Shape: torch.Size([7168, 512])\n",
|
62 |
+
" Dtype: torch.bfloat16\n",
|
63 |
+
" Size: 3670016 elements\n",
|
64 |
+
" First few elements: [-0.04931640625, -0.01904296875, 0.080078125, -0.01324462890625, 0.0179443359375]\n",
|
65 |
+
"\n",
|
66 |
+
"Key: model.layers.0.self_attn.o_proj.weight\n",
|
67 |
+
" Shape: torch.Size([3584, 3584])\n",
|
68 |
+
" Dtype: torch.bfloat16\n",
|
69 |
+
" Size: 12845056 elements\n",
|
70 |
+
" First few elements: [0.00323486328125, -0.030029296875, -0.0069580078125, 0.0089111328125, 0.007568359375]\n",
|
71 |
+
"\n",
|
72 |
+
"Key: model.layers.0.self_attn.q_proj.bias\n",
|
73 |
+
" Shape: torch.Size([5376])\n",
|
74 |
+
" Dtype: torch.bfloat16\n",
|
75 |
+
" Size: 5376 elements\n",
|
76 |
+
" First few elements: [0.5, 2.140625, -0.98046875, 1.3671875, 1.015625]\n",
|
77 |
+
"\n",
|
78 |
+
"Key: model.layers.0.self_attn.q_proj.weight\n",
|
79 |
+
" Shape: torch.Size([5376, 3584])\n",
|
80 |
+
" Dtype: torch.bfloat16\n",
|
81 |
+
" Size: 19267584 elements\n",
|
82 |
+
" First few elements: [-0.0003452301025390625, -0.005340576171875, 0.021484375, 0.003997802734375, -0.00274658203125]\n"
|
83 |
+
]
|
84 |
+
}
|
85 |
+
],
|
86 |
+
"source": [
|
87 |
+
"from safetensors import safe_open\n",
|
88 |
+
"\n",
|
89 |
+
"def inspect_safetensors(file_path):\n",
|
90 |
+
" print(f\"Inspecting file: {file_path}\")\n",
|
91 |
+
" with safe_open(file_path, framework=\"pt\", device=\"cpu\") as f:\n",
|
92 |
+
" print(\"Available keys (tensor names):\")\n",
|
93 |
+
" for key in f.keys():\n",
|
94 |
+
" if 'model.layers.0' in key:\n",
|
95 |
+
" \n",
|
96 |
+
" tensor = f.get_tensor(key)\n",
|
97 |
+
" print(f\"\\nKey: {key}\")\n",
|
98 |
+
" print(f\" Shape: {tensor.shape}\")\n",
|
99 |
+
" print(f\" Dtype: {tensor.dtype}\")\n",
|
100 |
+
" print(f\" Size: {tensor.numel()} elements\")\n",
|
101 |
+
" # 可选:显示前几个元素\n",
|
102 |
+
" print(f\" First few elements: {tensor.flatten()[:5].tolist()}\")\n",
|
103 |
+
"\n",
|
104 |
+
"# 示例路径,请替换为你自己的 .safetensors 文件路径\n",
|
105 |
+
"file_path = \"model-00001-of-00004.safetensors\"\n",
|
106 |
+
"inspect_safetensors(file_path)"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
{
|
110 |
+
"cell_type": "code",
|
111 |
+
"execution_count": null,
|
112 |
+
"id": "2a331ae6-f4ca-4d16-8bbf-36f39b9ac43e",
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [],
|
115 |
+
"source": []
|
116 |
+
},
|
117 |
+
{
|
118 |
+
"cell_type": "code",
|
119 |
+
"execution_count": null,
|
120 |
+
"id": "8bfd7429-5d77-42ad-8e3f-9cf37b25dfc7",
|
121 |
+
"metadata": {},
|
122 |
+
"outputs": [],
|
123 |
+
"source": []
|
124 |
+
}
|
125 |
+
],
|
126 |
+
"metadata": {
|
127 |
+
"kernelspec": {
|
128 |
+
"display_name": "vcflash",
|
129 |
+
"language": "python",
|
130 |
+
"name": "vcflash"
|
131 |
+
},
|
132 |
+
"language_info": {
|
133 |
+
"codemirror_mode": {
|
134 |
+
"name": "ipython",
|
135 |
+
"version": 3
|
136 |
+
},
|
137 |
+
"file_extension": ".py",
|
138 |
+
"mimetype": "text/x-python",
|
139 |
+
"name": "python",
|
140 |
+
"nbconvert_exporter": "python",
|
141 |
+
"pygments_lexer": "ipython3",
|
142 |
+
"version": "3.10.14"
|
143 |
+
}
|
144 |
+
},
|
145 |
+
"nbformat": 4,
|
146 |
+
"nbformat_minor": 5
|
147 |
+
}
|
.ipynb_checkpoints/config-checkpoint.json
ADDED
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"VideoChatFlashQwenForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "modeling_videochat_flash.VideoChatFlashQwenConfig",
|
8 |
+
"AutoModel": "modeling_videochat_flash.VideoChatFlashQwenForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 151643,
|
11 |
+
"dual_chunk_attention_config": {
|
12 |
+
"chunk_size": 262144,
|
13 |
+
"local_size": 8192,
|
14 |
+
"original_max_position_embeddings": 262144
|
15 |
+
},
|
16 |
+
"eos_token_id": 151645,
|
17 |
+
"frame_aspect_ratio": "square",
|
18 |
+
"frame_grid_pinpoints": null,
|
19 |
+
"head_dim": 64,
|
20 |
+
"hidden_act": "silu",
|
21 |
+
"hidden_size": 3584,
|
22 |
+
"image_aspect_ratio": "anyres_nopad",
|
23 |
+
"image_crop_resolution": null,
|
24 |
+
"image_grid_pinpoints": [
|
25 |
+
[
|
26 |
+
224,
|
27 |
+
224
|
28 |
+
],
|
29 |
+
[
|
30 |
+
224,
|
31 |
+
448
|
32 |
+
],
|
33 |
+
[
|
34 |
+
224,
|
35 |
+
672
|
36 |
+
],
|
37 |
+
[
|
38 |
+
224,
|
39 |
+
896
|
40 |
+
],
|
41 |
+
[
|
42 |
+
224,
|
43 |
+
1120
|
44 |
+
],
|
45 |
+
[
|
46 |
+
224,
|
47 |
+
1344
|
48 |
+
],
|
49 |
+
[
|
50 |
+
448,
|
51 |
+
224
|
52 |
+
],
|
53 |
+
[
|
54 |
+
448,
|
55 |
+
448
|
56 |
+
],
|
57 |
+
[
|
58 |
+
448,
|
59 |
+
672
|
60 |
+
],
|
61 |
+
[
|
62 |
+
448,
|
63 |
+
896
|
64 |
+
],
|
65 |
+
[
|
66 |
+
448,
|
67 |
+
1120
|
68 |
+
],
|
69 |
+
[
|
70 |
+
448,
|
71 |
+
1344
|
72 |
+
],
|
73 |
+
[
|
74 |
+
672,
|
75 |
+
224
|
76 |
+
],
|
77 |
+
[
|
78 |
+
672,
|
79 |
+
448
|
80 |
+
],
|
81 |
+
[
|
82 |
+
672,
|
83 |
+
672
|
84 |
+
],
|
85 |
+
[
|
86 |
+
672,
|
87 |
+
896
|
88 |
+
],
|
89 |
+
[
|
90 |
+
672,
|
91 |
+
1120
|
92 |
+
],
|
93 |
+
[
|
94 |
+
672,
|
95 |
+
1344
|
96 |
+
],
|
97 |
+
[
|
98 |
+
896,
|
99 |
+
224
|
100 |
+
],
|
101 |
+
[
|
102 |
+
896,
|
103 |
+
448
|
104 |
+
],
|
105 |
+
[
|
106 |
+
896,
|
107 |
+
672
|
108 |
+
],
|
109 |
+
[
|
110 |
+
896,
|
111 |
+
896
|
112 |
+
],
|
113 |
+
[
|
114 |
+
896,
|
115 |
+
1120
|
116 |
+
],
|
117 |
+
[
|
118 |
+
896,
|
119 |
+
1344
|
120 |
+
],
|
121 |
+
[
|
122 |
+
1120,
|
123 |
+
224
|
124 |
+
],
|
125 |
+
[
|
126 |
+
1120,
|
127 |
+
448
|
128 |
+
],
|
129 |
+
[
|
130 |
+
1120,
|
131 |
+
672
|
132 |
+
],
|
133 |
+
[
|
134 |
+
1120,
|
135 |
+
896
|
136 |
+
],
|
137 |
+
[
|
138 |
+
1120,
|
139 |
+
1120
|
140 |
+
],
|
141 |
+
[
|
142 |
+
1120,
|
143 |
+
1344
|
144 |
+
],
|
145 |
+
[
|
146 |
+
1344,
|
147 |
+
224
|
148 |
+
],
|
149 |
+
[
|
150 |
+
1344,
|
151 |
+
448
|
152 |
+
],
|
153 |
+
[
|
154 |
+
1344,
|
155 |
+
672
|
156 |
+
],
|
157 |
+
[
|
158 |
+
1344,
|
159 |
+
896
|
160 |
+
],
|
161 |
+
[
|
162 |
+
1344,
|
163 |
+
1120
|
164 |
+
],
|
165 |
+
[
|
166 |
+
1344,
|
167 |
+
1344
|
168 |
+
]
|
169 |
+
],
|
170 |
+
"image_split_resolution": null,
|
171 |
+
"initializer_range": 0.02,
|
172 |
+
"intermediate_size": 18944,
|
173 |
+
"llm_compress_layer_list": [
|
174 |
+
8,
|
175 |
+
16,
|
176 |
+
24
|
177 |
+
],
|
178 |
+
"llm_compress_type": "attention",
|
179 |
+
"llm_image_token_ratio_list": [
|
180 |
+
1.0,
|
181 |
+
0.5,
|
182 |
+
0.25,
|
183 |
+
0.125
|
184 |
+
],
|
185 |
+
"max_num_pixels": 14745600000,
|
186 |
+
"max_position_embeddings": 32000,
|
187 |
+
"max_window_layers": 28,
|
188 |
+
"min_slow_num_frames": 4,
|
189 |
+
"mm_close_init": false,
|
190 |
+
"mm_hidden_size": 1024,
|
191 |
+
"mm_llm_compress": false,
|
192 |
+
"mm_local_num_frames": 4,
|
193 |
+
"mm_newline_position": "nothing",
|
194 |
+
"mm_num_compress_latents": 128,
|
195 |
+
"mm_num_compress_query_type": "learnable",
|
196 |
+
"mm_patch_merge_type": "spatial_nopad",
|
197 |
+
"mm_pos_num_frames": 8,
|
198 |
+
"mm_projector_lr": null,
|
199 |
+
"mm_projector_type": "tome16_mlp_hd64",
|
200 |
+
"mm_resampler_type": null,
|
201 |
+
"mm_spatial_pool_mode": "bilinear",
|
202 |
+
"mm_tunable_parts": "mm_vision_tower,mm_mlp_adapter,mm_language_model",
|
203 |
+
"mm_use_im_patch_token": false,
|
204 |
+
"mm_use_im_start_end": false,
|
205 |
+
"mm_vision_select_feature": "patch",
|
206 |
+
"mm_vision_select_layer": -2,
|
207 |
+
"mm_vision_tower": "umt-large",
|
208 |
+
"mm_vision_tower_lr": 2e-06,
|
209 |
+
"model_type": "videochat_flash_qwen",
|
210 |
+
"num_attention_heads": 28,
|
211 |
+
"num_hidden_layers": 28,
|
212 |
+
"num_key_value_heads": 28,
|
213 |
+
"pos_skipping_range": 4096,
|
214 |
+
"rms_norm_eps": 1e-05,
|
215 |
+
"rope_scaling": null,
|
216 |
+
"rope_theta": 10000000.0,
|
217 |
+
"sliding_window": 32768,
|
218 |
+
"tie_word_embeddings": false,
|
219 |
+
"tokenizer_model_max_length": 32768,
|
220 |
+
"tokenizer_padding_side": "right",
|
221 |
+
"torch_dtype": "bfloat16",
|
222 |
+
"transformers_version": "4.51.3",
|
223 |
+
"use_cache": true,
|
224 |
+
"use_mm_proj": true,
|
225 |
+
"use_pos_skipping": false,
|
226 |
+
"use_sliding_window": false,
|
227 |
+
"vision_encode_type": "video_image",
|
228 |
+
"vision_tower_pretrained": null,
|
229 |
+
"vocab_size": 152064,
|
230 |
+
"attention_bias": true,
|
231 |
+
"qk_rope_head_dim": 64,
|
232 |
+
"qk_nope_head_dim": 128,
|
233 |
+
"v_head_dim": 128,
|
234 |
+
"q_lora_rank": null,
|
235 |
+
"kv_lora_rank": 512,
|
236 |
+
"qk_latent_layernorm": false
|
237 |
+
}
|
.ipynb_checkpoints/configuration_qwen2_mla-checkpoint.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
|
2 |
+
|
3 |
+
class Qwen2MLAConfig(Qwen2Config):
|
4 |
+
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
*args,
|
8 |
+
kv_lora_rank=512,
|
9 |
+
q_lora_rank=None,
|
10 |
+
qk_rope_head_dim=64,
|
11 |
+
qk_nope_head_dim=128,
|
12 |
+
v_head_dim=128,
|
13 |
+
qk_latent_layernorm=True,
|
14 |
+
**kwargs
|
15 |
+
):
|
16 |
+
super().__init__(*args, **kwargs)
|
17 |
+
|
18 |
+
self.kv_lora_rank = kv_lora_rank
|
19 |
+
self.q_lora_rank = q_lora_rank
|
20 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
21 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
22 |
+
self.qk_head_dim = qk_rope_head_dim + qk_nope_head_dim
|
23 |
+
self.v_head_dim = v_head_dim
|
24 |
+
self.qk_latent_layernorm = qk_latent_layernorm
|
.ipynb_checkpoints/constants-checkpoint.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
5 |
+
|
6 |
+
# Model Constants
|
7 |
+
IGNORE_INDEX = -100
|
8 |
+
IMAGE_TOKEN_INDEX = -200
|
9 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
10 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
11 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
12 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
.ipynb_checkpoints/conversation-checkpoint.py
ADDED
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import auto, Enum
|
3 |
+
from typing import List, Any, Dict, Union, Tuple
|
4 |
+
import re
|
5 |
+
import base64
|
6 |
+
from io import BytesIO
|
7 |
+
from PIL import Image
|
8 |
+
from transformers import AutoTokenizer
|
9 |
+
|
10 |
+
|
11 |
+
class SeparatorStyle(Enum):
|
12 |
+
"""Different separator style."""
|
13 |
+
|
14 |
+
SINGLE = auto()
|
15 |
+
TWO = auto()
|
16 |
+
MPT = auto()
|
17 |
+
PLAIN = auto()
|
18 |
+
CHATML = auto()
|
19 |
+
LLAMA_2 = auto()
|
20 |
+
LLAMA_3 = auto()
|
21 |
+
QWEN = auto()
|
22 |
+
GEMMA = auto()
|
23 |
+
|
24 |
+
|
25 |
+
@dataclasses.dataclass
|
26 |
+
class Conversation:
|
27 |
+
"""A class that keeps all conversation history."""
|
28 |
+
|
29 |
+
system: str
|
30 |
+
roles: List[str]
|
31 |
+
messages: List[List[str]]
|
32 |
+
offset: int
|
33 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
34 |
+
sep: str = "###"
|
35 |
+
sep2: str = None
|
36 |
+
version: str = "Unknown"
|
37 |
+
|
38 |
+
tokenizer_id: str = ""
|
39 |
+
tokenizer: Any = None
|
40 |
+
# Stop criteria (the default one is EOS token)
|
41 |
+
stop_str: Union[str, List[str]] = None
|
42 |
+
# Stops generation if meeting any token in this list
|
43 |
+
stop_token_ids: List[int] = None
|
44 |
+
|
45 |
+
skip_next: bool = False
|
46 |
+
|
47 |
+
def get_prompt(self):
|
48 |
+
messages = self.messages
|
49 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
50 |
+
messages = self.messages.copy()
|
51 |
+
init_role, init_msg = messages[0].copy()
|
52 |
+
init_msg = init_msg[0]
|
53 |
+
if "mmtag" in self.version:
|
54 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
55 |
+
messages[0] = (init_role, init_msg)
|
56 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
57 |
+
messages.insert(1, (self.roles[1], "Received."))
|
58 |
+
elif not init_msg.startswith("<image>"):
|
59 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
60 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
61 |
+
else:
|
62 |
+
messages[0] = (init_role, init_msg)
|
63 |
+
|
64 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
65 |
+
ret = self.system + self.sep
|
66 |
+
for role, message in messages:
|
67 |
+
if message:
|
68 |
+
if type(message) is tuple:
|
69 |
+
message, _, _ = message
|
70 |
+
ret += role + ": " + message + self.sep
|
71 |
+
else:
|
72 |
+
ret += role + ":"
|
73 |
+
|
74 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
75 |
+
seps = [self.sep, self.sep2]
|
76 |
+
ret = self.system + seps[0]
|
77 |
+
for i, (role, message) in enumerate(messages):
|
78 |
+
if message:
|
79 |
+
if type(message) is tuple:
|
80 |
+
message, _, _ = message
|
81 |
+
ret += role + ": " + message + seps[i % 2]
|
82 |
+
else:
|
83 |
+
ret += role + ":"
|
84 |
+
|
85 |
+
elif self.sep_style == SeparatorStyle.CHATML:
|
86 |
+
ret = "" if self.system == "" else self.system + self.sep + "\n"
|
87 |
+
for role, message in messages:
|
88 |
+
if message:
|
89 |
+
if type(message) is tuple:
|
90 |
+
message, images, _ = message
|
91 |
+
message = "<image>" * len(images) + message
|
92 |
+
ret += role + "\n" + message + self.sep + "\n"
|
93 |
+
else:
|
94 |
+
ret += role + "\n"
|
95 |
+
return ret
|
96 |
+
|
97 |
+
elif self.sep_style == SeparatorStyle.LLAMA_3:
|
98 |
+
chat_template_messages = [{"role": "system", "content": self.system}]
|
99 |
+
for role, message in messages:
|
100 |
+
if message:
|
101 |
+
if type(message) is tuple:
|
102 |
+
message, images = message
|
103 |
+
message = "<image>" * len(images) + message
|
104 |
+
chat_template_messages.append({"role": role, "content": message})
|
105 |
+
|
106 |
+
# print(chat_template_messages)
|
107 |
+
return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
|
108 |
+
# ret = "" if self.system == "" else self.system + self.sep + "\n"
|
109 |
+
# for role, message in messages:
|
110 |
+
# if message:
|
111 |
+
# if type(message) is tuple:
|
112 |
+
# message, images = message
|
113 |
+
# message = "<image>" * len(images) + message
|
114 |
+
# ret += role + "\n" + message + self.sep + "\n"
|
115 |
+
# else:
|
116 |
+
# ret += role + "\n"
|
117 |
+
# return ret
|
118 |
+
|
119 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
120 |
+
ret = self.system + self.sep
|
121 |
+
for role, message in messages:
|
122 |
+
if message:
|
123 |
+
if type(message) is tuple:
|
124 |
+
message, _, _ = message
|
125 |
+
ret += role + message + self.sep
|
126 |
+
else:
|
127 |
+
ret += role
|
128 |
+
|
129 |
+
elif self.sep_style == SeparatorStyle.GEMMA:
|
130 |
+
ret = ""
|
131 |
+
for i, (role, message) in enumerate(messages):
|
132 |
+
assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
|
133 |
+
if message:
|
134 |
+
if type(message) is tuple:
|
135 |
+
message, _, _ = message
|
136 |
+
ret += role + message + self.sep
|
137 |
+
else:
|
138 |
+
ret += role
|
139 |
+
|
140 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
141 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
|
142 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
143 |
+
ret = ""
|
144 |
+
|
145 |
+
for i, (role, message) in enumerate(messages):
|
146 |
+
if i == 0:
|
147 |
+
assert message, "first message should not be none"
|
148 |
+
assert role == self.roles[0], "first message should come from user"
|
149 |
+
if message:
|
150 |
+
if type(message) is tuple:
|
151 |
+
message, _, _ = message
|
152 |
+
if i == 0:
|
153 |
+
message = wrap_sys(self.system) + message
|
154 |
+
if i % 2 == 0:
|
155 |
+
message = wrap_inst(message)
|
156 |
+
ret += self.sep + message
|
157 |
+
else:
|
158 |
+
ret += " " + message + " " + self.sep2
|
159 |
+
else:
|
160 |
+
ret += ""
|
161 |
+
ret = ret.lstrip(self.sep)
|
162 |
+
|
163 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
164 |
+
seps = [self.sep, self.sep2]
|
165 |
+
ret = self.system
|
166 |
+
for i, (role, message) in enumerate(messages):
|
167 |
+
if message:
|
168 |
+
if type(message) is tuple:
|
169 |
+
message, _, _ = message
|
170 |
+
ret += message + seps[i % 2]
|
171 |
+
else:
|
172 |
+
ret += ""
|
173 |
+
else:
|
174 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
175 |
+
|
176 |
+
return ret
|
177 |
+
|
178 |
+
def append_message(self, role, message):
|
179 |
+
self.messages.append([role, message])
|
180 |
+
|
181 |
+
def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
|
182 |
+
if image_process_mode == "Pad":
|
183 |
+
|
184 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
185 |
+
width, height = pil_img.size
|
186 |
+
if width == height:
|
187 |
+
return pil_img
|
188 |
+
elif width > height:
|
189 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
190 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
191 |
+
return result
|
192 |
+
else:
|
193 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
194 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
195 |
+
return result
|
196 |
+
|
197 |
+
image = expand2square(image)
|
198 |
+
elif image_process_mode in ["Default", "Crop"]:
|
199 |
+
pass
|
200 |
+
elif image_process_mode == "Resize":
|
201 |
+
image = image.resize((336, 336))
|
202 |
+
else:
|
203 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
204 |
+
|
205 |
+
if type(image) is not Image.Image:
|
206 |
+
image = Image.open(image).convert("RGB")
|
207 |
+
|
208 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
209 |
+
aspect_ratio = max_hw / min_hw
|
210 |
+
max_len, min_len = 672, 448
|
211 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
212 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
213 |
+
W, H = image.size
|
214 |
+
if H > W:
|
215 |
+
H, W = longest_edge, shortest_edge
|
216 |
+
else:
|
217 |
+
H, W = shortest_edge, longest_edge
|
218 |
+
image = image.resize((W, H))
|
219 |
+
if return_pil:
|
220 |
+
return image
|
221 |
+
else:
|
222 |
+
buffered = BytesIO()
|
223 |
+
image.save(buffered, format=image_format)
|
224 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
225 |
+
return img_b64_str
|
226 |
+
|
227 |
+
def get_images(self, return_pil=False, return_path=False):
|
228 |
+
images = []
|
229 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
230 |
+
if i % 2 == 0:
|
231 |
+
if type(msg) is tuple:
|
232 |
+
msg, image, image_process_mode = msg
|
233 |
+
if type(image) != list:
|
234 |
+
image = [image]
|
235 |
+
for img in image:
|
236 |
+
if not return_path and self.is_image_file(img):
|
237 |
+
img = self.process_image(img, image_process_mode, return_pil=return_pil)
|
238 |
+
else:
|
239 |
+
images.append(img)
|
240 |
+
return images
|
241 |
+
|
242 |
+
def is_image_file(self, filename):
|
243 |
+
image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
|
244 |
+
return any(filename.lower().endswith(ext) for ext in image_extensions)
|
245 |
+
|
246 |
+
def is_video_file(self, filename):
|
247 |
+
video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
|
248 |
+
return any(filename.lower().endswith(ext) for ext in video_extensions)
|
249 |
+
|
250 |
+
def to_gradio_chatbot(self):
|
251 |
+
ret = []
|
252 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
253 |
+
if i % 2 == 0:
|
254 |
+
if type(msg) is tuple:
|
255 |
+
msg, image, image_process_mode = msg
|
256 |
+
if type(image) != list:
|
257 |
+
image = [image]
|
258 |
+
if len(image) == 1:
|
259 |
+
msg = "<image>\n" + msg.replace("<image>", "").strip()
|
260 |
+
else:
|
261 |
+
msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
|
262 |
+
|
263 |
+
img_str_list = []
|
264 |
+
for img in image:
|
265 |
+
if self.is_image_file(img):
|
266 |
+
img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
|
267 |
+
img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
|
268 |
+
img_str_list.append(img_str)
|
269 |
+
elif self.is_video_file(img):
|
270 |
+
ret.append(((img,), None))
|
271 |
+
|
272 |
+
msg = msg.strip()
|
273 |
+
img_place_holder = ""
|
274 |
+
for img_str in img_str_list:
|
275 |
+
img_place_holder += f"{img_str}\n\n"
|
276 |
+
|
277 |
+
if len(img_str_list) > 0:
|
278 |
+
msg = f"{img_place_holder}\n\n{msg}"
|
279 |
+
|
280 |
+
if len(msg) > 0:
|
281 |
+
ret.append([msg, None])
|
282 |
+
else:
|
283 |
+
ret.append([msg, None])
|
284 |
+
else:
|
285 |
+
ret[-1][-1] = msg
|
286 |
+
return ret
|
287 |
+
|
288 |
+
def copy(self):
|
289 |
+
return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
|
290 |
+
|
291 |
+
def dict(self):
|
292 |
+
if len(self.get_images()) > 0:
|
293 |
+
return {
|
294 |
+
"system": self.system,
|
295 |
+
"roles": self.roles,
|
296 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
297 |
+
"offset": self.offset,
|
298 |
+
"sep": self.sep,
|
299 |
+
"sep2": self.sep2,
|
300 |
+
}
|
301 |
+
return {
|
302 |
+
"system": self.system,
|
303 |
+
"roles": self.roles,
|
304 |
+
"messages": self.messages,
|
305 |
+
"offset": self.offset,
|
306 |
+
"sep": self.sep,
|
307 |
+
"sep2": self.sep2,
|
308 |
+
}
|
309 |
+
|
310 |
+
|
311 |
+
conv_vicuna_v0 = Conversation(
|
312 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
313 |
+
roles=("Human", "Assistant"),
|
314 |
+
messages=[
|
315 |
+
["Human", "What are the key differences between renewable and non-renewable energy sources?"],
|
316 |
+
[
|
317 |
+
"Assistant",
|
318 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
319 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
320 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
321 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
322 |
+
"renewable and non-renewable energy sources:\n"
|
323 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
324 |
+
"energy sources are finite and will eventually run out.\n"
|
325 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
326 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
327 |
+
"and other negative effects.\n"
|
328 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
329 |
+
"have lower operational costs than non-renewable sources.\n"
|
330 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
331 |
+
"locations than non-renewable sources.\n"
|
332 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
333 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
334 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
335 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
|
336 |
+
],
|
337 |
+
],
|
338 |
+
offset=2,
|
339 |
+
sep_style=SeparatorStyle.SINGLE,
|
340 |
+
sep="###",
|
341 |
+
)
|
342 |
+
|
343 |
+
conv_vicuna_v1 = Conversation(
|
344 |
+
system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
345 |
+
roles=("USER", "ASSISTANT"),
|
346 |
+
version="v1",
|
347 |
+
messages=[],
|
348 |
+
offset=0,
|
349 |
+
sep_style=SeparatorStyle.TWO,
|
350 |
+
sep=" ",
|
351 |
+
sep2="</s>",
|
352 |
+
)
|
353 |
+
|
354 |
+
conv_llama_2 = Conversation(
|
355 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
356 |
+
|
357 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
358 |
+
roles=("USER", "ASSISTANT"),
|
359 |
+
version="llama_v2",
|
360 |
+
messages=[],
|
361 |
+
offset=0,
|
362 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
363 |
+
sep="<s>",
|
364 |
+
sep2="</s>",
|
365 |
+
)
|
366 |
+
|
367 |
+
conv_llava_llama_2 = Conversation(
|
368 |
+
system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
369 |
+
roles=("USER", "ASSISTANT"),
|
370 |
+
version="llama_v2",
|
371 |
+
messages=[],
|
372 |
+
offset=0,
|
373 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
374 |
+
sep="<s>",
|
375 |
+
sep2="</s>",
|
376 |
+
)
|
377 |
+
|
378 |
+
# conv_llava_llama_3 = Conversation(
|
379 |
+
# system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
380 |
+
# roles=("user", "assistant"),
|
381 |
+
# version="llama_v3",
|
382 |
+
# messages=[],
|
383 |
+
# offset=0,
|
384 |
+
# sep="<|eot_id|>",
|
385 |
+
# sep_style=SeparatorStyle.LLAMA_3,
|
386 |
+
# tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
|
387 |
+
# tokenizer=AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct"),
|
388 |
+
# stop_token_ids=[128009],
|
389 |
+
# )
|
390 |
+
|
391 |
+
conv_mistral_instruct = Conversation(
|
392 |
+
system="",
|
393 |
+
roles=("USER", "ASSISTANT"),
|
394 |
+
version="llama_v2",
|
395 |
+
messages=[],
|
396 |
+
offset=0,
|
397 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
398 |
+
sep="",
|
399 |
+
sep2="</s>",
|
400 |
+
)
|
401 |
+
|
402 |
+
conv_llava_llama_2_simple = Conversation(
|
403 |
+
system="Answer the questions about the visual content that the user provides.",
|
404 |
+
roles=("USER", "ASSISTANT"),
|
405 |
+
version="llama_v2",
|
406 |
+
messages=[],
|
407 |
+
offset=0,
|
408 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
409 |
+
sep="<s>",
|
410 |
+
sep2="</s>",
|
411 |
+
)
|
412 |
+
|
413 |
+
conv_llava_llama_2_mmtag = Conversation(
|
414 |
+
system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
|
415 |
+
roles=("USER", "ASSISTANT"),
|
416 |
+
version="llama_v2_mmtag",
|
417 |
+
messages=[],
|
418 |
+
offset=0,
|
419 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
420 |
+
sep="<s>",
|
421 |
+
sep2="</s>",
|
422 |
+
)
|
423 |
+
|
424 |
+
conv_mpt = Conversation(
|
425 |
+
system="""<|im_start|>system
|
426 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
427 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
428 |
+
version="mpt",
|
429 |
+
messages=[],
|
430 |
+
offset=0,
|
431 |
+
sep_style=SeparatorStyle.MPT,
|
432 |
+
sep="<|im_end|>",
|
433 |
+
)
|
434 |
+
|
435 |
+
conv_qwen = Conversation(
|
436 |
+
system="""<|im_start|>system
|
437 |
+
You are a helpful assistant.""",
|
438 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
439 |
+
version="qwen",
|
440 |
+
messages=[],
|
441 |
+
offset=0,
|
442 |
+
sep_style=SeparatorStyle.CHATML,
|
443 |
+
sep="<|im_end|>",
|
444 |
+
)
|
445 |
+
|
446 |
+
|
447 |
+
|
448 |
+
conv_internlm_2 = Conversation(
|
449 |
+
system="""<|im_start|>system
|
450 |
+
You are a helpful assistant.""",
|
451 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
452 |
+
version="internlm_2",
|
453 |
+
messages=[],
|
454 |
+
offset=0,
|
455 |
+
sep_style=SeparatorStyle.CHATML,
|
456 |
+
sep="<|im_end|>",
|
457 |
+
)
|
458 |
+
|
459 |
+
conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
|
460 |
+
|
461 |
+
conv_llava_plain = Conversation(
|
462 |
+
system="",
|
463 |
+
roles=("", ""),
|
464 |
+
messages=[],
|
465 |
+
offset=0,
|
466 |
+
sep_style=SeparatorStyle.PLAIN,
|
467 |
+
sep="\n",
|
468 |
+
)
|
469 |
+
|
470 |
+
conv_llava_v0 = Conversation(
|
471 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
472 |
+
roles=("Human", "Assistant"),
|
473 |
+
messages=[],
|
474 |
+
offset=0,
|
475 |
+
sep_style=SeparatorStyle.SINGLE,
|
476 |
+
sep="###",
|
477 |
+
)
|
478 |
+
|
479 |
+
conv_llava_v0_mmtag = Conversation(
|
480 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
481 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
482 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
483 |
+
roles=("Human", "Assistant"),
|
484 |
+
messages=[],
|
485 |
+
offset=0,
|
486 |
+
sep_style=SeparatorStyle.SINGLE,
|
487 |
+
sep="###",
|
488 |
+
version="v0_mmtag",
|
489 |
+
)
|
490 |
+
|
491 |
+
conv_llava_v1 = Conversation(
|
492 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
493 |
+
roles=("USER", "ASSISTANT"),
|
494 |
+
version="v1",
|
495 |
+
messages=[],
|
496 |
+
offset=0,
|
497 |
+
sep_style=SeparatorStyle.TWO,
|
498 |
+
sep=" ",
|
499 |
+
sep2="</s>",
|
500 |
+
)
|
501 |
+
|
502 |
+
conv_llava_v1_mmtag = Conversation(
|
503 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
504 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
505 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
506 |
+
roles=("USER", "ASSISTANT"),
|
507 |
+
messages=[],
|
508 |
+
offset=0,
|
509 |
+
sep_style=SeparatorStyle.TWO,
|
510 |
+
sep=" ",
|
511 |
+
sep2="</s>",
|
512 |
+
version="v1_mmtag",
|
513 |
+
)
|
514 |
+
|
515 |
+
conv_mistral_orca = Conversation(
|
516 |
+
system="""<|im_start|>system
|
517 |
+
You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
|
518 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
519 |
+
version="mpt",
|
520 |
+
messages=[],
|
521 |
+
offset=0,
|
522 |
+
sep_style=SeparatorStyle.MPT,
|
523 |
+
sep="<|im_end|>",
|
524 |
+
)
|
525 |
+
|
526 |
+
conv_mistral_zephyr = Conversation(
|
527 |
+
system="""<|system|>
|
528 |
+
You are a helpful AI assistant.""",
|
529 |
+
roles=("<|user|>\n", "<|assistant|>\n"),
|
530 |
+
version="mpt",
|
531 |
+
messages=[],
|
532 |
+
offset=0,
|
533 |
+
sep_style=SeparatorStyle.MPT,
|
534 |
+
sep="</s>",
|
535 |
+
)
|
536 |
+
|
537 |
+
conv_mistral_direct = Conversation(
|
538 |
+
system="""<|im_start|>system
|
539 |
+
Answer the questions.""",
|
540 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
541 |
+
version="mpt",
|
542 |
+
messages=[],
|
543 |
+
offset=0,
|
544 |
+
sep_style=SeparatorStyle.MPT,
|
545 |
+
sep="<|im_end|>",
|
546 |
+
)
|
547 |
+
|
548 |
+
conv_chatml_direct = Conversation(
|
549 |
+
system="""<|im_start|>system
|
550 |
+
Answer the questions.""",
|
551 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
552 |
+
version="mpt",
|
553 |
+
messages=[],
|
554 |
+
offset=0,
|
555 |
+
sep_style=SeparatorStyle.MPT,
|
556 |
+
sep="<|im_end|>",
|
557 |
+
)
|
558 |
+
|
559 |
+
default_conversation = conv_vicuna_v0
|
560 |
+
conv_templates = {
|
561 |
+
"default": conv_vicuna_v0,
|
562 |
+
"v0": conv_vicuna_v0,
|
563 |
+
"v1": conv_vicuna_v1,
|
564 |
+
"vicuna_v1": conv_vicuna_v1,
|
565 |
+
"llama_2": conv_llama_2,
|
566 |
+
"mistral_instruct": conv_mistral_instruct,
|
567 |
+
"mistral_orca": conv_mistral_orca,
|
568 |
+
"mistral_zephyr": conv_mistral_zephyr,
|
569 |
+
"mistral_direct": conv_mistral_direct,
|
570 |
+
"plain": conv_llava_plain,
|
571 |
+
"v0_plain": conv_llava_plain,
|
572 |
+
"chatml_direct": conv_chatml_direct,
|
573 |
+
"llava_v0": conv_llava_v0,
|
574 |
+
"llava_v0_mmtag": conv_llava_v0_mmtag,
|
575 |
+
"llava_v1": conv_llava_v1,
|
576 |
+
"llava_v1_mmtag": conv_llava_v1_mmtag,
|
577 |
+
"llava_llama_2": conv_llava_llama_2,
|
578 |
+
# "llava_llama_3": conv_llava_llama_3,
|
579 |
+
"llava_llama_2_simple": conv_llava_llama_2_simple,
|
580 |
+
"llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
|
581 |
+
"llava_mistral_instruct": conv_mistral_instruct,
|
582 |
+
"mpt": conv_mpt,
|
583 |
+
"qwen_1_5": conv_qwen,
|
584 |
+
"qwen_2": conv_qwen,
|
585 |
+
"internlm_2": conv_internlm_2,
|
586 |
+
"gemma_instruct": conv_gemma_instruct,
|
587 |
+
}
|
588 |
+
|
589 |
+
|
590 |
+
if __name__ == "__main__":
|
591 |
+
print(default_conversation.get_prompt())
|
592 |
+
print(default_conversation)
|
.ipynb_checkpoints/mm_utils-checkpoint.py
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
from io import BytesIO
|
3 |
+
import base64
|
4 |
+
import math
|
5 |
+
import ast
|
6 |
+
import re
|
7 |
+
import torch
|
8 |
+
from transformers import StoppingCriteria
|
9 |
+
from .constants import IMAGE_TOKEN_INDEX
|
10 |
+
import random
|
11 |
+
import os
|
12 |
+
import io
|
13 |
+
import av
|
14 |
+
import cv2
|
15 |
+
import imageio
|
16 |
+
from decord import VideoReader
|
17 |
+
import numpy as np
|
18 |
+
from torchvision.transforms.functional import pil_to_tensor
|
19 |
+
|
20 |
+
|
21 |
+
######################## load video ########################
|
22 |
+
|
23 |
+
def get_index(num_frames, num_segments):
|
24 |
+
seg_size = float(num_frames - 1) / num_segments
|
25 |
+
start = int(seg_size / 2)
|
26 |
+
offsets = np.array([
|
27 |
+
start + int(np.round(seg_size * idx)) for idx in range(num_segments)
|
28 |
+
])
|
29 |
+
return offsets
|
30 |
+
|
31 |
+
|
32 |
+
def pts_to_secs(pts: int, time_base: float, start_pts: int) -> float:
|
33 |
+
"""
|
34 |
+
Converts a present time with the given time base and start_pts offset to seconds.
|
35 |
+
|
36 |
+
Returns:
|
37 |
+
time_in_seconds (float): The corresponding time in seconds.
|
38 |
+
|
39 |
+
https://github.com/facebookresearch/pytorchvideo/blob/main/pytorchvideo/data/utils.py#L54-L64
|
40 |
+
"""
|
41 |
+
if pts == math.inf:
|
42 |
+
return math.inf
|
43 |
+
|
44 |
+
return int(pts - start_pts) * time_base
|
45 |
+
|
46 |
+
|
47 |
+
def get_pyav_video_duration(video_reader):
|
48 |
+
video_stream = video_reader.streams.video[0]
|
49 |
+
video_duration = pts_to_secs(
|
50 |
+
video_stream.duration,
|
51 |
+
video_stream.time_base,
|
52 |
+
video_stream.start_time
|
53 |
+
)
|
54 |
+
return float(video_duration)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
def get_frame_indices(num_frames, vlen, sample='middle', fix_start=None, input_fps=1, min_num_frames=1, max_num_frames=-1, local_num_frames=8):
|
59 |
+
|
60 |
+
if min_num_frames > vlen:
|
61 |
+
if sample == 'dynamic_fps1':
|
62 |
+
min_num_frames = (vlen // local_num_frames) * local_num_frames
|
63 |
+
else:
|
64 |
+
min_num_frames = vlen
|
65 |
+
|
66 |
+
|
67 |
+
if sample == 'dynamic_fps1':
|
68 |
+
|
69 |
+
duration = float(vlen) / input_fps
|
70 |
+
num_segments = int(duration // local_num_frames)
|
71 |
+
if num_segments == 0:
|
72 |
+
num_frames = local_num_frames
|
73 |
+
else:
|
74 |
+
num_frames = local_num_frames * num_segments
|
75 |
+
|
76 |
+
if max_num_frames > 0:
|
77 |
+
num_frames = min(num_frames, max_num_frames)
|
78 |
+
sample = "middle" # NOTE
|
79 |
+
|
80 |
+
# logger.info(f"? is OK (img), duation={duration} frames={num_frames}!!!!")
|
81 |
+
|
82 |
+
num_frames = max(min_num_frames, num_frames)
|
83 |
+
|
84 |
+
# print(f"\033[0;31m vlen={vlen}, input_fps={input_fps} num_frames={num_frames} \033[0m")
|
85 |
+
|
86 |
+
if sample in ["rand", "middle"]: # uniform sampling
|
87 |
+
acc_samples = min(num_frames, vlen)
|
88 |
+
# split the video into `acc_samples` intervals, and sample from each interval.
|
89 |
+
intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
|
90 |
+
ranges = []
|
91 |
+
for idx, interv in enumerate(intervals[:-1]):
|
92 |
+
ranges.append((interv, intervals[idx + 1] - 1))
|
93 |
+
if sample == 'rand':
|
94 |
+
try:
|
95 |
+
frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
|
96 |
+
except:
|
97 |
+
frame_indices = np.random.permutation(vlen)[:acc_samples]
|
98 |
+
frame_indices.sort()
|
99 |
+
frame_indices = list(frame_indices)
|
100 |
+
elif fix_start is not None:
|
101 |
+
frame_indices = [x[0] + fix_start for x in ranges]
|
102 |
+
elif sample == 'middle':
|
103 |
+
frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
|
104 |
+
else:
|
105 |
+
raise NotImplementedError
|
106 |
+
|
107 |
+
if len(frame_indices) < num_frames: # padded with last frame
|
108 |
+
padded_frame_indices = [frame_indices[-1]] * num_frames
|
109 |
+
padded_frame_indices[:len(frame_indices)] = frame_indices
|
110 |
+
frame_indices = padded_frame_indices
|
111 |
+
elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
|
112 |
+
output_fps = float(sample[3:])
|
113 |
+
duration = float(vlen) / input_fps
|
114 |
+
delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
|
115 |
+
frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
|
116 |
+
frame_indices = np.around(frame_seconds * input_fps).astype(int)
|
117 |
+
frame_indices = [e for e in frame_indices if e < vlen]
|
118 |
+
if max_num_frames > 0 and len(frame_indices) > max_num_frames:
|
119 |
+
frame_indices = frame_indices[:max_num_frames]
|
120 |
+
# frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
|
121 |
+
else:
|
122 |
+
raise ValueError(f"Not support sample type: {sample}")
|
123 |
+
|
124 |
+
|
125 |
+
return frame_indices
|
126 |
+
|
127 |
+
|
128 |
+
def read_frames_av(video_path, num_frames, sample='rand', client=None, fix_start=None, min_num_frames=1, max_num_frames=-1, clip=None, local_num_frames=8):
|
129 |
+
if clip is not None:
|
130 |
+
raise NotImplementedError("av don't support clip!!!")
|
131 |
+
if 's3://' in video_path:
|
132 |
+
video_bytes = client.get(video_path)
|
133 |
+
byteio = io.BytesIO(video_bytes)
|
134 |
+
byteio.seek(0)
|
135 |
+
reader = av.open(byteio)
|
136 |
+
else:
|
137 |
+
byteio = None
|
138 |
+
reader = av.open(video_path)
|
139 |
+
frames = [f.to_rgb().to_ndarray() for f in reader.decode(video=0)]
|
140 |
+
vlen = len(frames)
|
141 |
+
duration = get_pyav_video_duration(reader)
|
142 |
+
fps = vlen / float(duration)
|
143 |
+
frame_indices = get_frame_indices(
|
144 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
145 |
+
input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
146 |
+
)
|
147 |
+
frames = np.stack([frames[idx] for idx in frame_indices]) # (T, H, W, C), torch.uint8
|
148 |
+
# frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
|
149 |
+
if byteio != None:
|
150 |
+
byteio.close()
|
151 |
+
|
152 |
+
reader.close()
|
153 |
+
|
154 |
+
return frames, frame_indices, float(fps), duration
|
155 |
+
|
156 |
+
|
157 |
+
def read_frames_gif(
|
158 |
+
video_path, num_frames, sample='rand', fix_start=None,
|
159 |
+
min_num_frames=1, max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
160 |
+
):
|
161 |
+
if clip is not None:
|
162 |
+
raise NotImplementedError("Gif don't support clip!!!")
|
163 |
+
if 's3://' in video_path:
|
164 |
+
video_bytes = client.get(video_path)
|
165 |
+
byteio = io.BytesIO(video_bytes)
|
166 |
+
gif = imageio.get_reader(byteio)
|
167 |
+
else:
|
168 |
+
byteio = None
|
169 |
+
gif = imageio.get_reader(video_path)
|
170 |
+
vlen = len(gif)
|
171 |
+
fps = 1.
|
172 |
+
duration = vlen / fps
|
173 |
+
frame_indices = get_frame_indices(
|
174 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
175 |
+
min_num_frames=min_num_frames,
|
176 |
+
max_num_frames=max_num_frames, local_num_frames=local_num_frames,
|
177 |
+
input_fps=fps
|
178 |
+
)
|
179 |
+
frames = []
|
180 |
+
|
181 |
+
min_h = min_w = 100000
|
182 |
+
hw_set = set()
|
183 |
+
for index, frame in enumerate(gif):
|
184 |
+
# for index in frame_idxs:
|
185 |
+
if index in frame_indices:
|
186 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
|
187 |
+
frame = frame.astype(np.uint8)
|
188 |
+
# # (H x W x C) to (C x H x W)
|
189 |
+
# frame = frame.permute(2, 0, 1)
|
190 |
+
frames.append(frame)
|
191 |
+
hw_set.add(frame.shape)
|
192 |
+
if frame.shape[0] < min_h:
|
193 |
+
min_h = frame.shape[0]
|
194 |
+
if frame.shape[1] < min_w:
|
195 |
+
min_w = frame.shape[1]
|
196 |
+
# print(hw_set, min_h, min_w)
|
197 |
+
if len(hw_set) > 1:
|
198 |
+
frames = [i[:min_h, :min_w] for i in frames]
|
199 |
+
|
200 |
+
frames = np.stack(frames) # .float() / 255
|
201 |
+
|
202 |
+
if byteio != None:
|
203 |
+
byteio.close()
|
204 |
+
|
205 |
+
return frames, frame_indices, float(fps), duration # for tgif
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
def read_frames_decord(
|
210 |
+
video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
|
211 |
+
max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
212 |
+
):
|
213 |
+
|
214 |
+
if video_path.endswith('.avi'):
|
215 |
+
return read_frames_av(video_path=video_path, num_frames=num_frames, sample=sample,
|
216 |
+
fix_start=fix_start, min_num_frames=min_num_frames, max_num_frames=max_num_frames,
|
217 |
+
client=client, clip=clip, local_num_frames=local_num_frames)
|
218 |
+
if 's3://' in video_path:
|
219 |
+
video_bytes = client.get(video_path)
|
220 |
+
if video_bytes is None or len(video_bytes) == 0:
|
221 |
+
raise ValueError(f"Can't read byte from {video_path}!")
|
222 |
+
byteio = io.BytesIO(video_bytes)
|
223 |
+
video_reader = VideoReader(byteio, num_threads=1)
|
224 |
+
else:
|
225 |
+
byteio = None
|
226 |
+
video_reader = VideoReader(video_path, num_threads=1)
|
227 |
+
vlen = len(video_reader)
|
228 |
+
fps = video_reader.get_avg_fps()
|
229 |
+
duration = vlen / float(fps)
|
230 |
+
|
231 |
+
|
232 |
+
if clip:
|
233 |
+
start, end = clip
|
234 |
+
start = max(0, start)
|
235 |
+
end = min(duration - 0.1, end)
|
236 |
+
duration = end - start
|
237 |
+
vlen = int(duration * fps)
|
238 |
+
start_index = int(start * fps)
|
239 |
+
|
240 |
+
frame_indices = get_frame_indices(
|
241 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
242 |
+
input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
243 |
+
)
|
244 |
+
if clip:
|
245 |
+
frame_indices = [f + start_index for f in frame_indices]
|
246 |
+
|
247 |
+
# print(fps, frame_indices)
|
248 |
+
frames = video_reader.get_batch(frame_indices).asnumpy() # (T, H, W, C), torch.uint8
|
249 |
+
# https://github.com/dmlc/decord/issues/208
|
250 |
+
video_reader.seek(0)
|
251 |
+
|
252 |
+
if byteio != None:
|
253 |
+
byteio.close()
|
254 |
+
# frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
|
255 |
+
return frames, frame_indices, float(fps), duration
|
256 |
+
|
257 |
+
|
258 |
+
|
259 |
+
def read_frames_img(
|
260 |
+
video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
|
261 |
+
max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
262 |
+
):
|
263 |
+
def extract_frame_number(filename):
|
264 |
+
# Extract the numeric part from the filename using regular expressions
|
265 |
+
if filename.endswith('.jpg'):
|
266 |
+
match = re.search(r'_(\d+).jpg$', filename)
|
267 |
+
elif filename.endswith('.jpeg'):
|
268 |
+
match = re.search(r'_(\d+).jpeg$', filename)
|
269 |
+
elif filename.endswith('.png'):
|
270 |
+
match = re.search(r'_(\d+).png$', filename)
|
271 |
+
else:
|
272 |
+
raise NotImplementedError(f"Wrong filename: {filename}")
|
273 |
+
|
274 |
+
return int(match.group(1)) if match else -1
|
275 |
+
|
276 |
+
|
277 |
+
def sort_frames(frame_paths):
|
278 |
+
# Extract filenames from each path and sort by their numeric part
|
279 |
+
return sorted(frame_paths, key=lambda x: extract_frame_number(os.path.basename(x)))
|
280 |
+
|
281 |
+
# img_list=[]
|
282 |
+
|
283 |
+
if "s3://" in video_path:
|
284 |
+
img_list = sort_frames(client.list(video_path))
|
285 |
+
else:
|
286 |
+
img_list = sort_frames(list(os.listdir(video_path)))
|
287 |
+
|
288 |
+
|
289 |
+
if 'tvqa' in video_path.lower():
|
290 |
+
fps = 3.0
|
291 |
+
else:
|
292 |
+
fps = 1.0
|
293 |
+
|
294 |
+
if clip is not None:
|
295 |
+
start = float(clip[0])
|
296 |
+
end = float(clip[1])
|
297 |
+
start = max(0, start)
|
298 |
+
end = min(len(img_list) / fps, end)
|
299 |
+
vlen = (end - start) * fps
|
300 |
+
else:
|
301 |
+
vlen = len(img_list)
|
302 |
+
|
303 |
+
duration = vlen / fps
|
304 |
+
|
305 |
+
if min_num_frames > vlen:
|
306 |
+
if sample == 'dynamic_fps1':
|
307 |
+
min_num_frames = (vlen // local_num_frames) * local_num_frames
|
308 |
+
else:
|
309 |
+
min_num_frames = vlen
|
310 |
+
|
311 |
+
if sample == 'dynamic_fps1':
|
312 |
+
num_segments = int(duration // local_num_frames)
|
313 |
+
if num_segments == 0:
|
314 |
+
num_frames = local_num_frames
|
315 |
+
else:
|
316 |
+
num_frames = local_num_frames * num_segments
|
317 |
+
num_frames = min(num_frames, max_num_frames)
|
318 |
+
num_frames = max(min_num_frames, num_frames)
|
319 |
+
|
320 |
+
num_frames = int(num_frames)
|
321 |
+
if clip is not None:
|
322 |
+
def _get_index_by_time(start_sec, end_sec, num_segments=8, fps=1., max_frame=9999):
|
323 |
+
start_idx = max(1, round(start_sec * fps))
|
324 |
+
end_idx = min(round(end_sec * fps), max_frame)
|
325 |
+
seg_size = float(end_idx - start_idx) / (num_segments - 1)
|
326 |
+
offsets = np.array([start_idx + int(np.round(seg_size * idx)) for idx in range(num_segments)])
|
327 |
+
return offsets
|
328 |
+
|
329 |
+
frame_indices = _get_index_by_time(float(clip[0]), float(clip[1]), num_segments=num_frames, fps=fps, max_frame=len(img_list)-1)
|
330 |
+
else:
|
331 |
+
frame_indices = get_frame_indices(
|
332 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
333 |
+
min_num_frames=min_num_frames,
|
334 |
+
max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
335 |
+
)
|
336 |
+
|
337 |
+
imgs = []
|
338 |
+
for idx in frame_indices:
|
339 |
+
frame_fname = os.path.join(video_path, img_list[idx])
|
340 |
+
if "s3://" in video_path:
|
341 |
+
img_bytes = client.get(frame_fname)
|
342 |
+
else:
|
343 |
+
with open(frame_fname, 'rb') as f:
|
344 |
+
img_bytes = f.read()
|
345 |
+
img_np = np.frombuffer(img_bytes, np.uint8)
|
346 |
+
img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
|
347 |
+
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
|
348 |
+
imgs.append(img)
|
349 |
+
|
350 |
+
frames = np.array(imgs, dtype=np.uint8)
|
351 |
+
|
352 |
+
|
353 |
+
return frames, frame_indices, fps, duration
|
354 |
+
|
355 |
+
|
356 |
+
|
357 |
+
VIDEO_READER_FUNCS = {
|
358 |
+
'av': read_frames_av,
|
359 |
+
'decord': read_frames_decord,
|
360 |
+
'gif': read_frames_gif,
|
361 |
+
'img': read_frames_img,
|
362 |
+
'frame': read_frames_img
|
363 |
+
}
|
364 |
+
|
365 |
+
|
366 |
+
|
367 |
+
def load_video(video_path, max_num_frames=512, media_dict=None): #, media_dict):
|
368 |
+
|
369 |
+
if media_dict is None:
|
370 |
+
media_dict = {'video_read_type': 'decord'}
|
371 |
+
|
372 |
+
if type(video_path) != str:
|
373 |
+
assert len(video_path) == 1, video_path
|
374 |
+
video_path = video_path[0]
|
375 |
+
|
376 |
+
if 'start' in media_dict:
|
377 |
+
clip = [media_dict['start'], media_dict['end']]
|
378 |
+
else:
|
379 |
+
clip = None
|
380 |
+
|
381 |
+
|
382 |
+
client = None
|
383 |
+
|
384 |
+
frames, frame_indices, fps, duration = VIDEO_READER_FUNCS[media_dict['video_read_type']](video_path=video_path, num_frames=max_num_frames, sample='dynamic_fps1', fix_start=None, min_num_frames=64, max_num_frames=max_num_frames, client=client, clip=clip, local_num_frames=8)
|
385 |
+
|
386 |
+
sec = [str(round(f / fps, 1)) for f in frame_indices]
|
387 |
+
|
388 |
+
msg = f"\nThe video lasts for {duration:.2f} seconds, and {len(sec)} frames are uniformly sampled from it. "
|
389 |
+
|
390 |
+
return frames, msg
|
391 |
+
|
392 |
+
|
393 |
+
######################## load video ########################
|
394 |
+
|
395 |
+
|
396 |
+
def resize_and_center_crop(image, shortest_edge_length):
|
397 |
+
# Calculate new dimensions and resize
|
398 |
+
aspect_ratio = float(image.width) / float(image.height)
|
399 |
+
if aspect_ratio > 1:
|
400 |
+
new_width = int(shortest_edge_length * aspect_ratio)
|
401 |
+
new_height = shortest_edge_length
|
402 |
+
else:
|
403 |
+
new_width = shortest_edge_length
|
404 |
+
new_height = int(shortest_edge_length / aspect_ratio)
|
405 |
+
resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
|
406 |
+
|
407 |
+
# Calculate the position and perform the center crop
|
408 |
+
left = (new_width - shortest_edge_length) / 2
|
409 |
+
top = (new_height - shortest_edge_length) / 2
|
410 |
+
right = (new_width + shortest_edge_length) / 2
|
411 |
+
bottom = (new_height + shortest_edge_length) / 2
|
412 |
+
cropped_image = resized_image.crop((left, top, right, bottom))
|
413 |
+
|
414 |
+
return cropped_image
|
415 |
+
|
416 |
+
|
417 |
+
def auto_pad_images(image, grid_params):
|
418 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
419 |
+
assert len(grid_params) > 0, "Grid parameters should not be empty"
|
420 |
+
|
421 |
+
# Step 1: Calculate and find the closest aspect ratio
|
422 |
+
input_width, input_height = image.size
|
423 |
+
input_aspect_ratio = input_width / input_height
|
424 |
+
candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
|
425 |
+
closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
|
426 |
+
|
427 |
+
candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
|
428 |
+
|
429 |
+
target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
|
430 |
+
|
431 |
+
resize_width, resize_height = target_resolution
|
432 |
+
if input_width > input_height:
|
433 |
+
resize_height = int(resize_width / input_aspect_ratio)
|
434 |
+
else:
|
435 |
+
resize_width = int(resize_height * input_aspect_ratio)
|
436 |
+
resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
|
437 |
+
|
438 |
+
# Step 5: Pad the resized image if necessary to match the target resolution
|
439 |
+
pad_width = target_resolution[0] - resize_width
|
440 |
+
pad_height = target_resolution[1] - resize_height
|
441 |
+
padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
|
442 |
+
padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
|
443 |
+
|
444 |
+
return padded_image
|
445 |
+
|
446 |
+
|
447 |
+
def extract_patches(image, patch_size, overlap_ratio):
|
448 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
449 |
+
assert patch_size > 0, "Patch size should be greater than 0"
|
450 |
+
assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
|
451 |
+
|
452 |
+
W, H = image.size
|
453 |
+
patches = []
|
454 |
+
|
455 |
+
stride = int(patch_size * (1 - overlap_ratio))
|
456 |
+
|
457 |
+
num_patches_y = (H - patch_size) // stride + 1
|
458 |
+
num_patches_x = (W - patch_size) // stride + 1
|
459 |
+
|
460 |
+
y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
|
461 |
+
x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
|
462 |
+
|
463 |
+
for y in range(y_start, y_start + num_patches_y * stride, stride):
|
464 |
+
for x in range(x_start, x_start + num_patches_x * stride, stride):
|
465 |
+
patch = image.crop((x, y, x + patch_size, y + patch_size))
|
466 |
+
patches.append(patch)
|
467 |
+
|
468 |
+
return patches
|
469 |
+
|
470 |
+
|
471 |
+
def process_highres_image_crop_split(image, data_args, processor=None):
|
472 |
+
crop_resolution = data_args.image_crop_resolution
|
473 |
+
split_resolution = data_args.image_split_resolution
|
474 |
+
if processor is None:
|
475 |
+
processor = data_args.image_processor
|
476 |
+
image_crop = resize_and_center_crop(image, crop_resolution)
|
477 |
+
image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
|
478 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
479 |
+
return torch.stack(image_patches, dim=0)
|
480 |
+
|
481 |
+
|
482 |
+
def process_highres_image(image, processor, grid_pinpoints):
|
483 |
+
grid_params = [int(x) for x in grid_pinpoints.split(",")]
|
484 |
+
width_height = max(image.size)
|
485 |
+
fit_grid_params = [x for x in grid_params if x >= width_height]
|
486 |
+
if len(fit_grid_params) == 0:
|
487 |
+
select_size = max(grid_params)
|
488 |
+
else:
|
489 |
+
select_size = min(fit_grid_params)
|
490 |
+
# FIXME: always select the 448
|
491 |
+
select_size = max(grid_params)
|
492 |
+
image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
|
493 |
+
|
494 |
+
# FIXME: this seems to be a bug that it always resizes instead of padding
|
495 |
+
image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
|
496 |
+
image_padded = image_padded.resize((select_size, select_size))
|
497 |
+
image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
|
498 |
+
image_patches = [image_original_resize] + image_patches
|
499 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
500 |
+
return torch.stack(image_patches, dim=0)
|
501 |
+
|
502 |
+
|
503 |
+
def select_best_resolution(original_size, possible_resolutions, max_resolutions, patch_size):
|
504 |
+
"""
|
505 |
+
Selects the best resolution from a list of possible resolutions based on the original size.
|
506 |
+
|
507 |
+
Args:
|
508 |
+
original_size (tuple): The original size of the image in the format (width, height).
|
509 |
+
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
|
510 |
+
|
511 |
+
Returns:
|
512 |
+
tuple: The best fit resolution in the format (width, height).
|
513 |
+
"""
|
514 |
+
original_width, original_height = original_size
|
515 |
+
best_fit = None
|
516 |
+
max_effective_resolution = 0
|
517 |
+
min_wasted_resolution = float("inf")
|
518 |
+
|
519 |
+
for width, height in possible_resolutions:
|
520 |
+
if max_resolutions != None and (width * height != patch_size * patch_size):
|
521 |
+
if (width * height+patch_size*patch_size) > max_resolutions: # NOTE 要算一个global
|
522 |
+
continue
|
523 |
+
# Calculate the downscaled size to keep the aspect ratio
|
524 |
+
scale = min(width / original_width, height / original_height)
|
525 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
526 |
+
|
527 |
+
# Calculate effective and wasted resolutions
|
528 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
529 |
+
wasted_resolution = (width * height) - effective_resolution
|
530 |
+
|
531 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
532 |
+
max_effective_resolution = effective_resolution
|
533 |
+
min_wasted_resolution = wasted_resolution
|
534 |
+
best_fit = (width, height)
|
535 |
+
|
536 |
+
# print(f"original_size={original_size}, possible_resolutions={possible_resolutions}, max_resolutions={max_resolutions}, best_fit={best_fit}")
|
537 |
+
assert best_fit is not None, f"Can't find suitable fit in {possible_resolutions} at max:{max_resolutions}"
|
538 |
+
return best_fit
|
539 |
+
|
540 |
+
|
541 |
+
def resize_and_pad_image(image, target_resolution):
|
542 |
+
"""
|
543 |
+
Resize and pad an image to a target resolution while maintaining aspect ratio.
|
544 |
+
|
545 |
+
Args:
|
546 |
+
image (PIL.Image.Image): The input image.
|
547 |
+
target_resolution (tuple): The target resolution (width, height) of the image.
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
PIL.Image.Image: The resized and padded image.
|
551 |
+
"""
|
552 |
+
original_width, original_height = image.size
|
553 |
+
target_width, target_height = target_resolution
|
554 |
+
|
555 |
+
# Determine which dimension (width or height) to fill
|
556 |
+
scale_w = target_width / original_width
|
557 |
+
scale_h = target_height / original_height
|
558 |
+
|
559 |
+
if scale_w < scale_h:
|
560 |
+
# Width will be filled completely
|
561 |
+
new_width = target_width
|
562 |
+
new_height = min(math.ceil(original_height * scale_w), target_height)
|
563 |
+
else:
|
564 |
+
# Height will be filled completely
|
565 |
+
new_height = target_height
|
566 |
+
new_width = min(math.ceil(original_width * scale_h), target_width)
|
567 |
+
|
568 |
+
# Resize the image
|
569 |
+
resized_image = image.resize((new_width, new_height))
|
570 |
+
|
571 |
+
# Create a new image with the target size and paste the resized image onto it
|
572 |
+
new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
|
573 |
+
paste_x = (target_width - new_width) // 2
|
574 |
+
paste_y = (target_height - new_height) // 2
|
575 |
+
new_image.paste(resized_image, (paste_x, paste_y))
|
576 |
+
|
577 |
+
return new_image
|
578 |
+
|
579 |
+
|
580 |
+
def divide_to_patches(image, patch_size):
|
581 |
+
"""
|
582 |
+
Divides an image into patches of a specified size.
|
583 |
+
|
584 |
+
Args:
|
585 |
+
image (PIL.Image.Image): The input image.
|
586 |
+
patch_size (int): The size of each patch.
|
587 |
+
|
588 |
+
Returns:
|
589 |
+
list: A list of PIL.Image.Image objects representing the patches.
|
590 |
+
"""
|
591 |
+
patches = []
|
592 |
+
width, height = image.size
|
593 |
+
for i in range(0, height, patch_size):
|
594 |
+
for j in range(0, width, patch_size):
|
595 |
+
box = (j, i, j + patch_size, i + patch_size)
|
596 |
+
patch = image.crop(box)
|
597 |
+
patches.append(patch)
|
598 |
+
|
599 |
+
return patches
|
600 |
+
|
601 |
+
|
602 |
+
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size, max_resolutions=None):
|
603 |
+
"""
|
604 |
+
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
|
605 |
+
|
606 |
+
Args:
|
607 |
+
image_size (tuple): The size of the input image in the format (width, height).
|
608 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
609 |
+
patch_size (int): The size of each image patch.
|
610 |
+
|
611 |
+
Returns:
|
612 |
+
tuple: The shape of the image patch grid in the format (width, height).
|
613 |
+
"""
|
614 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
615 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
616 |
+
# Use regex to extract the range from the input string
|
617 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
618 |
+
range_start = tuple(map(int, matches[0]))
|
619 |
+
range_end = tuple(map(int, matches[-1]))
|
620 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
621 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
622 |
+
# Multiply all elements by patch_size
|
623 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
624 |
+
if type(grid_pinpoints) is list:
|
625 |
+
possible_resolutions = grid_pinpoints
|
626 |
+
else:
|
627 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
628 |
+
width, height = select_best_resolution(image_size, possible_resolutions, max_resolutions=max_resolutions, patch_size=patch_size)
|
629 |
+
|
630 |
+
# print("get width/patch size", width, patch_size, flush=True)
|
631 |
+
|
632 |
+
return width // patch_size, height // patch_size
|
633 |
+
|
634 |
+
|
635 |
+
def process_anyres_image(image, processor, grid_pinpoints):
|
636 |
+
"""
|
637 |
+
Process an image with variable resolutions.
|
638 |
+
|
639 |
+
Args:
|
640 |
+
image (PIL.Image.Image): The input image to be processed.
|
641 |
+
processor: The image processor object.
|
642 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
643 |
+
|
644 |
+
Returns:
|
645 |
+
torch.Tensor: A tensor containing the processed image patches.
|
646 |
+
"""
|
647 |
+
raise NotImplementedError
|
648 |
+
# Convert grid_pinpoints from string to list
|
649 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
650 |
+
try:
|
651 |
+
patch_size = processor.size[0]
|
652 |
+
except Exception as e:
|
653 |
+
patch_size = processor.size["shortest_edge"]
|
654 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
655 |
+
# Use regex to extract the range from the input string
|
656 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
657 |
+
range_start = tuple(map(int, matches[0]))
|
658 |
+
range_end = tuple(map(int, matches[-1]))
|
659 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
660 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
661 |
+
# Multiply all elements by patch_size
|
662 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
663 |
+
|
664 |
+
if type(grid_pinpoints) is list:
|
665 |
+
possible_resolutions = grid_pinpoints
|
666 |
+
else:
|
667 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
668 |
+
best_resolution = select_best_resolution(image.size, possible_resolutions)
|
669 |
+
image_padded = resize_and_pad_image(image, best_resolution)
|
670 |
+
|
671 |
+
patches = divide_to_patches(image_padded, processor.crop_size["height"])
|
672 |
+
|
673 |
+
# FIXME: this seems to be a bug that it resizes instead of pad.
|
674 |
+
# but to keep it consistent with previous, i will keep it as it is
|
675 |
+
# TODO: uncomment below to ablate with the padding
|
676 |
+
if isinstance(processor.size, dict):
|
677 |
+
shortest_edge = processor.size["shortest_edge"]
|
678 |
+
else:
|
679 |
+
shortest_edge = min(processor.size)
|
680 |
+
image_original_resize = image.resize((shortest_edge, shortest_edge))
|
681 |
+
# image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
682 |
+
# image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
683 |
+
|
684 |
+
image_patches = [image_original_resize] + patches
|
685 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
686 |
+
|
687 |
+
# print("image.size", image.size, "len(image_patches):", len(image_patches), "patch_size:", image_patches[0].shape)
|
688 |
+
return torch.stack(image_patches, dim=0)
|
689 |
+
|
690 |
+
def process_anyres_image_nopad(image, processor, grid_pinpoints):
|
691 |
+
"""
|
692 |
+
Process an image with variable resolutions.
|
693 |
+
|
694 |
+
Args:
|
695 |
+
image (PIL.Image.Image): The input image to be processed.
|
696 |
+
processor: The image processor object.
|
697 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
698 |
+
|
699 |
+
Returns:
|
700 |
+
torch.Tensor: A tensor containing the processed image patches.
|
701 |
+
"""
|
702 |
+
# Convert grid_pinpoints from string to list
|
703 |
+
try:
|
704 |
+
patch_size = processor.size[0]
|
705 |
+
except Exception as e:
|
706 |
+
patch_size = processor.size["shortest_edge"]
|
707 |
+
|
708 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
709 |
+
|
710 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
711 |
+
|
712 |
+
# Use regex to extract the range from the input string
|
713 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
714 |
+
range_start = tuple(map(int, matches[0]))
|
715 |
+
range_end = tuple(map(int, matches[-1]))
|
716 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
717 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
718 |
+
# Multiply all elements by patch_size
|
719 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
720 |
+
|
721 |
+
if type(grid_pinpoints) is list:
|
722 |
+
possible_resolutions = grid_pinpoints
|
723 |
+
else:
|
724 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
725 |
+
best_resolution = select_best_resolution(image.size, possible_resolutions, max_resolutions=None, patch_size=patch_size) # 目前图像无限制
|
726 |
+
# image_padded = resize_and_pad_image(image, best_resolution)
|
727 |
+
|
728 |
+
patches = divide_to_patches(image.resize(best_resolution), patch_size)
|
729 |
+
|
730 |
+
# FIXME: this seems to be a bug that it resizes instead of pad.
|
731 |
+
# but to keep it consistent with previous, i will keep it as it is
|
732 |
+
# TODO: uncomment below to ablate with the padding
|
733 |
+
if isinstance(processor.size, dict):
|
734 |
+
shortest_edge = processor.size["shortest_edge"]
|
735 |
+
else:
|
736 |
+
shortest_edge = min(processor.size)
|
737 |
+
image_original_resize = image.resize((shortest_edge, shortest_edge))
|
738 |
+
# image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
739 |
+
# image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
740 |
+
|
741 |
+
image_patches = [image_original_resize] + patches
|
742 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
743 |
+
|
744 |
+
# raise ValueError(f"image.size: {image.size} len(image_patches): {len(image_patches)}, patch_size:, {image_patches[0].shape}, possible_resolutions:, {possible_resolutions}, best: {best_resolution}")
|
745 |
+
return torch.stack(image_patches, dim=0)
|
746 |
+
|
747 |
+
|
748 |
+
def load_image_from_base64(image):
|
749 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
750 |
+
|
751 |
+
|
752 |
+
def expand2square(pil_img, background_color):
|
753 |
+
width, height = pil_img.size
|
754 |
+
if width == height:
|
755 |
+
return pil_img
|
756 |
+
elif width > height:
|
757 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
758 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
759 |
+
return result
|
760 |
+
else:
|
761 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
762 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
763 |
+
return result
|
764 |
+
|
765 |
+
|
766 |
+
def process_images(images, image_processor, model_cfg):
|
767 |
+
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
768 |
+
new_images = []
|
769 |
+
if image_aspect_ratio == "highres":
|
770 |
+
raise NotImplementedError
|
771 |
+
for image in images:
|
772 |
+
image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
773 |
+
new_images.append(image)
|
774 |
+
elif "anyres" in image_aspect_ratio:
|
775 |
+
for image in images:
|
776 |
+
if "nopad" in image_aspect_ratio:
|
777 |
+
image = process_anyres_image_nopad(image, image_processor, model_cfg.image_grid_pinpoints)
|
778 |
+
else:
|
779 |
+
image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
780 |
+
new_images.append(image)
|
781 |
+
elif image_aspect_ratio == "crop_split":
|
782 |
+
raise NotImplementedError
|
783 |
+
for image in images:
|
784 |
+
image = process_highres_image_crop_split(image, model_cfg, image_processor)
|
785 |
+
new_images.append(image)
|
786 |
+
elif image_aspect_ratio == "pad":
|
787 |
+
for image in images:
|
788 |
+
image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
|
789 |
+
image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
|
790 |
+
new_images.append(image)
|
791 |
+
else:
|
792 |
+
return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
|
793 |
+
if all(x.shape == new_images[0].shape for x in new_images):
|
794 |
+
new_images = torch.stack(new_images, dim=0)
|
795 |
+
return new_images
|
796 |
+
|
797 |
+
|
798 |
+
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
799 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
|
800 |
+
|
801 |
+
def insert_separator(X, sep):
|
802 |
+
return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
|
803 |
+
|
804 |
+
input_ids = []
|
805 |
+
offset = 0
|
806 |
+
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
807 |
+
offset = 1
|
808 |
+
input_ids.append(prompt_chunks[0][0])
|
809 |
+
|
810 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
811 |
+
input_ids.extend(x[offset:])
|
812 |
+
|
813 |
+
if return_tensors is not None:
|
814 |
+
if return_tensors == "pt":
|
815 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
816 |
+
raise ValueError(f"Unsupported tensor type: {return_tensors}")
|
817 |
+
return input_ids
|
818 |
+
|
819 |
+
|
820 |
+
def get_model_name_from_path(model_path):
|
821 |
+
model_path = model_path.strip("/")
|
822 |
+
model_paths = model_path.split("/")
|
823 |
+
if model_paths[-1].startswith("checkpoint-"):
|
824 |
+
return model_paths[-2] + "_" + model_paths[-1]
|
825 |
+
else:
|
826 |
+
return model_paths[-1]
|
827 |
+
|
828 |
+
|
829 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
830 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
831 |
+
self.keywords = keywords
|
832 |
+
self.keyword_ids = []
|
833 |
+
for keyword in keywords:
|
834 |
+
cur_keyword_ids = tokenizer(keyword).input_ids
|
835 |
+
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
836 |
+
cur_keyword_ids = cur_keyword_ids[1:]
|
837 |
+
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
838 |
+
self.tokenizer = tokenizer
|
839 |
+
self.start_len = input_ids.shape[1]
|
840 |
+
|
841 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
842 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
843 |
+
offset = min(output_ids.shape[1] - self.start_len, 3)
|
844 |
+
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
845 |
+
for keyword_id in self.keyword_ids:
|
846 |
+
if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
|
847 |
+
return True
|
848 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
849 |
+
for keyword in self.keywords:
|
850 |
+
if keyword in outputs:
|
851 |
+
return True
|
852 |
+
return False
|
.ipynb_checkpoints/modeling_qwen2_mla-checkpoint.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Tuple, Union
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from transformers.cache_utils import Cache
|
7 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
8 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
9 |
+
from transformers.processing_utils import Unpack
|
10 |
+
|
11 |
+
from transformers.models.qwen2.modeling_qwen2 import (
|
12 |
+
Qwen2Model,
|
13 |
+
Qwen2DecoderLayer,
|
14 |
+
Qwen2PreTrainedModel,
|
15 |
+
Qwen2ForCausalLM
|
16 |
+
)
|
17 |
+
from .configuration_qwen2_mla import Qwen2MLAConfig
|
18 |
+
|
19 |
+
from transformers.models.gemma2.modeling_gemma2 import (
|
20 |
+
eager_attention_forward, # for supporting softcap
|
21 |
+
logger
|
22 |
+
)
|
23 |
+
from transformers.models.deepseek_v3.modeling_deepseek_v3 import (
|
24 |
+
apply_rotary_pos_emb_interleave,
|
25 |
+
DeepseekV3RMSNorm
|
26 |
+
)
|
27 |
+
|
28 |
+
|
29 |
+
class MLAAttention(nn.Module):
|
30 |
+
"""
|
31 |
+
Modified from `transformers.models.llama.modeling_deepseek_v3.DeepseekV3Attention`
|
32 |
+
add support for attention bias and softcapping
|
33 |
+
"""
|
34 |
+
def __init__(self, config, layer_idx: int):
|
35 |
+
|
36 |
+
super().__init__()
|
37 |
+
self.config = config
|
38 |
+
self.layer_idx = layer_idx
|
39 |
+
|
40 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
41 |
+
self.attention_dropout = config.attention_dropout
|
42 |
+
self.num_heads = config.num_attention_heads
|
43 |
+
self.rope_theta = config.rope_theta
|
44 |
+
self.q_lora_rank = config.q_lora_rank
|
45 |
+
self.kv_lora_rank = config.kv_lora_rank
|
46 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
47 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
48 |
+
self.v_head_dim = config.v_head_dim
|
49 |
+
self.qk_head_dim = config.qk_head_dim
|
50 |
+
|
51 |
+
self.qk_latent_layernorm = getattr(config, "qk_latent_layernorm", True)
|
52 |
+
|
53 |
+
self.is_causal = True
|
54 |
+
if self.q_lora_rank is None:
|
55 |
+
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=config.attention_bias)
|
56 |
+
else:
|
57 |
+
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
|
58 |
+
if self.qk_latent_layernorm:
|
59 |
+
self.q_a_layernorm = DeepseekV3RMSNorm(self.q_lora_rank)
|
60 |
+
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=config.attention_bias)
|
61 |
+
|
62 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
63 |
+
config.hidden_size,
|
64 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
65 |
+
bias=config.attention_bias,
|
66 |
+
)
|
67 |
+
if self.qk_latent_layernorm:
|
68 |
+
self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
|
69 |
+
self.kv_b_proj = nn.Linear(
|
70 |
+
self.kv_lora_rank,
|
71 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
72 |
+
bias=False,
|
73 |
+
)
|
74 |
+
|
75 |
+
self.o_proj = nn.Linear(
|
76 |
+
self.num_heads * self.v_head_dim,
|
77 |
+
config.hidden_size,
|
78 |
+
bias=False,
|
79 |
+
)
|
80 |
+
|
81 |
+
self.scaling = self.qk_head_dim**-0.5
|
82 |
+
|
83 |
+
def forward(
|
84 |
+
self,
|
85 |
+
hidden_states: torch.Tensor,
|
86 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
87 |
+
attention_mask: Optional[torch.Tensor],
|
88 |
+
past_key_value: Optional[Cache] = None,
|
89 |
+
cache_position: Optional[torch.LongTensor] = None,
|
90 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
91 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
92 |
+
batch_size, seq_length = hidden_states.shape[:-1]
|
93 |
+
query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
|
94 |
+
key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
|
95 |
+
|
96 |
+
if self.q_lora_rank is None:
|
97 |
+
q_states = self.q_proj(hidden_states)
|
98 |
+
elif self.qk_latent_layernorm:
|
99 |
+
q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
100 |
+
else:
|
101 |
+
q_states = self.q_b_proj(self.q_a_proj(hidden_states))
|
102 |
+
q_states = q_states.view(query_shape).transpose(1, 2)
|
103 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
104 |
+
|
105 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
106 |
+
k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
107 |
+
|
108 |
+
if self.qk_latent_layernorm:
|
109 |
+
k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
|
110 |
+
else:
|
111 |
+
k_pass = self.kv_b_proj(k_pass).view(key_shape).transpose(1, 2)
|
112 |
+
k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
113 |
+
|
114 |
+
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
|
115 |
+
|
116 |
+
cos, sin = position_embeddings
|
117 |
+
q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
|
118 |
+
k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
|
119 |
+
|
120 |
+
query_states = torch.cat((q_pass, q_rot), dim=-1)
|
121 |
+
key_states = torch.cat((k_pass, k_rot), dim=-1)
|
122 |
+
|
123 |
+
if past_key_value is not None:
|
124 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
125 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
126 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
127 |
+
|
128 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
129 |
+
value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
|
130 |
+
|
131 |
+
attention_interface = eager_attention_forward
|
132 |
+
if self.config._attn_implementation != "eager":
|
133 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
134 |
+
logger.warning_once(
|
135 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
136 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
137 |
+
)
|
138 |
+
else:
|
139 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
140 |
+
|
141 |
+
attn_output, attn_weights = attention_interface(
|
142 |
+
self,
|
143 |
+
query_states,
|
144 |
+
key_states,
|
145 |
+
value_states,
|
146 |
+
attention_mask,
|
147 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
148 |
+
scaling=self.scaling,
|
149 |
+
softcap=getattr(self.config, "attn_logit_softcapping", None),
|
150 |
+
**kwargs,
|
151 |
+
)
|
152 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
153 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
154 |
+
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
|
155 |
+
attn_output = self.o_proj(attn_output)
|
156 |
+
return attn_output, attn_weights
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
class Qwen2MLADecoderLayer(Qwen2DecoderLayer):
|
161 |
+
"""
|
162 |
+
Qwen2 decoder layer with MLA (Multi-Head Latent Attention) instead of standard attention.
|
163 |
+
This class inherits from Qwen2DecoderLayer and only replaces the self_attn component.
|
164 |
+
"""
|
165 |
+
|
166 |
+
def __init__(self, config: Qwen2MLAConfig, layer_idx: int):
|
167 |
+
super().__init__(config, layer_idx)
|
168 |
+
# Replace the standard Qwen2 attention with MLA attention
|
169 |
+
self.self_attn = MLAAttention(config, layer_idx)
|
170 |
+
|
171 |
+
|
172 |
+
class Qwen2MLAPreTrainedModel(Qwen2PreTrainedModel):
|
173 |
+
"""
|
174 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
175 |
+
models for Qwen2 with MLA attention.
|
176 |
+
"""
|
177 |
+
|
178 |
+
config_class = Qwen2MLAConfig
|
179 |
+
_no_split_modules = ["Qwen2MLADecoderLayer"]
|
180 |
+
|
181 |
+
|
182 |
+
class Qwen2MLAModel(Qwen2MLAPreTrainedModel, Qwen2Model):
|
183 |
+
"""
|
184 |
+
The Qwen2 model with MLA attention layers.
|
185 |
+
|
186 |
+
This model inherits from both Qwen2MLAPreTrainedModel and Qwen2Model,
|
187 |
+
replacing the standard Qwen2 decoder layers with MLA-enabled ones.
|
188 |
+
"""
|
189 |
+
|
190 |
+
def __init__(self, config: Qwen2MLAConfig):
|
191 |
+
super().__init__(config)
|
192 |
+
|
193 |
+
# Replace the layers with MLA-enabled decoder layers
|
194 |
+
self.layers = nn.ModuleList(
|
195 |
+
[Qwen2MLADecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
196 |
+
)
|
197 |
+
|
198 |
+
|
199 |
+
class Qwen2MLAForCausalLM(Qwen2MLAPreTrainedModel, Qwen2ForCausalLM):
|
200 |
+
"""
|
201 |
+
The Qwen2 model with MLA attention for causal language modeling.
|
202 |
+
|
203 |
+
This model can be used for text generation tasks, providing the same
|
204 |
+
interface as Qwen2ForCausalLM but with MLA attention mechanism.
|
205 |
+
"""
|
206 |
+
|
207 |
+
def __init__(self, config: Qwen2MLAConfig):
|
208 |
+
super().__init__(config)
|
209 |
+
# Replace the base model with the MLA version
|
210 |
+
self.model = Qwen2MLAModel(config)
|
211 |
+
|
212 |
+
|
213 |
+
# Export the main classes for external use
|
214 |
+
__all__ = [
|
215 |
+
"Qwen2MLAForCausalLM",
|
216 |
+
"Qwen2MLAModel",
|
217 |
+
"Qwen2MLAPreTrainedModel",
|
218 |
+
]
|
.ipynb_checkpoints/modeling_videochat_flash-checkpoint.py
ADDED
@@ -0,0 +1,716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
from abc import ABC, abstractmethod
|
16 |
+
import re
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
import random
|
20 |
+
from typing import List, Optional, Tuple, Union, Dict
|
21 |
+
|
22 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
23 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
24 |
+
from transformers.generation.utils import GenerateOutput
|
25 |
+
|
26 |
+
from .vision_tower_builder import build_vision_tower
|
27 |
+
from .mm_projector_builder import build_vision_projector
|
28 |
+
|
29 |
+
from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
|
30 |
+
from .conversation import conv_templates, SeparatorStyle
|
31 |
+
from .mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, get_anyres_image_grid_shape, load_video
|
32 |
+
from .modeling_qwen2_mla import Qwen2MLAModel, Qwen2MLAForCausalLM
|
33 |
+
|
34 |
+
|
35 |
+
from .configuration_qwen2_mla import Qwen2MLAConfig
|
36 |
+
|
37 |
+
|
38 |
+
|
39 |
+
class LlavaMetaModel:
|
40 |
+
|
41 |
+
def __init__(self, config):
|
42 |
+
super(LlavaMetaModel, self).__init__(config)
|
43 |
+
|
44 |
+
if hasattr(config, "mm_vision_tower"):
|
45 |
+
delay_load = getattr(config, "delay_load", False)
|
46 |
+
self.vision_tower = build_vision_tower(config, delay_load=delay_load)
|
47 |
+
self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
|
48 |
+
|
49 |
+
if "unpad" in getattr(config, "mm_patch_merge_type", ""):
|
50 |
+
self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
51 |
+
if "nopad" in getattr(config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
|
52 |
+
self.frame_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
53 |
+
|
54 |
+
def get_vision_tower(self):
|
55 |
+
vision_tower = getattr(self, "vision_tower", None)
|
56 |
+
if type(vision_tower) is list:
|
57 |
+
vision_tower = vision_tower[0]
|
58 |
+
return vision_tower
|
59 |
+
|
60 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
61 |
+
vision_tower = model_args.vision_tower
|
62 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
63 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
64 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
65 |
+
mm_patch_merge_type = model_args.mm_patch_merge_type
|
66 |
+
|
67 |
+
self.config.mm_vision_tower = vision_tower
|
68 |
+
self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
|
69 |
+
|
70 |
+
if self.get_vision_tower() is None:
|
71 |
+
vision_tower = build_vision_tower(model_args)
|
72 |
+
|
73 |
+
if fsdp is not None and len(fsdp) > 0:
|
74 |
+
self.vision_tower = [vision_tower]
|
75 |
+
else:
|
76 |
+
self.vision_tower = vision_tower
|
77 |
+
else:
|
78 |
+
if fsdp is not None and len(fsdp) > 0:
|
79 |
+
vision_tower = self.vision_tower[0]
|
80 |
+
else:
|
81 |
+
vision_tower = self.vision_tower
|
82 |
+
vision_tower.load_model()
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
self.config.use_mm_proj = True
|
87 |
+
self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
|
88 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
89 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
90 |
+
self.config.mm_patch_merge_type = mm_patch_merge_type
|
91 |
+
|
92 |
+
if getattr(self, "mm_projector", None) is None:
|
93 |
+
self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
|
94 |
+
|
95 |
+
if "unpad" in mm_patch_merge_type:
|
96 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
97 |
+
self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
98 |
+
if "nopad" in getattr(self.config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
|
99 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
100 |
+
self.frame_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
101 |
+
else:
|
102 |
+
# In case it is frozen by LoRA
|
103 |
+
for p in self.mm_projector.parameters():
|
104 |
+
p.requires_grad = True
|
105 |
+
|
106 |
+
if pretrain_mm_mlp_adapter is not None:
|
107 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
|
108 |
+
|
109 |
+
def get_w(weights, keyword):
|
110 |
+
return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
|
111 |
+
|
112 |
+
if self.config.mm_projector_type =='lxh_qformer':
|
113 |
+
incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"), strict=False)
|
114 |
+
else:
|
115 |
+
incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
|
116 |
+
print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
117 |
+
|
118 |
+
|
119 |
+
class LlavaMetaForCausalLM(ABC):
|
120 |
+
|
121 |
+
@abstractmethod
|
122 |
+
def get_model(self):
|
123 |
+
pass
|
124 |
+
|
125 |
+
def get_vision_tower(self):
|
126 |
+
return self.get_model().get_vision_tower()
|
127 |
+
|
128 |
+
|
129 |
+
def encode_video_image(self, images_list, video_idx_in_batch):
|
130 |
+
# video encoder编码后按图像的connector处理
|
131 |
+
bs = len(images_list)
|
132 |
+
|
133 |
+
concat_images = []
|
134 |
+
concat_videos = []
|
135 |
+
for idx, image in enumerate(images_list):
|
136 |
+
if idx in video_idx_in_batch:
|
137 |
+
concat_videos.append(image)
|
138 |
+
else:
|
139 |
+
concat_images.append(image)
|
140 |
+
# print(concat_videos[0].shape)
|
141 |
+
has_image = len(concat_images) > 0
|
142 |
+
has_video = len(concat_videos) > 0
|
143 |
+
|
144 |
+
mm_local_num_frames = getattr(self.config, "mm_local_num_frames", -1)
|
145 |
+
assert mm_local_num_frames != -1
|
146 |
+
if has_image:
|
147 |
+
image_split_sizes = [image.shape[0] for image in concat_images]
|
148 |
+
concat_images = torch.cat([image.unsqueeze(1) for image in concat_images], dim=0)
|
149 |
+
# print("input vit image.shape:", concat_images.shape)
|
150 |
+
images_features = self.get_model().get_vision_tower()(concat_images) # B_i, N, D
|
151 |
+
images_features = torch.split(images_features, image_split_sizes)
|
152 |
+
|
153 |
+
if has_video:
|
154 |
+
video_split_sizes = [video.shape[0] // mm_local_num_frames for video in concat_videos]
|
155 |
+
concat_videos = torch.cat([video.reshape(video.shape[0] // mm_local_num_frames, mm_local_num_frames, video.shape[1], video.shape[2], video.shape[3]) for video in concat_videos], dim=0)
|
156 |
+
# print("input vit video.shape:", concat_videos.shape)
|
157 |
+
videos_features = self.get_model().get_vision_tower()(concat_videos) # B_v, N, D
|
158 |
+
videos_features = [v.reshape(-1, v.shape[-2] // mm_local_num_frames, v.shape[-1]) for v in torch.split(videos_features, video_split_sizes)]
|
159 |
+
|
160 |
+
|
161 |
+
all_videos_or_images_features = []
|
162 |
+
img_idx = 0
|
163 |
+
vid_idx = 0
|
164 |
+
|
165 |
+
for idx in range(bs):
|
166 |
+
|
167 |
+
if idx in video_idx_in_batch:
|
168 |
+
feat = self.get_model().mm_projector(videos_features[vid_idx], compress=True, local_num_frames=getattr(self.config, "mm_local_num_frames", -1))
|
169 |
+
|
170 |
+
vid_idx += 1
|
171 |
+
else:
|
172 |
+
feat = self.get_model().mm_projector(images_features[img_idx], compress=False)
|
173 |
+
img_idx += 1
|
174 |
+
# print("video_idx_in_batch:", video_idx_in_batch)
|
175 |
+
all_videos_or_images_features.append(feat)
|
176 |
+
|
177 |
+
if has_video:
|
178 |
+
assert vid_idx == len(videos_features), f"vid: {vid_idx} != {len(videos_features)}"
|
179 |
+
if has_image:
|
180 |
+
assert img_idx == len(images_features), f"img: {img_idx} != {len(images_features)}"
|
181 |
+
|
182 |
+
return all_videos_or_images_features
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
|
187 |
+
assert type(modalities) is list, modalities
|
188 |
+
|
189 |
+
vision_tower = self.get_vision_tower()
|
190 |
+
# rank_print(modalities)
|
191 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
192 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
193 |
+
|
194 |
+
if type(images) is list or images.ndim == 5:
|
195 |
+
if type(images) is list:
|
196 |
+
images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
|
197 |
+
|
198 |
+
video_idx_in_batch = []
|
199 |
+
for _ in range(len(modalities)):
|
200 |
+
if modalities[_] == "video":
|
201 |
+
video_idx_in_batch.append(_)
|
202 |
+
|
203 |
+
images_list = []
|
204 |
+
for image in images:
|
205 |
+
if image.ndim == 4:
|
206 |
+
images_list.append(image)
|
207 |
+
else:
|
208 |
+
images_list.append(image.unsqueeze(0))
|
209 |
+
|
210 |
+
|
211 |
+
vision_encode_type = getattr(self.config, "vision_encode_type", "image")
|
212 |
+
mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
|
213 |
+
image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
|
214 |
+
frame_aspect_ratio = getattr(self.config, "frame_aspect_ratio", "square")
|
215 |
+
mm_newline_position = getattr(self.config, "mm_newline_position", "nothing")
|
216 |
+
|
217 |
+
|
218 |
+
if vision_encode_type == "video_image": # video backbone, process video with compress
|
219 |
+
image_features = self.encode_video_image(images_list, video_idx_in_batch=video_idx_in_batch)
|
220 |
+
else:
|
221 |
+
raise NotImplementedError(vision_encode_type)
|
222 |
+
|
223 |
+
|
224 |
+
if mm_patch_merge_type == "flat":
|
225 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
226 |
+
elif mm_patch_merge_type.startswith("spatial"):
|
227 |
+
new_image_features = []
|
228 |
+
for image_idx, image_feature in enumerate(image_features):
|
229 |
+
|
230 |
+
if image_idx in video_idx_in_batch: # video operations
|
231 |
+
|
232 |
+
if "anyres" in frame_aspect_ratio:
|
233 |
+
raise NotImplementedError
|
234 |
+
else:
|
235 |
+
frame_feature = image_feature
|
236 |
+
|
237 |
+
if "pad" in mm_patch_merge_type:
|
238 |
+
if mm_newline_position == 'one_token':
|
239 |
+
frame_feature = frame_feature.flatten(0, 1)
|
240 |
+
if "unpad" in mm_patch_merge_type:
|
241 |
+
frame_feature = torch.cat((frame_feature, self.model.image_newline[None].to(frame_feature.device)), dim=0)
|
242 |
+
else:
|
243 |
+
frame_feature = torch.cat((frame_feature, self.model.frame_newline[None].to(frame_feature.device)), dim=0)
|
244 |
+
elif mm_newline_position == 'nothing':
|
245 |
+
frame_feature = frame_feature.flatten(0, 1)
|
246 |
+
else:
|
247 |
+
raise NotImplementedError("add pad please!!")
|
248 |
+
else:
|
249 |
+
frame_feature = frame_feature.flatten(0, 1)
|
250 |
+
|
251 |
+
# print(f"final video frame_feature.shape: {frame_feature.shape}")
|
252 |
+
image_feature = frame_feature
|
253 |
+
|
254 |
+
elif image_feature.shape[0] > 1: # multi patches and multi images operations
|
255 |
+
base_image_feature = image_feature[0]
|
256 |
+
image_feature = image_feature[1:]
|
257 |
+
origin_size = image_feature.shape
|
258 |
+
|
259 |
+
height = width = self.get_model().mm_projector.num_image_patches_per_side
|
260 |
+
assert height * width == base_image_feature.shape[0], f"height:{height}, width: {width}, base_image_feature: {base_image_feature.shape}"
|
261 |
+
|
262 |
+
if "anyres_max" in image_aspect_ratio:
|
263 |
+
matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
|
264 |
+
if matched_anyres_max_num_patches:
|
265 |
+
max_num_patches = int(matched_anyres_max_num_patches.group(1))
|
266 |
+
|
267 |
+
if "anyres" in image_aspect_ratio:
|
268 |
+
if hasattr(self.get_vision_tower(), "image_size"):
|
269 |
+
vision_tower_image_size = self.get_vision_tower().image_size
|
270 |
+
else:
|
271 |
+
raise ValueError("vision_tower_image_size is not found in the vision tower.")
|
272 |
+
try:
|
273 |
+
num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size, max_resolutions=None)
|
274 |
+
except Exception as e:
|
275 |
+
print(f"Error: {e}")
|
276 |
+
raise e
|
277 |
+
# num_patch_width, num_patch_height = 2, 2
|
278 |
+
|
279 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
280 |
+
else:
|
281 |
+
raise NotImplementedError(image_aspect_ratio)
|
282 |
+
image_feature = image_feature.view(2, 2, height, width, -1)
|
283 |
+
|
284 |
+
if "maxpool2x2" in mm_patch_merge_type:
|
285 |
+
raise NotImplementedError
|
286 |
+
elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
|
287 |
+
raise NotImplementedError
|
288 |
+
elif "unpad" in mm_patch_merge_type:
|
289 |
+
raise NotImplementedError
|
290 |
+
else:
|
291 |
+
image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
|
292 |
+
image_feature = image_feature.flatten(0, 3)
|
293 |
+
if "nobase" in mm_patch_merge_type:
|
294 |
+
pass
|
295 |
+
else:
|
296 |
+
try:
|
297 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
298 |
+
except Exception as e:
|
299 |
+
raise ValueError(f"{num_patch_width} {num_patch_height} now: base_image_feature: {base_image_feature.shape}, {image_feature.shape}, image_sizes[image_idx]: {image_sizes[image_idx]}, origin_size: {origin_size}, {image_sizes[image_idx]}, {self.config.image_grid_pinpoints}, {vision_tower_image_size}")
|
300 |
+
else: # single image operations
|
301 |
+
image_feature = image_feature[0]
|
302 |
+
if "unpad" in mm_patch_merge_type:
|
303 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
|
304 |
+
|
305 |
+
# print(f"image/video_feature.shape: {image_feature.shape}")
|
306 |
+
new_image_features.append(image_feature)
|
307 |
+
image_features = new_image_features
|
308 |
+
else:
|
309 |
+
raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
|
310 |
+
else:
|
311 |
+
# raise NotImplementedError(f"images.shape={images.shape}, modalities={modalities}")
|
312 |
+
image_features = self.encode_image(images)
|
313 |
+
|
314 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
315 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
|
316 |
+
raise NotImplementedError
|
317 |
+
# print(f"Total images len(image_features: {len(image_features)}")
|
318 |
+
|
319 |
+
# Let's just add dummy tensors if they do not exist,
|
320 |
+
# it is a headache to deal with None all the time.
|
321 |
+
# But it is not ideal, and if you have a better idea,
|
322 |
+
# please open an issue / submit a PR, thanks.
|
323 |
+
_labels = labels
|
324 |
+
_position_ids = position_ids
|
325 |
+
_attention_mask = attention_mask
|
326 |
+
if attention_mask is None:
|
327 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
328 |
+
else:
|
329 |
+
attention_mask = attention_mask.bool()
|
330 |
+
if position_ids is None:
|
331 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
332 |
+
if labels is None:
|
333 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
334 |
+
|
335 |
+
|
336 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
337 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
338 |
+
|
339 |
+
new_input_embeds = []
|
340 |
+
new_labels = []
|
341 |
+
cur_image_idx = 0
|
342 |
+
|
343 |
+
mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
|
344 |
+
|
345 |
+
if mm_llm_compress:
|
346 |
+
self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
|
347 |
+
self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
|
348 |
+
self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
|
349 |
+
first_image_token_position = []
|
350 |
+
text_prompt_lens = []
|
351 |
+
else:
|
352 |
+
self.model.llm_compress_type = "attention"
|
353 |
+
self.model.llm_compress_layer_list = []
|
354 |
+
self.model.llm_image_token_ratio_list = []
|
355 |
+
first_image_token_position = []
|
356 |
+
text_prompt_lens = []
|
357 |
+
|
358 |
+
# rank_print("Inserting Images embedding")
|
359 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
360 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
361 |
+
|
362 |
+
if mm_llm_compress:
|
363 |
+
####### copy from pdrop, only support single image/video NOTE ##################
|
364 |
+
# record image position for further dropping
|
365 |
+
image_index = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
|
366 |
+
assert len(image_index) == 1, f"Only support singe/video: {image_index}"
|
367 |
+
if image_index == []:
|
368 |
+
first_image_token_position.append(-1)
|
369 |
+
else:
|
370 |
+
first_image_token_position.append(image_index[0])
|
371 |
+
|
372 |
+
|
373 |
+
# record input instruction length in inference mode
|
374 |
+
if not self.training:
|
375 |
+
if image_index == []:
|
376 |
+
assert num_images == 0, num_images
|
377 |
+
else:
|
378 |
+
assert num_images == 1, f"num_images={num_images}"
|
379 |
+
text_prompt_lens.append(cur_input_ids.shape[0] - num_images) # consider image place holder
|
380 |
+
|
381 |
+
###############################################
|
382 |
+
|
383 |
+
# print(f"num_images={num_images}")
|
384 |
+
if num_images == 0:
|
385 |
+
cur_image_features = image_features[cur_image_idx]
|
386 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
387 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
388 |
+
new_input_embeds.append(cur_input_embeds)
|
389 |
+
new_labels.append(labels[batch_idx])
|
390 |
+
cur_image_idx += 1
|
391 |
+
continue
|
392 |
+
|
393 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
394 |
+
cur_input_ids_noim = []
|
395 |
+
cur_labels = labels[batch_idx]
|
396 |
+
cur_labels_noim = []
|
397 |
+
for i in range(len(image_token_indices) - 1):
|
398 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
399 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
400 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
401 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
402 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
403 |
+
cur_new_input_embeds = []
|
404 |
+
cur_new_labels = []
|
405 |
+
|
406 |
+
for i in range(num_images + 1):
|
407 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
408 |
+
cur_new_labels.append(cur_labels_noim[i])
|
409 |
+
if i < num_images:
|
410 |
+
try:
|
411 |
+
cur_image_features = image_features[cur_image_idx]
|
412 |
+
except IndexError:
|
413 |
+
print(f"cur_image_idx={cur_image_idx} is not ok")
|
414 |
+
cur_image_features = image_features[cur_image_idx - 1]
|
415 |
+
cur_image_idx += 1
|
416 |
+
cur_new_input_embeds.append(cur_image_features)
|
417 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
418 |
+
|
419 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
420 |
+
|
421 |
+
# import pdb; pdb.set_trace()
|
422 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
423 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
424 |
+
|
425 |
+
new_input_embeds.append(cur_new_input_embeds)
|
426 |
+
new_labels.append(cur_new_labels)
|
427 |
+
|
428 |
+
|
429 |
+
if mm_llm_compress:
|
430 |
+
self.model.first_image_token_position = first_image_token_position
|
431 |
+
self.model.text_prompt_lens = text_prompt_lens
|
432 |
+
self.model.num_image_token_lens = [image_feature.shape[0] for image_feature in image_features]
|
433 |
+
|
434 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
435 |
+
tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
|
436 |
+
# rank_print("Finishing Inserting")
|
437 |
+
|
438 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
439 |
+
new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
440 |
+
|
441 |
+
# Combine them
|
442 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
443 |
+
batch_size = len(new_input_embeds)
|
444 |
+
|
445 |
+
new_input_embeds_padded = []
|
446 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
447 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
448 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
449 |
+
# print("Prepare pos id")
|
450 |
+
|
451 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
452 |
+
cur_len = cur_new_embed.shape[0]
|
453 |
+
if getattr(self.config, "tokenizer_padding_side", "right") == "left":
|
454 |
+
new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
|
455 |
+
if cur_len > 0:
|
456 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
457 |
+
attention_mask[i, -cur_len:] = True
|
458 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
459 |
+
else:
|
460 |
+
new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
|
461 |
+
if cur_len > 0:
|
462 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
463 |
+
attention_mask[i, :cur_len] = True
|
464 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
465 |
+
|
466 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
467 |
+
# print("tokenizer padding")
|
468 |
+
|
469 |
+
if _labels is None:
|
470 |
+
new_labels = None
|
471 |
+
else:
|
472 |
+
new_labels = new_labels_padded
|
473 |
+
|
474 |
+
if _attention_mask is None:
|
475 |
+
attention_mask = None
|
476 |
+
else:
|
477 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
478 |
+
|
479 |
+
if _position_ids is None:
|
480 |
+
position_ids = None
|
481 |
+
if getattr(self.config, "use_pos_skipping", False) and self.training:
|
482 |
+
position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
|
483 |
+
split_position = random.randint(0, new_input_embeds.size(1))
|
484 |
+
left_add = random.randint(0, self.config.pos_skipping_range)
|
485 |
+
right_add = random.randint(left_add, self.config.pos_skipping_range)
|
486 |
+
position_ids[:, :split_position] += left_add
|
487 |
+
position_ids[:, split_position:] += right_add
|
488 |
+
# import pdb; pdb.set_trace()
|
489 |
+
# print("Finish preparing")
|
490 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
491 |
+
|
492 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer):
|
493 |
+
if model_args.mm_use_im_patch_token:
|
494 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
495 |
+
self.resize_token_embeddings(len(tokenizer))
|
496 |
+
|
497 |
+
if model_args.mm_use_im_start_end:
|
498 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
499 |
+
self.resize_token_embeddings(len(tokenizer))
|
500 |
+
|
501 |
+
if num_new_tokens > 0:
|
502 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
503 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
504 |
+
|
505 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
506 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
507 |
+
|
508 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
509 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
510 |
+
|
511 |
+
if model_args.tune_mm_mlp_adapter:
|
512 |
+
for p in self.get_input_embeddings().parameters():
|
513 |
+
p.requires_grad = True
|
514 |
+
for p in self.get_output_embeddings().parameters():
|
515 |
+
p.requires_grad = False
|
516 |
+
|
517 |
+
if model_args.pretrain_mm_mlp_adapter:
|
518 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
|
519 |
+
embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
|
520 |
+
assert num_new_tokens == 2
|
521 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
522 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
523 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
524 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
525 |
+
else:
|
526 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
527 |
+
elif model_args.mm_use_im_patch_token:
|
528 |
+
if model_args.tune_mm_mlp_adapter:
|
529 |
+
for p in self.get_input_embeddings().parameters():
|
530 |
+
p.requires_grad = False
|
531 |
+
for p in self.get_output_embeddings().parameters():
|
532 |
+
p.requires_grad = False
|
533 |
+
|
534 |
+
|
535 |
+
|
536 |
+
class VideoChatFlashQwenConfig(Qwen2MLAConfig):
|
537 |
+
model_type = "videochat_flash_qwen"
|
538 |
+
|
539 |
+
|
540 |
+
class VideoChatFlashQwenModel(LlavaMetaModel, Qwen2MLAModel):
|
541 |
+
config_class = VideoChatFlashQwenConfig
|
542 |
+
|
543 |
+
def __init__(self, config: VideoChatFlashQwenConfig):
|
544 |
+
super(VideoChatFlashQwenModel, self).__init__(config)
|
545 |
+
|
546 |
+
|
547 |
+
class VideoChatFlashQwenForCausalLM(LlavaMetaForCausalLM, Qwen2MLAForCausalLM):
|
548 |
+
config_class = VideoChatFlashQwenConfig
|
549 |
+
|
550 |
+
def __init__(self, config):
|
551 |
+
# super(Qwen2MLAForCausalLM, self).__init__(config)
|
552 |
+
Qwen2MLAForCausalLM.__init__(self, config)
|
553 |
+
config.model_type = "videochat_flash_qwen"
|
554 |
+
# config.rope_scaling = None
|
555 |
+
|
556 |
+
self.model = VideoChatFlashQwenModel(config)
|
557 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
558 |
+
# Initialize weights and apply final processing
|
559 |
+
self.post_init()
|
560 |
+
|
561 |
+
def get_model(self):
|
562 |
+
return self.model
|
563 |
+
|
564 |
+
def forward(
|
565 |
+
self,
|
566 |
+
input_ids: torch.LongTensor = None,
|
567 |
+
attention_mask: Optional[torch.Tensor] = None,
|
568 |
+
position_ids: Optional[torch.LongTensor] = None,
|
569 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
570 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
571 |
+
labels: Optional[torch.LongTensor] = None,
|
572 |
+
use_cache: Optional[bool] = None,
|
573 |
+
output_attentions: Optional[bool] = None,
|
574 |
+
output_hidden_states: Optional[bool] = None,
|
575 |
+
images: Optional[torch.FloatTensor] = None,
|
576 |
+
image_sizes: Optional[List[List[int]]] = None,
|
577 |
+
return_dict: Optional[bool] = None,
|
578 |
+
modalities: Optional[List[str]] = ["image"],
|
579 |
+
dpo_forward: Optional[bool] = False,
|
580 |
+
cache_position=None,
|
581 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
582 |
+
|
583 |
+
if inputs_embeds is None:
|
584 |
+
(input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
|
585 |
+
|
586 |
+
# print("inputs_embeds.shape:", inputs_embeds.shape)
|
587 |
+
if dpo_forward:
|
588 |
+
raise NotImplementedError
|
589 |
+
else:
|
590 |
+
return super().forward(
|
591 |
+
input_ids=input_ids,
|
592 |
+
attention_mask=attention_mask,
|
593 |
+
position_ids=position_ids,
|
594 |
+
past_key_values=past_key_values,
|
595 |
+
inputs_embeds=inputs_embeds,
|
596 |
+
labels=labels,
|
597 |
+
use_cache=use_cache,
|
598 |
+
output_attentions=output_attentions,
|
599 |
+
output_hidden_states=output_hidden_states,
|
600 |
+
return_dict=return_dict,
|
601 |
+
)
|
602 |
+
|
603 |
+
@torch.no_grad()
|
604 |
+
def generate(
|
605 |
+
self,
|
606 |
+
inputs: Optional[torch.Tensor] = None,
|
607 |
+
images: Optional[torch.Tensor] = None,
|
608 |
+
image_sizes: Optional[torch.Tensor] = None,
|
609 |
+
modalities: Optional[List[str]] = ["image"],
|
610 |
+
**kwargs,
|
611 |
+
) -> Union[GenerateOutput, torch.LongTensor]:
|
612 |
+
position_ids = kwargs.pop("position_ids", None)
|
613 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
614 |
+
if "inputs_embeds" in kwargs:
|
615 |
+
raise NotImplementedError("`inputs_embeds` is not supported")
|
616 |
+
|
617 |
+
if images is not None:
|
618 |
+
(inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
|
619 |
+
else:
|
620 |
+
self.model.image_token_posi = [-1]
|
621 |
+
self.model.prompt_len = None
|
622 |
+
self.model.image_tokens = [0]
|
623 |
+
inputs_embeds = self.get_model().embed_tokens(inputs)
|
624 |
+
|
625 |
+
return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
|
626 |
+
|
627 |
+
@torch.no_grad()
|
628 |
+
def chat(self,
|
629 |
+
video_path,
|
630 |
+
tokenizer,
|
631 |
+
user_prompt,
|
632 |
+
chat_history=None,
|
633 |
+
return_history=True,
|
634 |
+
max_num_frames=512,
|
635 |
+
media_dict=None,
|
636 |
+
generation_config={}):
|
637 |
+
|
638 |
+
frames, time_msg = load_video(video_path, max_num_frames=max_num_frames, media_dict=media_dict)
|
639 |
+
|
640 |
+
image_sizes = [frames[0].shape[:2]]
|
641 |
+
|
642 |
+
frames = [self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.dtype).cuda()]
|
643 |
+
|
644 |
+
conv = conv_templates["qwen_2"].copy()
|
645 |
+
|
646 |
+
if chat_history is None or len(chat_history) == 0:
|
647 |
+
user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{time_msg.strip()} {user_prompt}'
|
648 |
+
else:
|
649 |
+
assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
|
650 |
+
for msg in chat_history:
|
651 |
+
conv.append_message(msg['role'], msg['content'])
|
652 |
+
|
653 |
+
conv.append_message(conv.roles[0], user_prompt)
|
654 |
+
conv.append_message(conv.roles[1], None)
|
655 |
+
|
656 |
+
prompt = conv.get_prompt()
|
657 |
+
|
658 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
|
659 |
+
|
660 |
+
if tokenizer.pad_token_id is None:
|
661 |
+
if "qwen" in tokenizer.name_or_path.lower():
|
662 |
+
print("Setting pad token to bos token for qwen model.")
|
663 |
+
tokenizer.pad_token_id = 151643
|
664 |
+
|
665 |
+
attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
|
666 |
+
|
667 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
668 |
+
keywords = [stop_str]
|
669 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
670 |
+
|
671 |
+
with torch.inference_mode():
|
672 |
+
output_ids = self.generate(
|
673 |
+
inputs=input_ids,
|
674 |
+
images=frames,
|
675 |
+
attention_mask=attention_masks,
|
676 |
+
modalities=["video"],
|
677 |
+
image_sizes=image_sizes,
|
678 |
+
use_cache=True,
|
679 |
+
stopping_criteria=[stopping_criteria],
|
680 |
+
**generation_config
|
681 |
+
)
|
682 |
+
|
683 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
684 |
+
if outputs.endswith(stop_str):
|
685 |
+
outputs = outputs[: -len(stop_str)]
|
686 |
+
|
687 |
+
outputs = outputs.strip()
|
688 |
+
|
689 |
+
# print(f"\033[91m== Question: \033[0m\n{prompt}\n")
|
690 |
+
# print(f"\033[91m== Response: \033[0m\n{outputs}\n")
|
691 |
+
|
692 |
+
if chat_history is None:
|
693 |
+
chat_history = []
|
694 |
+
|
695 |
+
chat_history.append({"role":conv.roles[0], "content":user_prompt})
|
696 |
+
chat_history.append({"role":conv.roles[1], "content":outputs})
|
697 |
+
if return_history:
|
698 |
+
return outputs, chat_history
|
699 |
+
else:
|
700 |
+
return outputs
|
701 |
+
|
702 |
+
|
703 |
+
|
704 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
705 |
+
images = kwargs.pop("images", None)
|
706 |
+
image_sizes = kwargs.pop("image_sizes", None)
|
707 |
+
inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
|
708 |
+
if images is not None:
|
709 |
+
inputs["images"] = images
|
710 |
+
if image_sizes is not None:
|
711 |
+
inputs["image_sizes"] = image_sizes
|
712 |
+
return inputs
|
713 |
+
|
714 |
+
|
715 |
+
AutoConfig.register("videochat_flash_qwen", VideoChatFlashQwenConfig)
|
716 |
+
AutoModelForCausalLM.register(VideoChatFlashQwenConfig, VideoChatFlashQwenForCausalLM)
|
.ipynb_checkpoints/test-checkpoint.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModel, AutoTokenizer
|
2 |
+
import torch
|
3 |
+
from modeling_videochat_flash import VideoChatFlashQwenForCausalLM
|
4 |
+
|
5 |
+
# model setting
|
6 |
+
model_path = './'
|
7 |
+
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
9 |
+
model = VideoChatFlashQwenForCausalLM.from_pretrained(model_path).to(torch.bfloat16).cuda()
|
10 |
+
image_processor = model.get_vision_tower().image_processor
|
11 |
+
|
12 |
+
mm_llm_compress = False # use the global compress or not
|
13 |
+
if mm_llm_compress:
|
14 |
+
model.config.mm_llm_compress = True
|
15 |
+
model.config.llm_compress_type = "uniform0_attention"
|
16 |
+
model.config.llm_compress_layer_list = [4, 18]
|
17 |
+
model.config.llm_image_token_ratio_list = [1, 0.75, 0.25]
|
18 |
+
else:
|
19 |
+
model.config.mm_llm_compress = False
|
20 |
+
|
21 |
+
# evaluation setting
|
22 |
+
max_num_frames = 512
|
23 |
+
generation_config = dict(
|
24 |
+
do_sample=False,
|
25 |
+
temperature=0.0,
|
26 |
+
max_new_tokens=1024,
|
27 |
+
top_p=0.1,
|
28 |
+
num_beams=1
|
29 |
+
)
|
30 |
+
|
31 |
+
video_path = "test.mp4"
|
32 |
+
|
33 |
+
# single-turn conversation
|
34 |
+
question1 = "Describe this video in detail."
|
35 |
+
output1, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question1, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
|
36 |
+
|
37 |
+
print(output1)
|
38 |
+
|
39 |
+
# # multi-turn conversation
|
40 |
+
# question2 = "How many people appear in the video?"
|
41 |
+
# output2, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question2, chat_history=chat_history, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
|
42 |
+
|
43 |
+
# print(output2)
|
.ipynb_checkpoints/tokenizer-checkpoint.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:540b7fbf60b80e8293593a86960df91d2263723d69107ffc1afc89a7c08cda12
|
3 |
+
size 11422162
|
Untitled.ipynb
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 7,
|
6 |
+
"id": "64f33f31-f533-41e8-9821-940a5d2ea343",
|
7 |
+
"metadata": {
|
8 |
+
"tags": []
|
9 |
+
},
|
10 |
+
"outputs": [
|
11 |
+
{
|
12 |
+
"name": "stdout",
|
13 |
+
"output_type": "stream",
|
14 |
+
"text": [
|
15 |
+
"Inspecting file: model-00001-of-00004.safetensors\n",
|
16 |
+
"Available keys (tensor names):\n",
|
17 |
+
"\n",
|
18 |
+
"Key: model.layers.0.input_layernorm.weight\n",
|
19 |
+
" Shape: torch.Size([3584])\n",
|
20 |
+
" Dtype: torch.bfloat16\n",
|
21 |
+
" Size: 3584 elements\n",
|
22 |
+
" First few elements: [0.275390625, 0.3046875, 0.26171875, 0.291015625, 0.29296875]\n",
|
23 |
+
"\n",
|
24 |
+
"Key: model.layers.0.mlp.down_proj.weight\n",
|
25 |
+
" Shape: torch.Size([3584, 18944])\n",
|
26 |
+
" Dtype: torch.bfloat16\n",
|
27 |
+
" Size: 67895296 elements\n",
|
28 |
+
" First few elements: [-0.005096435546875, 0.01385498046875, 0.0096435546875, -0.00848388671875, -0.002593994140625]\n",
|
29 |
+
"\n",
|
30 |
+
"Key: model.layers.0.mlp.gate_proj.weight\n",
|
31 |
+
" Shape: torch.Size([18944, 3584])\n",
|
32 |
+
" Dtype: torch.bfloat16\n",
|
33 |
+
" Size: 67895296 elements\n",
|
34 |
+
" First few elements: [0.00286865234375, -0.0201416015625, -0.0216064453125, 0.006622314453125, -0.015625]\n",
|
35 |
+
"\n",
|
36 |
+
"Key: model.layers.0.mlp.up_proj.weight\n",
|
37 |
+
" Shape: torch.Size([18944, 3584])\n",
|
38 |
+
" Dtype: torch.bfloat16\n",
|
39 |
+
" Size: 67895296 elements\n",
|
40 |
+
" First few elements: [0.007537841796875, -0.0111083984375, -0.0024261474609375, -0.006927490234375, -0.02587890625]\n",
|
41 |
+
"\n",
|
42 |
+
"Key: model.layers.0.post_attention_layernorm.weight\n",
|
43 |
+
" Shape: torch.Size([3584])\n",
|
44 |
+
" Dtype: torch.bfloat16\n",
|
45 |
+
" Size: 3584 elements\n",
|
46 |
+
" First few elements: [0.28515625, 0.33203125, 0.259765625, 0.236328125, 0.296875]\n",
|
47 |
+
"\n",
|
48 |
+
"Key: model.layers.0.self_attn.kv_a_proj_with_mqa.bias\n",
|
49 |
+
" Shape: torch.Size([576])\n",
|
50 |
+
" Dtype: torch.bfloat16\n",
|
51 |
+
" Size: 576 elements\n",
|
52 |
+
" First few elements: [3.953125, 0.0634765625, 1.2578125, -1.515625, 0.29296875]\n",
|
53 |
+
"\n",
|
54 |
+
"Key: model.layers.0.self_attn.kv_a_proj_with_mqa.weight\n",
|
55 |
+
" Shape: torch.Size([576, 3584])\n",
|
56 |
+
" Dtype: torch.bfloat16\n",
|
57 |
+
" Size: 2064384 elements\n",
|
58 |
+
" First few elements: [0.0322265625, -0.005157470703125, -0.03173828125, 0.0184326171875, -0.015625]\n",
|
59 |
+
"\n",
|
60 |
+
"Key: model.layers.0.self_attn.kv_b_proj.weight\n",
|
61 |
+
" Shape: torch.Size([7168, 512])\n",
|
62 |
+
" Dtype: torch.bfloat16\n",
|
63 |
+
" Size: 3670016 elements\n",
|
64 |
+
" First few elements: [-0.04931640625, -0.01904296875, 0.080078125, -0.01324462890625, 0.0179443359375]\n",
|
65 |
+
"\n",
|
66 |
+
"Key: model.layers.0.self_attn.o_proj.weight\n",
|
67 |
+
" Shape: torch.Size([3584, 3584])\n",
|
68 |
+
" Dtype: torch.bfloat16\n",
|
69 |
+
" Size: 12845056 elements\n",
|
70 |
+
" First few elements: [0.00323486328125, -0.030029296875, -0.0069580078125, 0.0089111328125, 0.007568359375]\n",
|
71 |
+
"\n",
|
72 |
+
"Key: model.layers.0.self_attn.q_proj.bias\n",
|
73 |
+
" Shape: torch.Size([5376])\n",
|
74 |
+
" Dtype: torch.bfloat16\n",
|
75 |
+
" Size: 5376 elements\n",
|
76 |
+
" First few elements: [0.5, 2.140625, -0.98046875, 1.3671875, 1.015625]\n",
|
77 |
+
"\n",
|
78 |
+
"Key: model.layers.0.self_attn.q_proj.weight\n",
|
79 |
+
" Shape: torch.Size([5376, 3584])\n",
|
80 |
+
" Dtype: torch.bfloat16\n",
|
81 |
+
" Size: 19267584 elements\n",
|
82 |
+
" First few elements: [-0.0003452301025390625, -0.005340576171875, 0.021484375, 0.003997802734375, -0.00274658203125]\n"
|
83 |
+
]
|
84 |
+
}
|
85 |
+
],
|
86 |
+
"source": [
|
87 |
+
"from safetensors import safe_open\n",
|
88 |
+
"\n",
|
89 |
+
"def inspect_safetensors(file_path):\n",
|
90 |
+
" print(f\"Inspecting file: {file_path}\")\n",
|
91 |
+
" with safe_open(file_path, framework=\"pt\", device=\"cpu\") as f:\n",
|
92 |
+
" print(\"Available keys (tensor names):\")\n",
|
93 |
+
" for key in f.keys():\n",
|
94 |
+
" if 'model.layers.0' in key:\n",
|
95 |
+
" \n",
|
96 |
+
" tensor = f.get_tensor(key)\n",
|
97 |
+
" print(f\"\\nKey: {key}\")\n",
|
98 |
+
" print(f\" Shape: {tensor.shape}\")\n",
|
99 |
+
" print(f\" Dtype: {tensor.dtype}\")\n",
|
100 |
+
" print(f\" Size: {tensor.numel()} elements\")\n",
|
101 |
+
" # 可选:显示前几个元素\n",
|
102 |
+
" print(f\" First few elements: {tensor.flatten()[:5].tolist()}\")\n",
|
103 |
+
"\n",
|
104 |
+
"# 示例路径,请替换为你自己的 .safetensors 文件路径\n",
|
105 |
+
"file_path = \"model-00001-of-00004.safetensors\"\n",
|
106 |
+
"inspect_safetensors(file_path)"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
{
|
110 |
+
"cell_type": "code",
|
111 |
+
"execution_count": 2,
|
112 |
+
"id": "2a331ae6-f4ca-4d16-8bbf-36f39b9ac43e",
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"ename": "Exception",
|
117 |
+
"evalue": "data did not match any variant of untagged enum ModelWrapper at line 757455 column 3",
|
118 |
+
"output_type": "error",
|
119 |
+
"traceback": [
|
120 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
121 |
+
"\u001b[0;31mException\u001b[0m Traceback (most recent call last)",
|
122 |
+
"Cell \u001b[0;32mIn[2], line 8\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[38;5;66;03m# model setting\u001b[39;00m\n\u001b[1;32m 6\u001b[0m model_path \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m./\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m----> 8\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m \u001b[43mAutoTokenizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmodel_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtrust_remote_code\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m)\u001b[49m\n\u001b[1;32m 9\u001b[0m model \u001b[38;5;241m=\u001b[39m VideoChatFlashQwenForCausalLM\u001b[38;5;241m.\u001b[39mfrom_pretrained(model_path)\u001b[38;5;241m.\u001b[39mto(torch\u001b[38;5;241m.\u001b[39mbfloat16)\u001b[38;5;241m.\u001b[39mcuda()\n\u001b[1;32m 10\u001b[0m image_processor \u001b[38;5;241m=\u001b[39m model\u001b[38;5;241m.\u001b[39mget_vision_tower()\u001b[38;5;241m.\u001b[39mimage_processor\n",
|
123 |
+
"File \u001b[0;32m/opt/conda/envs/vcflash/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py:837\u001b[0m, in \u001b[0;36mAutoTokenizer.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *inputs, **kwargs)\u001b[0m\n\u001b[1;32m 833\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m tokenizer_class \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 834\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m 835\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTokenizer class \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mtokenizer_class_candidate\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m does not exist or is not currently imported.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 836\u001b[0m )\n\u001b[0;32m--> 837\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtokenizer_class\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 839\u001b[0m \u001b[38;5;66;03m# Otherwise we have to be creative.\u001b[39;00m\n\u001b[1;32m 840\u001b[0m \u001b[38;5;66;03m# if model is an encoder decoder, the encoder tokenizer class is used by default\u001b[39;00m\n\u001b[1;32m 841\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(config, EncoderDecoderConfig):\n",
|
124 |
+
"File \u001b[0;32m/opt/conda/envs/vcflash/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:2086\u001b[0m, in \u001b[0;36mPreTrainedTokenizerBase.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, cache_dir, force_download, local_files_only, token, revision, trust_remote_code, *init_inputs, **kwargs)\u001b[0m\n\u001b[1;32m 2083\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 2084\u001b[0m logger\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mloading file \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfile_path\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m from cache at \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresolved_vocab_files[file_id]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m-> 2086\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_from_pretrained\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2087\u001b[0m \u001b[43m \u001b[49m\u001b[43mresolved_vocab_files\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2088\u001b[0m \u001b[43m \u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2089\u001b[0m \u001b[43m \u001b[49m\u001b[43minit_configuration\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2090\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minit_inputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2091\u001b[0m \u001b[43m \u001b[49m\u001b[43mtoken\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtoken\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2092\u001b[0m \u001b[43m \u001b[49m\u001b[43mcache_dir\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcache_dir\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2093\u001b[0m \u001b[43m \u001b[49m\u001b[43mlocal_files_only\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mlocal_files_only\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2094\u001b[0m \u001b[43m \u001b[49m\u001b[43m_commit_hash\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcommit_hash\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2095\u001b[0m \u001b[43m \u001b[49m\u001b[43m_is_local\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mis_local\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2096\u001b[0m \u001b[43m \u001b[49m\u001b[43mtrust_remote_code\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtrust_remote_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2097\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2098\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
|
125 |
+
"File \u001b[0;32m/opt/conda/envs/vcflash/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:2325\u001b[0m, in \u001b[0;36mPreTrainedTokenizerBase._from_pretrained\u001b[0;34m(cls, resolved_vocab_files, pretrained_model_name_or_path, init_configuration, token, cache_dir, local_files_only, _commit_hash, _is_local, trust_remote_code, *init_inputs, **kwargs)\u001b[0m\n\u001b[1;32m 2323\u001b[0m \u001b[38;5;66;03m# Instantiate the tokenizer.\u001b[39;00m\n\u001b[1;32m 2324\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m-> 2325\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minit_inputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minit_kwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2326\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mOSError\u001b[39;00m:\n\u001b[1;32m 2327\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mOSError\u001b[39;00m(\n\u001b[1;32m 2328\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUnable to load vocabulary from file. \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2329\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPlease check that the provided vocabulary is accessible and not corrupted.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2330\u001b[0m )\n",
|
126 |
+
"File \u001b[0;32m/opt/conda/envs/vcflash/lib/python3.10/site-packages/transformers/models/qwen2/tokenization_qwen2_fast.py:129\u001b[0m, in \u001b[0;36mQwen2TokenizerFast.__init__\u001b[0;34m(self, vocab_file, merges_file, tokenizer_file, unk_token, bos_token, eos_token, pad_token, **kwargs)\u001b[0m\n\u001b[1;32m 118\u001b[0m unk_token \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m 119\u001b[0m AddedToken(unk_token, lstrip\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, rstrip\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, special\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m, normalized\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[1;32m 120\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(unk_token, \u001b[38;5;28mstr\u001b[39m)\n\u001b[1;32m 121\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m unk_token\n\u001b[1;32m 122\u001b[0m )\n\u001b[1;32m 123\u001b[0m pad_token \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m 124\u001b[0m AddedToken(pad_token, lstrip\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, rstrip\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, special\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m, normalized\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[1;32m 125\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(pad_token, \u001b[38;5;28mstr\u001b[39m)\n\u001b[1;32m 126\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m pad_token\n\u001b[1;32m 127\u001b[0m )\n\u001b[0;32m--> 129\u001b[0m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;21;43m__init__\u001b[39;49m\u001b[43m(\u001b[49m\n\u001b[1;32m 130\u001b[0m \u001b[43m \u001b[49m\u001b[43mvocab_file\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 131\u001b[0m \u001b[43m \u001b[49m\u001b[43mmerges_file\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 132\u001b[0m \u001b[43m \u001b[49m\u001b[43mtokenizer_file\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtokenizer_file\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 133\u001b[0m \u001b[43m \u001b[49m\u001b[43munk_token\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43munk_token\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 134\u001b[0m \u001b[43m \u001b[49m\u001b[43mbos_token\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mbos_token\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 135\u001b[0m \u001b[43m \u001b[49m\u001b[43meos_token\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43meos_token\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 136\u001b[0m \u001b[43m \u001b[49m\u001b[43mpad_token\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpad_token\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 137\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 138\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
|
127 |
+
"File \u001b[0;32m/opt/conda/envs/vcflash/lib/python3.10/site-packages/transformers/tokenization_utils_fast.py:111\u001b[0m, in \u001b[0;36mPreTrainedTokenizerFast.__init__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 108\u001b[0m fast_tokenizer \u001b[38;5;241m=\u001b[39m copy\u001b[38;5;241m.\u001b[39mdeepcopy(tokenizer_object)\n\u001b[1;32m 109\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m fast_tokenizer_file \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m from_slow:\n\u001b[1;32m 110\u001b[0m \u001b[38;5;66;03m# We have a serialization from tokenizers which let us directly build the backend\u001b[39;00m\n\u001b[0;32m--> 111\u001b[0m fast_tokenizer \u001b[38;5;241m=\u001b[39m \u001b[43mTokenizerFast\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_file\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfast_tokenizer_file\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 112\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m slow_tokenizer \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 113\u001b[0m \u001b[38;5;66;03m# We need to convert a slow tokenizer to build the backend\u001b[39;00m\n\u001b[1;32m 114\u001b[0m fast_tokenizer \u001b[38;5;241m=\u001b[39m convert_slow_tokenizer(slow_tokenizer)\n",
|
128 |
+
"\u001b[0;31mException\u001b[0m: data did not match any variant of untagged enum ModelWrapper at line 757455 column 3"
|
129 |
+
]
|
130 |
+
}
|
131 |
+
],
|
132 |
+
"source": [
|
133 |
+
"from transformers import AutoModel, AutoTokenizer\n",
|
134 |
+
"import torch\n",
|
135 |
+
"from modeling_videochat_flash import VideoChatFlashQwenForCausalLM\n",
|
136 |
+
"\n",
|
137 |
+
"# model setting\n",
|
138 |
+
"model_path = './'\n",
|
139 |
+
"\n",
|
140 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)\n",
|
141 |
+
"model = VideoChatFlashQwenForCausalLM.from_pretrained(model_path).to(torch.bfloat16).cuda()\n",
|
142 |
+
"image_processor = model.get_vision_tower().image_processor\n",
|
143 |
+
"\n",
|
144 |
+
"mm_llm_compress = False # use the global compress or not\n",
|
145 |
+
"if mm_llm_compress:\n",
|
146 |
+
" model.config.mm_llm_compress = True\n",
|
147 |
+
" model.config.llm_compress_type = \"uniform0_attention\"\n",
|
148 |
+
" model.config.llm_compress_layer_list = [4, 18]\n",
|
149 |
+
" model.config.llm_image_token_ratio_list = [1, 0.75, 0.25]\n",
|
150 |
+
"else:\n",
|
151 |
+
" model.config.mm_llm_compress = False\n",
|
152 |
+
"\n",
|
153 |
+
"# evaluation setting\n",
|
154 |
+
"max_num_frames = 512\n",
|
155 |
+
"generation_config = dict(\n",
|
156 |
+
" do_sample=False,\n",
|
157 |
+
" temperature=0.0,\n",
|
158 |
+
" max_new_tokens=1024,\n",
|
159 |
+
" top_p=0.1,\n",
|
160 |
+
" num_beams=1\n",
|
161 |
+
")\n",
|
162 |
+
"\n",
|
163 |
+
"video_path = \"test.mp4\"\n",
|
164 |
+
"\n",
|
165 |
+
"# single-turn conversation\n",
|
166 |
+
"question1 = \"Describe this video in detail.\"\n",
|
167 |
+
"output1, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question1, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)\n",
|
168 |
+
"\n",
|
169 |
+
"print(output1)\n",
|
170 |
+
"\n",
|
171 |
+
"# # multi-turn conversation\n",
|
172 |
+
"# question2 = \"How many people appear in the video?\"\n",
|
173 |
+
"# output2, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question2, chat_history=chat_history, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)\n",
|
174 |
+
"\n",
|
175 |
+
"# print(output2)\n"
|
176 |
+
]
|
177 |
+
},
|
178 |
+
{
|
179 |
+
"cell_type": "code",
|
180 |
+
"execution_count": null,
|
181 |
+
"id": "8bfd7429-5d77-42ad-8e3f-9cf37b25dfc7",
|
182 |
+
"metadata": {},
|
183 |
+
"outputs": [],
|
184 |
+
"source": []
|
185 |
+
}
|
186 |
+
],
|
187 |
+
"metadata": {
|
188 |
+
"kernelspec": {
|
189 |
+
"display_name": "vcflash",
|
190 |
+
"language": "python",
|
191 |
+
"name": "vcflash"
|
192 |
+
},
|
193 |
+
"language_info": {
|
194 |
+
"codemirror_mode": {
|
195 |
+
"name": "ipython",
|
196 |
+
"version": 3
|
197 |
+
},
|
198 |
+
"file_extension": ".py",
|
199 |
+
"mimetype": "text/x-python",
|
200 |
+
"name": "python",
|
201 |
+
"nbconvert_exporter": "python",
|
202 |
+
"pygments_lexer": "ipython3",
|
203 |
+
"version": "3.10.14"
|
204 |
+
}
|
205 |
+
},
|
206 |
+
"nbformat": 4,
|
207 |
+
"nbformat_minor": 5
|
208 |
+
}
|
__pycache__/configuration_qwen2_mla.cpython-312.pyc
ADDED
Binary file (1.16 kB). View file
|
|
__pycache__/constants.cpython-310.pyc
ADDED
Binary file (550 Bytes). View file
|
|
__pycache__/constants.cpython-312.pyc
ADDED
Binary file (592 Bytes). View file
|
|
__pycache__/conversation.cpython-310.pyc
ADDED
Binary file (14.4 kB). View file
|
|
__pycache__/conversation.cpython-312.pyc
ADDED
Binary file (22.4 kB). View file
|
|
__pycache__/mm_projector_builder.cpython-310.pyc
ADDED
Binary file (5.02 kB). View file
|
|
__pycache__/mm_projector_builder.cpython-312.pyc
ADDED
Binary file (8.55 kB). View file
|
|
__pycache__/mm_utils.cpython-310.pyc
ADDED
Binary file (23.7 kB). View file
|
|
__pycache__/mm_utils.cpython-312.pyc
ADDED
Binary file (36.5 kB). View file
|
|
__pycache__/modeling_qwen2_mla.cpython-312.pyc
ADDED
Binary file (11.8 kB). View file
|
|
__pycache__/modeling_videochat_flash.cpython-310.pyc
ADDED
Binary file (19.5 kB). View file
|
|
__pycache__/modeling_videochat_flash.cpython-312.pyc
ADDED
Binary file (37.6 kB). View file
|
|
__pycache__/vision_tower_builder.cpython-310.pyc
ADDED
Binary file (19.7 kB). View file
|
|
__pycache__/vision_tower_builder.cpython-312.pyc
ADDED
Binary file (32.3 kB). View file
|
|
added_tokens.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</tool_call>": 151658,
|
3 |
+
"<tool_call>": 151657,
|
4 |
+
"<|box_end|>": 151649,
|
5 |
+
"<|box_start|>": 151648,
|
6 |
+
"<|endoftext|>": 151643,
|
7 |
+
"<|file_sep|>": 151664,
|
8 |
+
"<|fim_middle|>": 151660,
|
9 |
+
"<|fim_pad|>": 151662,
|
10 |
+
"<|fim_prefix|>": 151659,
|
11 |
+
"<|fim_suffix|>": 151661,
|
12 |
+
"<|im_end|>": 151645,
|
13 |
+
"<|im_start|>": 151644,
|
14 |
+
"<|image_pad|>": 151655,
|
15 |
+
"<|object_ref_end|>": 151647,
|
16 |
+
"<|object_ref_start|>": 151646,
|
17 |
+
"<|quad_end|>": 151651,
|
18 |
+
"<|quad_start|>": 151650,
|
19 |
+
"<|repo_name|>": 151663,
|
20 |
+
"<|video_pad|>": 151656,
|
21 |
+
"<|vision_end|>": 151653,
|
22 |
+
"<|vision_pad|>": 151654,
|
23 |
+
"<|vision_start|>": 151652
|
24 |
+
}
|
config.json
ADDED
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"VideoChatFlashQwenForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "modeling_videochat_flash.VideoChatFlashQwenConfig",
|
8 |
+
"AutoModel": "modeling_videochat_flash.VideoChatFlashQwenForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 151643,
|
11 |
+
"dual_chunk_attention_config": {
|
12 |
+
"chunk_size": 262144,
|
13 |
+
"local_size": 8192,
|
14 |
+
"original_max_position_embeddings": 262144
|
15 |
+
},
|
16 |
+
"eos_token_id": 151645,
|
17 |
+
"frame_aspect_ratio": "square",
|
18 |
+
"frame_grid_pinpoints": null,
|
19 |
+
"head_dim": 64,
|
20 |
+
"hidden_act": "silu",
|
21 |
+
"hidden_size": 3584,
|
22 |
+
"image_aspect_ratio": "anyres_nopad",
|
23 |
+
"image_crop_resolution": null,
|
24 |
+
"image_grid_pinpoints": [
|
25 |
+
[
|
26 |
+
224,
|
27 |
+
224
|
28 |
+
],
|
29 |
+
[
|
30 |
+
224,
|
31 |
+
448
|
32 |
+
],
|
33 |
+
[
|
34 |
+
224,
|
35 |
+
672
|
36 |
+
],
|
37 |
+
[
|
38 |
+
224,
|
39 |
+
896
|
40 |
+
],
|
41 |
+
[
|
42 |
+
224,
|
43 |
+
1120
|
44 |
+
],
|
45 |
+
[
|
46 |
+
224,
|
47 |
+
1344
|
48 |
+
],
|
49 |
+
[
|
50 |
+
448,
|
51 |
+
224
|
52 |
+
],
|
53 |
+
[
|
54 |
+
448,
|
55 |
+
448
|
56 |
+
],
|
57 |
+
[
|
58 |
+
448,
|
59 |
+
672
|
60 |
+
],
|
61 |
+
[
|
62 |
+
448,
|
63 |
+
896
|
64 |
+
],
|
65 |
+
[
|
66 |
+
448,
|
67 |
+
1120
|
68 |
+
],
|
69 |
+
[
|
70 |
+
448,
|
71 |
+
1344
|
72 |
+
],
|
73 |
+
[
|
74 |
+
672,
|
75 |
+
224
|
76 |
+
],
|
77 |
+
[
|
78 |
+
672,
|
79 |
+
448
|
80 |
+
],
|
81 |
+
[
|
82 |
+
672,
|
83 |
+
672
|
84 |
+
],
|
85 |
+
[
|
86 |
+
672,
|
87 |
+
896
|
88 |
+
],
|
89 |
+
[
|
90 |
+
672,
|
91 |
+
1120
|
92 |
+
],
|
93 |
+
[
|
94 |
+
672,
|
95 |
+
1344
|
96 |
+
],
|
97 |
+
[
|
98 |
+
896,
|
99 |
+
224
|
100 |
+
],
|
101 |
+
[
|
102 |
+
896,
|
103 |
+
448
|
104 |
+
],
|
105 |
+
[
|
106 |
+
896,
|
107 |
+
672
|
108 |
+
],
|
109 |
+
[
|
110 |
+
896,
|
111 |
+
896
|
112 |
+
],
|
113 |
+
[
|
114 |
+
896,
|
115 |
+
1120
|
116 |
+
],
|
117 |
+
[
|
118 |
+
896,
|
119 |
+
1344
|
120 |
+
],
|
121 |
+
[
|
122 |
+
1120,
|
123 |
+
224
|
124 |
+
],
|
125 |
+
[
|
126 |
+
1120,
|
127 |
+
448
|
128 |
+
],
|
129 |
+
[
|
130 |
+
1120,
|
131 |
+
672
|
132 |
+
],
|
133 |
+
[
|
134 |
+
1120,
|
135 |
+
896
|
136 |
+
],
|
137 |
+
[
|
138 |
+
1120,
|
139 |
+
1120
|
140 |
+
],
|
141 |
+
[
|
142 |
+
1120,
|
143 |
+
1344
|
144 |
+
],
|
145 |
+
[
|
146 |
+
1344,
|
147 |
+
224
|
148 |
+
],
|
149 |
+
[
|
150 |
+
1344,
|
151 |
+
448
|
152 |
+
],
|
153 |
+
[
|
154 |
+
1344,
|
155 |
+
672
|
156 |
+
],
|
157 |
+
[
|
158 |
+
1344,
|
159 |
+
896
|
160 |
+
],
|
161 |
+
[
|
162 |
+
1344,
|
163 |
+
1120
|
164 |
+
],
|
165 |
+
[
|
166 |
+
1344,
|
167 |
+
1344
|
168 |
+
]
|
169 |
+
],
|
170 |
+
"image_split_resolution": null,
|
171 |
+
"initializer_range": 0.02,
|
172 |
+
"intermediate_size": 18944,
|
173 |
+
"llm_compress_layer_list": [
|
174 |
+
8,
|
175 |
+
16,
|
176 |
+
24
|
177 |
+
],
|
178 |
+
"llm_compress_type": "attention",
|
179 |
+
"llm_image_token_ratio_list": [
|
180 |
+
1.0,
|
181 |
+
0.5,
|
182 |
+
0.25,
|
183 |
+
0.125
|
184 |
+
],
|
185 |
+
"max_num_pixels": 14745600000,
|
186 |
+
"max_position_embeddings": 32000,
|
187 |
+
"max_window_layers": 28,
|
188 |
+
"min_slow_num_frames": 4,
|
189 |
+
"mm_close_init": false,
|
190 |
+
"mm_hidden_size": 1024,
|
191 |
+
"mm_llm_compress": false,
|
192 |
+
"mm_local_num_frames": 4,
|
193 |
+
"mm_newline_position": "nothing",
|
194 |
+
"mm_num_compress_latents": 128,
|
195 |
+
"mm_num_compress_query_type": "learnable",
|
196 |
+
"mm_patch_merge_type": "spatial_nopad",
|
197 |
+
"mm_pos_num_frames": 8,
|
198 |
+
"mm_projector_lr": null,
|
199 |
+
"mm_projector_type": "tome16_mlp_hd64",
|
200 |
+
"mm_resampler_type": null,
|
201 |
+
"mm_spatial_pool_mode": "bilinear",
|
202 |
+
"mm_tunable_parts": "mm_vision_tower,mm_mlp_adapter,mm_language_model",
|
203 |
+
"mm_use_im_patch_token": false,
|
204 |
+
"mm_use_im_start_end": false,
|
205 |
+
"mm_vision_select_feature": "patch",
|
206 |
+
"mm_vision_select_layer": -2,
|
207 |
+
"mm_vision_tower": "umt-large",
|
208 |
+
"mm_vision_tower_lr": 2e-06,
|
209 |
+
"model_type": "videochat_flash_qwen",
|
210 |
+
"num_attention_heads": 28,
|
211 |
+
"num_hidden_layers": 28,
|
212 |
+
"num_key_value_heads": 28,
|
213 |
+
"pos_skipping_range": 4096,
|
214 |
+
"rms_norm_eps": 1e-05,
|
215 |
+
"rope_scaling": null,
|
216 |
+
"rope_theta": 10000000.0,
|
217 |
+
"sliding_window": 32768,
|
218 |
+
"tie_word_embeddings": false,
|
219 |
+
"tokenizer_model_max_length": 32768,
|
220 |
+
"tokenizer_padding_side": "right",
|
221 |
+
"torch_dtype": "bfloat16",
|
222 |
+
"transformers_version": "4.51.3",
|
223 |
+
"use_cache": true,
|
224 |
+
"use_mm_proj": true,
|
225 |
+
"use_pos_skipping": false,
|
226 |
+
"use_sliding_window": false,
|
227 |
+
"vision_encode_type": "video_image",
|
228 |
+
"vision_tower_pretrained": null,
|
229 |
+
"vocab_size": 152064,
|
230 |
+
"attention_bias": true,
|
231 |
+
"qk_rope_head_dim": 64,
|
232 |
+
"qk_nope_head_dim": 128,
|
233 |
+
"v_head_dim": 128,
|
234 |
+
"q_lora_rank": null,
|
235 |
+
"kv_lora_rank": 512,
|
236 |
+
"qk_latent_layernorm": false
|
237 |
+
}
|
configuration_qwen2_mla.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
|
2 |
+
|
3 |
+
class Qwen2MLAConfig(Qwen2Config):
|
4 |
+
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
*args,
|
8 |
+
kv_lora_rank=512,
|
9 |
+
q_lora_rank=None,
|
10 |
+
qk_rope_head_dim=64,
|
11 |
+
qk_nope_head_dim=128,
|
12 |
+
v_head_dim=128,
|
13 |
+
qk_latent_layernorm=True,
|
14 |
+
**kwargs
|
15 |
+
):
|
16 |
+
super().__init__(*args, **kwargs)
|
17 |
+
|
18 |
+
self.kv_lora_rank = kv_lora_rank
|
19 |
+
self.q_lora_rank = q_lora_rank
|
20 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
21 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
22 |
+
self.qk_head_dim = qk_rope_head_dim + qk_nope_head_dim
|
23 |
+
self.v_head_dim = v_head_dim
|
24 |
+
self.qk_latent_layernorm = qk_latent_layernorm
|
constants.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
5 |
+
|
6 |
+
# Model Constants
|
7 |
+
IGNORE_INDEX = -100
|
8 |
+
IMAGE_TOKEN_INDEX = -200
|
9 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
10 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
11 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
12 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
conversation.py
ADDED
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import auto, Enum
|
3 |
+
from typing import List, Any, Dict, Union, Tuple
|
4 |
+
import re
|
5 |
+
import base64
|
6 |
+
from io import BytesIO
|
7 |
+
from PIL import Image
|
8 |
+
from transformers import AutoTokenizer
|
9 |
+
|
10 |
+
|
11 |
+
class SeparatorStyle(Enum):
|
12 |
+
"""Different separator style."""
|
13 |
+
|
14 |
+
SINGLE = auto()
|
15 |
+
TWO = auto()
|
16 |
+
MPT = auto()
|
17 |
+
PLAIN = auto()
|
18 |
+
CHATML = auto()
|
19 |
+
LLAMA_2 = auto()
|
20 |
+
LLAMA_3 = auto()
|
21 |
+
QWEN = auto()
|
22 |
+
GEMMA = auto()
|
23 |
+
|
24 |
+
|
25 |
+
@dataclasses.dataclass
|
26 |
+
class Conversation:
|
27 |
+
"""A class that keeps all conversation history."""
|
28 |
+
|
29 |
+
system: str
|
30 |
+
roles: List[str]
|
31 |
+
messages: List[List[str]]
|
32 |
+
offset: int
|
33 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
34 |
+
sep: str = "###"
|
35 |
+
sep2: str = None
|
36 |
+
version: str = "Unknown"
|
37 |
+
|
38 |
+
tokenizer_id: str = ""
|
39 |
+
tokenizer: Any = None
|
40 |
+
# Stop criteria (the default one is EOS token)
|
41 |
+
stop_str: Union[str, List[str]] = None
|
42 |
+
# Stops generation if meeting any token in this list
|
43 |
+
stop_token_ids: List[int] = None
|
44 |
+
|
45 |
+
skip_next: bool = False
|
46 |
+
|
47 |
+
def get_prompt(self):
|
48 |
+
messages = self.messages
|
49 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
50 |
+
messages = self.messages.copy()
|
51 |
+
init_role, init_msg = messages[0].copy()
|
52 |
+
init_msg = init_msg[0]
|
53 |
+
if "mmtag" in self.version:
|
54 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
55 |
+
messages[0] = (init_role, init_msg)
|
56 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
57 |
+
messages.insert(1, (self.roles[1], "Received."))
|
58 |
+
elif not init_msg.startswith("<image>"):
|
59 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
60 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
61 |
+
else:
|
62 |
+
messages[0] = (init_role, init_msg)
|
63 |
+
|
64 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
65 |
+
ret = self.system + self.sep
|
66 |
+
for role, message in messages:
|
67 |
+
if message:
|
68 |
+
if type(message) is tuple:
|
69 |
+
message, _, _ = message
|
70 |
+
ret += role + ": " + message + self.sep
|
71 |
+
else:
|
72 |
+
ret += role + ":"
|
73 |
+
|
74 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
75 |
+
seps = [self.sep, self.sep2]
|
76 |
+
ret = self.system + seps[0]
|
77 |
+
for i, (role, message) in enumerate(messages):
|
78 |
+
if message:
|
79 |
+
if type(message) is tuple:
|
80 |
+
message, _, _ = message
|
81 |
+
ret += role + ": " + message + seps[i % 2]
|
82 |
+
else:
|
83 |
+
ret += role + ":"
|
84 |
+
|
85 |
+
elif self.sep_style == SeparatorStyle.CHATML:
|
86 |
+
ret = "" if self.system == "" else self.system + self.sep + "\n"
|
87 |
+
for role, message in messages:
|
88 |
+
if message:
|
89 |
+
if type(message) is tuple:
|
90 |
+
message, images, _ = message
|
91 |
+
message = "<image>" * len(images) + message
|
92 |
+
ret += role + "\n" + message + self.sep + "\n"
|
93 |
+
else:
|
94 |
+
ret += role + "\n"
|
95 |
+
return ret
|
96 |
+
|
97 |
+
elif self.sep_style == SeparatorStyle.LLAMA_3:
|
98 |
+
chat_template_messages = [{"role": "system", "content": self.system}]
|
99 |
+
for role, message in messages:
|
100 |
+
if message:
|
101 |
+
if type(message) is tuple:
|
102 |
+
message, images = message
|
103 |
+
message = "<image>" * len(images) + message
|
104 |
+
chat_template_messages.append({"role": role, "content": message})
|
105 |
+
|
106 |
+
# print(chat_template_messages)
|
107 |
+
return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
|
108 |
+
# ret = "" if self.system == "" else self.system + self.sep + "\n"
|
109 |
+
# for role, message in messages:
|
110 |
+
# if message:
|
111 |
+
# if type(message) is tuple:
|
112 |
+
# message, images = message
|
113 |
+
# message = "<image>" * len(images) + message
|
114 |
+
# ret += role + "\n" + message + self.sep + "\n"
|
115 |
+
# else:
|
116 |
+
# ret += role + "\n"
|
117 |
+
# return ret
|
118 |
+
|
119 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
120 |
+
ret = self.system + self.sep
|
121 |
+
for role, message in messages:
|
122 |
+
if message:
|
123 |
+
if type(message) is tuple:
|
124 |
+
message, _, _ = message
|
125 |
+
ret += role + message + self.sep
|
126 |
+
else:
|
127 |
+
ret += role
|
128 |
+
|
129 |
+
elif self.sep_style == SeparatorStyle.GEMMA:
|
130 |
+
ret = ""
|
131 |
+
for i, (role, message) in enumerate(messages):
|
132 |
+
assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
|
133 |
+
if message:
|
134 |
+
if type(message) is tuple:
|
135 |
+
message, _, _ = message
|
136 |
+
ret += role + message + self.sep
|
137 |
+
else:
|
138 |
+
ret += role
|
139 |
+
|
140 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
141 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
|
142 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
143 |
+
ret = ""
|
144 |
+
|
145 |
+
for i, (role, message) in enumerate(messages):
|
146 |
+
if i == 0:
|
147 |
+
assert message, "first message should not be none"
|
148 |
+
assert role == self.roles[0], "first message should come from user"
|
149 |
+
if message:
|
150 |
+
if type(message) is tuple:
|
151 |
+
message, _, _ = message
|
152 |
+
if i == 0:
|
153 |
+
message = wrap_sys(self.system) + message
|
154 |
+
if i % 2 == 0:
|
155 |
+
message = wrap_inst(message)
|
156 |
+
ret += self.sep + message
|
157 |
+
else:
|
158 |
+
ret += " " + message + " " + self.sep2
|
159 |
+
else:
|
160 |
+
ret += ""
|
161 |
+
ret = ret.lstrip(self.sep)
|
162 |
+
|
163 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
164 |
+
seps = [self.sep, self.sep2]
|
165 |
+
ret = self.system
|
166 |
+
for i, (role, message) in enumerate(messages):
|
167 |
+
if message:
|
168 |
+
if type(message) is tuple:
|
169 |
+
message, _, _ = message
|
170 |
+
ret += message + seps[i % 2]
|
171 |
+
else:
|
172 |
+
ret += ""
|
173 |
+
else:
|
174 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
175 |
+
|
176 |
+
return ret
|
177 |
+
|
178 |
+
def append_message(self, role, message):
|
179 |
+
self.messages.append([role, message])
|
180 |
+
|
181 |
+
def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
|
182 |
+
if image_process_mode == "Pad":
|
183 |
+
|
184 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
185 |
+
width, height = pil_img.size
|
186 |
+
if width == height:
|
187 |
+
return pil_img
|
188 |
+
elif width > height:
|
189 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
190 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
191 |
+
return result
|
192 |
+
else:
|
193 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
194 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
195 |
+
return result
|
196 |
+
|
197 |
+
image = expand2square(image)
|
198 |
+
elif image_process_mode in ["Default", "Crop"]:
|
199 |
+
pass
|
200 |
+
elif image_process_mode == "Resize":
|
201 |
+
image = image.resize((336, 336))
|
202 |
+
else:
|
203 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
204 |
+
|
205 |
+
if type(image) is not Image.Image:
|
206 |
+
image = Image.open(image).convert("RGB")
|
207 |
+
|
208 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
209 |
+
aspect_ratio = max_hw / min_hw
|
210 |
+
max_len, min_len = 672, 448
|
211 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
212 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
213 |
+
W, H = image.size
|
214 |
+
if H > W:
|
215 |
+
H, W = longest_edge, shortest_edge
|
216 |
+
else:
|
217 |
+
H, W = shortest_edge, longest_edge
|
218 |
+
image = image.resize((W, H))
|
219 |
+
if return_pil:
|
220 |
+
return image
|
221 |
+
else:
|
222 |
+
buffered = BytesIO()
|
223 |
+
image.save(buffered, format=image_format)
|
224 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
225 |
+
return img_b64_str
|
226 |
+
|
227 |
+
def get_images(self, return_pil=False, return_path=False):
|
228 |
+
images = []
|
229 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
230 |
+
if i % 2 == 0:
|
231 |
+
if type(msg) is tuple:
|
232 |
+
msg, image, image_process_mode = msg
|
233 |
+
if type(image) != list:
|
234 |
+
image = [image]
|
235 |
+
for img in image:
|
236 |
+
if not return_path and self.is_image_file(img):
|
237 |
+
img = self.process_image(img, image_process_mode, return_pil=return_pil)
|
238 |
+
else:
|
239 |
+
images.append(img)
|
240 |
+
return images
|
241 |
+
|
242 |
+
def is_image_file(self, filename):
|
243 |
+
image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
|
244 |
+
return any(filename.lower().endswith(ext) for ext in image_extensions)
|
245 |
+
|
246 |
+
def is_video_file(self, filename):
|
247 |
+
video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
|
248 |
+
return any(filename.lower().endswith(ext) for ext in video_extensions)
|
249 |
+
|
250 |
+
def to_gradio_chatbot(self):
|
251 |
+
ret = []
|
252 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
253 |
+
if i % 2 == 0:
|
254 |
+
if type(msg) is tuple:
|
255 |
+
msg, image, image_process_mode = msg
|
256 |
+
if type(image) != list:
|
257 |
+
image = [image]
|
258 |
+
if len(image) == 1:
|
259 |
+
msg = "<image>\n" + msg.replace("<image>", "").strip()
|
260 |
+
else:
|
261 |
+
msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
|
262 |
+
|
263 |
+
img_str_list = []
|
264 |
+
for img in image:
|
265 |
+
if self.is_image_file(img):
|
266 |
+
img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
|
267 |
+
img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
|
268 |
+
img_str_list.append(img_str)
|
269 |
+
elif self.is_video_file(img):
|
270 |
+
ret.append(((img,), None))
|
271 |
+
|
272 |
+
msg = msg.strip()
|
273 |
+
img_place_holder = ""
|
274 |
+
for img_str in img_str_list:
|
275 |
+
img_place_holder += f"{img_str}\n\n"
|
276 |
+
|
277 |
+
if len(img_str_list) > 0:
|
278 |
+
msg = f"{img_place_holder}\n\n{msg}"
|
279 |
+
|
280 |
+
if len(msg) > 0:
|
281 |
+
ret.append([msg, None])
|
282 |
+
else:
|
283 |
+
ret.append([msg, None])
|
284 |
+
else:
|
285 |
+
ret[-1][-1] = msg
|
286 |
+
return ret
|
287 |
+
|
288 |
+
def copy(self):
|
289 |
+
return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
|
290 |
+
|
291 |
+
def dict(self):
|
292 |
+
if len(self.get_images()) > 0:
|
293 |
+
return {
|
294 |
+
"system": self.system,
|
295 |
+
"roles": self.roles,
|
296 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
297 |
+
"offset": self.offset,
|
298 |
+
"sep": self.sep,
|
299 |
+
"sep2": self.sep2,
|
300 |
+
}
|
301 |
+
return {
|
302 |
+
"system": self.system,
|
303 |
+
"roles": self.roles,
|
304 |
+
"messages": self.messages,
|
305 |
+
"offset": self.offset,
|
306 |
+
"sep": self.sep,
|
307 |
+
"sep2": self.sep2,
|
308 |
+
}
|
309 |
+
|
310 |
+
|
311 |
+
conv_vicuna_v0 = Conversation(
|
312 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
313 |
+
roles=("Human", "Assistant"),
|
314 |
+
messages=[
|
315 |
+
["Human", "What are the key differences between renewable and non-renewable energy sources?"],
|
316 |
+
[
|
317 |
+
"Assistant",
|
318 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
319 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
320 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
321 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
322 |
+
"renewable and non-renewable energy sources:\n"
|
323 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
324 |
+
"energy sources are finite and will eventually run out.\n"
|
325 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
326 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
327 |
+
"and other negative effects.\n"
|
328 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
329 |
+
"have lower operational costs than non-renewable sources.\n"
|
330 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
331 |
+
"locations than non-renewable sources.\n"
|
332 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
333 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
334 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
335 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
|
336 |
+
],
|
337 |
+
],
|
338 |
+
offset=2,
|
339 |
+
sep_style=SeparatorStyle.SINGLE,
|
340 |
+
sep="###",
|
341 |
+
)
|
342 |
+
|
343 |
+
conv_vicuna_v1 = Conversation(
|
344 |
+
system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
345 |
+
roles=("USER", "ASSISTANT"),
|
346 |
+
version="v1",
|
347 |
+
messages=[],
|
348 |
+
offset=0,
|
349 |
+
sep_style=SeparatorStyle.TWO,
|
350 |
+
sep=" ",
|
351 |
+
sep2="</s>",
|
352 |
+
)
|
353 |
+
|
354 |
+
conv_llama_2 = Conversation(
|
355 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
356 |
+
|
357 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
358 |
+
roles=("USER", "ASSISTANT"),
|
359 |
+
version="llama_v2",
|
360 |
+
messages=[],
|
361 |
+
offset=0,
|
362 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
363 |
+
sep="<s>",
|
364 |
+
sep2="</s>",
|
365 |
+
)
|
366 |
+
|
367 |
+
conv_llava_llama_2 = Conversation(
|
368 |
+
system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
369 |
+
roles=("USER", "ASSISTANT"),
|
370 |
+
version="llama_v2",
|
371 |
+
messages=[],
|
372 |
+
offset=0,
|
373 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
374 |
+
sep="<s>",
|
375 |
+
sep2="</s>",
|
376 |
+
)
|
377 |
+
|
378 |
+
# conv_llava_llama_3 = Conversation(
|
379 |
+
# system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
380 |
+
# roles=("user", "assistant"),
|
381 |
+
# version="llama_v3",
|
382 |
+
# messages=[],
|
383 |
+
# offset=0,
|
384 |
+
# sep="<|eot_id|>",
|
385 |
+
# sep_style=SeparatorStyle.LLAMA_3,
|
386 |
+
# tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
|
387 |
+
# tokenizer=AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct"),
|
388 |
+
# stop_token_ids=[128009],
|
389 |
+
# )
|
390 |
+
|
391 |
+
conv_mistral_instruct = Conversation(
|
392 |
+
system="",
|
393 |
+
roles=("USER", "ASSISTANT"),
|
394 |
+
version="llama_v2",
|
395 |
+
messages=[],
|
396 |
+
offset=0,
|
397 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
398 |
+
sep="",
|
399 |
+
sep2="</s>",
|
400 |
+
)
|
401 |
+
|
402 |
+
conv_llava_llama_2_simple = Conversation(
|
403 |
+
system="Answer the questions about the visual content that the user provides.",
|
404 |
+
roles=("USER", "ASSISTANT"),
|
405 |
+
version="llama_v2",
|
406 |
+
messages=[],
|
407 |
+
offset=0,
|
408 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
409 |
+
sep="<s>",
|
410 |
+
sep2="</s>",
|
411 |
+
)
|
412 |
+
|
413 |
+
conv_llava_llama_2_mmtag = Conversation(
|
414 |
+
system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
|
415 |
+
roles=("USER", "ASSISTANT"),
|
416 |
+
version="llama_v2_mmtag",
|
417 |
+
messages=[],
|
418 |
+
offset=0,
|
419 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
420 |
+
sep="<s>",
|
421 |
+
sep2="</s>",
|
422 |
+
)
|
423 |
+
|
424 |
+
conv_mpt = Conversation(
|
425 |
+
system="""<|im_start|>system
|
426 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
427 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
428 |
+
version="mpt",
|
429 |
+
messages=[],
|
430 |
+
offset=0,
|
431 |
+
sep_style=SeparatorStyle.MPT,
|
432 |
+
sep="<|im_end|>",
|
433 |
+
)
|
434 |
+
|
435 |
+
conv_qwen = Conversation(
|
436 |
+
system="""<|im_start|>system
|
437 |
+
You are a helpful assistant.""",
|
438 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
439 |
+
version="qwen",
|
440 |
+
messages=[],
|
441 |
+
offset=0,
|
442 |
+
sep_style=SeparatorStyle.CHATML,
|
443 |
+
sep="<|im_end|>",
|
444 |
+
)
|
445 |
+
|
446 |
+
|
447 |
+
|
448 |
+
conv_internlm_2 = Conversation(
|
449 |
+
system="""<|im_start|>system
|
450 |
+
You are a helpful assistant.""",
|
451 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
452 |
+
version="internlm_2",
|
453 |
+
messages=[],
|
454 |
+
offset=0,
|
455 |
+
sep_style=SeparatorStyle.CHATML,
|
456 |
+
sep="<|im_end|>",
|
457 |
+
)
|
458 |
+
|
459 |
+
conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
|
460 |
+
|
461 |
+
conv_llava_plain = Conversation(
|
462 |
+
system="",
|
463 |
+
roles=("", ""),
|
464 |
+
messages=[],
|
465 |
+
offset=0,
|
466 |
+
sep_style=SeparatorStyle.PLAIN,
|
467 |
+
sep="\n",
|
468 |
+
)
|
469 |
+
|
470 |
+
conv_llava_v0 = Conversation(
|
471 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
472 |
+
roles=("Human", "Assistant"),
|
473 |
+
messages=[],
|
474 |
+
offset=0,
|
475 |
+
sep_style=SeparatorStyle.SINGLE,
|
476 |
+
sep="###",
|
477 |
+
)
|
478 |
+
|
479 |
+
conv_llava_v0_mmtag = Conversation(
|
480 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
481 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
482 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
483 |
+
roles=("Human", "Assistant"),
|
484 |
+
messages=[],
|
485 |
+
offset=0,
|
486 |
+
sep_style=SeparatorStyle.SINGLE,
|
487 |
+
sep="###",
|
488 |
+
version="v0_mmtag",
|
489 |
+
)
|
490 |
+
|
491 |
+
conv_llava_v1 = Conversation(
|
492 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
493 |
+
roles=("USER", "ASSISTANT"),
|
494 |
+
version="v1",
|
495 |
+
messages=[],
|
496 |
+
offset=0,
|
497 |
+
sep_style=SeparatorStyle.TWO,
|
498 |
+
sep=" ",
|
499 |
+
sep2="</s>",
|
500 |
+
)
|
501 |
+
|
502 |
+
conv_llava_v1_mmtag = Conversation(
|
503 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
504 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
505 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
506 |
+
roles=("USER", "ASSISTANT"),
|
507 |
+
messages=[],
|
508 |
+
offset=0,
|
509 |
+
sep_style=SeparatorStyle.TWO,
|
510 |
+
sep=" ",
|
511 |
+
sep2="</s>",
|
512 |
+
version="v1_mmtag",
|
513 |
+
)
|
514 |
+
|
515 |
+
conv_mistral_orca = Conversation(
|
516 |
+
system="""<|im_start|>system
|
517 |
+
You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
|
518 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
519 |
+
version="mpt",
|
520 |
+
messages=[],
|
521 |
+
offset=0,
|
522 |
+
sep_style=SeparatorStyle.MPT,
|
523 |
+
sep="<|im_end|>",
|
524 |
+
)
|
525 |
+
|
526 |
+
conv_mistral_zephyr = Conversation(
|
527 |
+
system="""<|system|>
|
528 |
+
You are a helpful AI assistant.""",
|
529 |
+
roles=("<|user|>\n", "<|assistant|>\n"),
|
530 |
+
version="mpt",
|
531 |
+
messages=[],
|
532 |
+
offset=0,
|
533 |
+
sep_style=SeparatorStyle.MPT,
|
534 |
+
sep="</s>",
|
535 |
+
)
|
536 |
+
|
537 |
+
conv_mistral_direct = Conversation(
|
538 |
+
system="""<|im_start|>system
|
539 |
+
Answer the questions.""",
|
540 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
541 |
+
version="mpt",
|
542 |
+
messages=[],
|
543 |
+
offset=0,
|
544 |
+
sep_style=SeparatorStyle.MPT,
|
545 |
+
sep="<|im_end|>",
|
546 |
+
)
|
547 |
+
|
548 |
+
conv_chatml_direct = Conversation(
|
549 |
+
system="""<|im_start|>system
|
550 |
+
Answer the questions.""",
|
551 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
552 |
+
version="mpt",
|
553 |
+
messages=[],
|
554 |
+
offset=0,
|
555 |
+
sep_style=SeparatorStyle.MPT,
|
556 |
+
sep="<|im_end|>",
|
557 |
+
)
|
558 |
+
|
559 |
+
default_conversation = conv_vicuna_v0
|
560 |
+
conv_templates = {
|
561 |
+
"default": conv_vicuna_v0,
|
562 |
+
"v0": conv_vicuna_v0,
|
563 |
+
"v1": conv_vicuna_v1,
|
564 |
+
"vicuna_v1": conv_vicuna_v1,
|
565 |
+
"llama_2": conv_llama_2,
|
566 |
+
"mistral_instruct": conv_mistral_instruct,
|
567 |
+
"mistral_orca": conv_mistral_orca,
|
568 |
+
"mistral_zephyr": conv_mistral_zephyr,
|
569 |
+
"mistral_direct": conv_mistral_direct,
|
570 |
+
"plain": conv_llava_plain,
|
571 |
+
"v0_plain": conv_llava_plain,
|
572 |
+
"chatml_direct": conv_chatml_direct,
|
573 |
+
"llava_v0": conv_llava_v0,
|
574 |
+
"llava_v0_mmtag": conv_llava_v0_mmtag,
|
575 |
+
"llava_v1": conv_llava_v1,
|
576 |
+
"llava_v1_mmtag": conv_llava_v1_mmtag,
|
577 |
+
"llava_llama_2": conv_llava_llama_2,
|
578 |
+
# "llava_llama_3": conv_llava_llama_3,
|
579 |
+
"llava_llama_2_simple": conv_llava_llama_2_simple,
|
580 |
+
"llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
|
581 |
+
"llava_mistral_instruct": conv_mistral_instruct,
|
582 |
+
"mpt": conv_mpt,
|
583 |
+
"qwen_1_5": conv_qwen,
|
584 |
+
"qwen_2": conv_qwen,
|
585 |
+
"internlm_2": conv_internlm_2,
|
586 |
+
"gemma_instruct": conv_gemma_instruct,
|
587 |
+
}
|
588 |
+
|
589 |
+
|
590 |
+
if __name__ == "__main__":
|
591 |
+
print(default_conversation.get_prompt())
|
592 |
+
print(default_conversation)
|
generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"pad_token_id": 151643,
|
9 |
+
"repetition_penalty": 1.05,
|
10 |
+
"temperature": 0.7,
|
11 |
+
"top_k": 20,
|
12 |
+
"top_p": 0.8,
|
13 |
+
"transformers_version": "4.51.3"
|
14 |
+
}
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
mm_projector_builder.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from typing import Callable, Tuple
|
4 |
+
|
5 |
+
|
6 |
+
def bipartite_soft_matching(
|
7 |
+
metric: torch.Tensor,
|
8 |
+
r: int,
|
9 |
+
) -> Tuple[Callable, Callable]:
|
10 |
+
"""
|
11 |
+
Applies ToMe with a balanced matching set (50%, 50%).
|
12 |
+
|
13 |
+
Input size is [batch, tokens, channels].
|
14 |
+
r indicates the number of tokens to remove (max 50% of tokens).
|
15 |
+
"""
|
16 |
+
protected = 0
|
17 |
+
|
18 |
+
t = metric.shape[1]
|
19 |
+
r = min(r, (t - protected) // 2)
|
20 |
+
|
21 |
+
assert r > 0, r
|
22 |
+
|
23 |
+
with torch.no_grad():
|
24 |
+
metric = metric / metric.norm(dim=-1, keepdim=True)
|
25 |
+
a, b = metric[..., ::2, :], metric[..., 1::2, :]
|
26 |
+
scores = a @ b.transpose(-1, -2)
|
27 |
+
|
28 |
+
node_max, node_idx = scores.max(dim=-1)
|
29 |
+
edge_idx = node_max.argsort(dim=-1, descending=True)[..., None]
|
30 |
+
|
31 |
+
unm_idx = edge_idx[..., r:, :] # Unmerged Tokens
|
32 |
+
src_idx = edge_idx[..., :r, :] # Merged Tokens
|
33 |
+
dst_idx = node_idx[..., None].gather(dim=-2, index=src_idx)
|
34 |
+
|
35 |
+
def merge(x: torch.Tensor, mode="mean") -> torch.Tensor:
|
36 |
+
src, dst = x[..., ::2, :], x[..., 1::2, :]
|
37 |
+
n, t1, c = src.shape
|
38 |
+
unm = src.gather(dim=-2, index=unm_idx.expand(n, t1 - r, c))
|
39 |
+
src = src.gather(dim=-2, index=src_idx.expand(n, r, c))
|
40 |
+
dst = dst.scatter_add(-2, dst_idx.expand(n, r, c), src) # , reduce=mode)
|
41 |
+
|
42 |
+
return torch.cat([unm, dst], dim=1)
|
43 |
+
|
44 |
+
def unmerge(x: torch.Tensor) -> torch.Tensor:
|
45 |
+
unm_len = unm_idx.shape[1]
|
46 |
+
unm, dst = x[..., :unm_len, :], x[..., unm_len:, :]
|
47 |
+
n, _, c = unm.shape
|
48 |
+
|
49 |
+
src = dst.gather(dim=-2, index=dst_idx.expand(n, r, c))
|
50 |
+
|
51 |
+
out = torch.zeros(n, metric.shape[1], c, device=x.device, dtype=x.dtype)
|
52 |
+
|
53 |
+
out[..., 1::2, :] = dst
|
54 |
+
out.scatter_(dim=-2, index=(2 * unm_idx).expand(n, unm_len, c), src=unm)
|
55 |
+
out.scatter_(dim=-2, index=(2 * src_idx).expand(n, r, c), src=src)
|
56 |
+
|
57 |
+
return out
|
58 |
+
|
59 |
+
return merge, unmerge
|
60 |
+
|
61 |
+
|
62 |
+
def merge_wavg(
|
63 |
+
merge: Callable, x: torch.Tensor, size: torch.Tensor = None
|
64 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
65 |
+
"""
|
66 |
+
Applies the merge function by taking a weighted average based on token size.
|
67 |
+
Returns the merged tensor and the new token sizes.
|
68 |
+
"""
|
69 |
+
if size is None:
|
70 |
+
size = torch.ones_like(x[..., 0, None])
|
71 |
+
|
72 |
+
x = merge(x * size, mode="sum")
|
73 |
+
size = merge(size, mode="sum")
|
74 |
+
|
75 |
+
x = x / size
|
76 |
+
return x, size
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
class ToMe16_mlp_hd64(nn.Module):
|
82 |
+
def __init__(self, config, vision_cfg):
|
83 |
+
super().__init__()
|
84 |
+
self._config = config
|
85 |
+
self.mm_hidden_size = config.mm_hidden_size
|
86 |
+
self.hw = vision_cfg.image_size // vision_cfg.patch_size
|
87 |
+
self.num_attention_heads = vision_cfg.num_attention_heads
|
88 |
+
self.mlp = nn.Sequential(nn.Linear(config.mm_hidden_size, config.hidden_size),
|
89 |
+
nn.GELU(),
|
90 |
+
nn.Linear(config.hidden_size, config.hidden_size))
|
91 |
+
self.max_pos_hw = self.hw
|
92 |
+
self.max_pos_num_frames = config.mm_pos_num_frames
|
93 |
+
self.num_image_patches_per_side = 8
|
94 |
+
self.num_frame_patches_per_side = 4
|
95 |
+
|
96 |
+
def merge_tokens(self, x, target_num_token):
|
97 |
+
r"""
|
98 |
+
x = torch.randn(10, 2560, c)
|
99 |
+
x = merge_tokens(x, r_merge_list=[1280])
|
100 |
+
"""
|
101 |
+
size = None
|
102 |
+
b, p, c = x.shape
|
103 |
+
tmp_p = p
|
104 |
+
r_merge_list = []
|
105 |
+
assert tmp_p > target_num_token, f"{tmp_p} should greater than {target_num_token}"
|
106 |
+
while tmp_p != target_num_token:
|
107 |
+
if tmp_p - target_num_token <= (tmp_p // 2):
|
108 |
+
r_merge_list.append(tmp_p - target_num_token)
|
109 |
+
break
|
110 |
+
else:
|
111 |
+
r_merge_list.append(tmp_p // 2)
|
112 |
+
tmp_p = tmp_p - (tmp_p // 2)
|
113 |
+
|
114 |
+
|
115 |
+
head = self.num_attention_heads
|
116 |
+
|
117 |
+
dim = c // head
|
118 |
+
for r in r_merge_list:
|
119 |
+
metric = x.reshape(b, p, head, dim).mean(2) # [b, p, c//head]
|
120 |
+
merge, _ = bipartite_soft_matching(
|
121 |
+
metric,
|
122 |
+
r
|
123 |
+
)
|
124 |
+
x, size = merge_wavg(merge, x, size)
|
125 |
+
_, p, _ = x.shape
|
126 |
+
|
127 |
+
return x
|
128 |
+
|
129 |
+
|
130 |
+
|
131 |
+
def forward(self, x, compress=False, local_num_frames=-1): # 单帧64
|
132 |
+
height = width = self.hw
|
133 |
+
assert height * width == x.shape[1]
|
134 |
+
|
135 |
+
if local_num_frames != -1 and local_num_frames != 1:
|
136 |
+
assert compress is True
|
137 |
+
if compress:
|
138 |
+
if local_num_frames != -1:
|
139 |
+
num_frames = local_num_frames
|
140 |
+
x = x.reshape(x.shape[0] // local_num_frames, -1, x.shape[-1])
|
141 |
+
else:
|
142 |
+
num_frames = x.shape[0]
|
143 |
+
x = x.reshape(1, -1, x.shape[-1])
|
144 |
+
num_tome_tokens = 16 * num_frames
|
145 |
+
else:
|
146 |
+
num_tome_tokens = 64
|
147 |
+
|
148 |
+
x = self.merge_tokens(x, target_num_token=num_tome_tokens)
|
149 |
+
x = self.mlp(x)
|
150 |
+
return x
|
151 |
+
|
152 |
+
@property
|
153 |
+
def config(self):
|
154 |
+
return {"mm_projector_type": "tome16_mlp_hd64"}
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
def build_vision_projector(config, delay_load=False, **kwargs):
|
160 |
+
projector_type = getattr(config, "mm_projector_type", "linear")
|
161 |
+
|
162 |
+
if projector_type == 'tome16_mlp_hd64':
|
163 |
+
return ToMe16_mlp_hd64(config, kwargs["vision_cfg"])
|
164 |
+
|
165 |
+
raise ValueError(f"Unknown projector type: {projector_type}")
|
mm_utils.py
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
from io import BytesIO
|
3 |
+
import base64
|
4 |
+
import math
|
5 |
+
import ast
|
6 |
+
import re
|
7 |
+
import torch
|
8 |
+
from transformers import StoppingCriteria
|
9 |
+
from .constants import IMAGE_TOKEN_INDEX
|
10 |
+
import random
|
11 |
+
import os
|
12 |
+
import io
|
13 |
+
import av
|
14 |
+
import cv2
|
15 |
+
import imageio
|
16 |
+
from decord import VideoReader
|
17 |
+
import numpy as np
|
18 |
+
from torchvision.transforms.functional import pil_to_tensor
|
19 |
+
|
20 |
+
|
21 |
+
######################## load video ########################
|
22 |
+
|
23 |
+
def get_index(num_frames, num_segments):
|
24 |
+
seg_size = float(num_frames - 1) / num_segments
|
25 |
+
start = int(seg_size / 2)
|
26 |
+
offsets = np.array([
|
27 |
+
start + int(np.round(seg_size * idx)) for idx in range(num_segments)
|
28 |
+
])
|
29 |
+
return offsets
|
30 |
+
|
31 |
+
|
32 |
+
def pts_to_secs(pts: int, time_base: float, start_pts: int) -> float:
|
33 |
+
"""
|
34 |
+
Converts a present time with the given time base and start_pts offset to seconds.
|
35 |
+
|
36 |
+
Returns:
|
37 |
+
time_in_seconds (float): The corresponding time in seconds.
|
38 |
+
|
39 |
+
https://github.com/facebookresearch/pytorchvideo/blob/main/pytorchvideo/data/utils.py#L54-L64
|
40 |
+
"""
|
41 |
+
if pts == math.inf:
|
42 |
+
return math.inf
|
43 |
+
|
44 |
+
return int(pts - start_pts) * time_base
|
45 |
+
|
46 |
+
|
47 |
+
def get_pyav_video_duration(video_reader):
|
48 |
+
video_stream = video_reader.streams.video[0]
|
49 |
+
video_duration = pts_to_secs(
|
50 |
+
video_stream.duration,
|
51 |
+
video_stream.time_base,
|
52 |
+
video_stream.start_time
|
53 |
+
)
|
54 |
+
return float(video_duration)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
def get_frame_indices(num_frames, vlen, sample='middle', fix_start=None, input_fps=1, min_num_frames=1, max_num_frames=-1, local_num_frames=8):
|
59 |
+
|
60 |
+
if min_num_frames > vlen:
|
61 |
+
if sample == 'dynamic_fps1':
|
62 |
+
min_num_frames = (vlen // local_num_frames) * local_num_frames
|
63 |
+
else:
|
64 |
+
min_num_frames = vlen
|
65 |
+
|
66 |
+
|
67 |
+
if sample == 'dynamic_fps1':
|
68 |
+
|
69 |
+
duration = float(vlen) / input_fps
|
70 |
+
num_segments = int(duration // local_num_frames)
|
71 |
+
if num_segments == 0:
|
72 |
+
num_frames = local_num_frames
|
73 |
+
else:
|
74 |
+
num_frames = local_num_frames * num_segments
|
75 |
+
|
76 |
+
if max_num_frames > 0:
|
77 |
+
num_frames = min(num_frames, max_num_frames)
|
78 |
+
sample = "middle" # NOTE
|
79 |
+
|
80 |
+
# logger.info(f"? is OK (img), duation={duration} frames={num_frames}!!!!")
|
81 |
+
|
82 |
+
num_frames = max(min_num_frames, num_frames)
|
83 |
+
|
84 |
+
# print(f"\033[0;31m vlen={vlen}, input_fps={input_fps} num_frames={num_frames} \033[0m")
|
85 |
+
|
86 |
+
if sample in ["rand", "middle"]: # uniform sampling
|
87 |
+
acc_samples = min(num_frames, vlen)
|
88 |
+
# split the video into `acc_samples` intervals, and sample from each interval.
|
89 |
+
intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
|
90 |
+
ranges = []
|
91 |
+
for idx, interv in enumerate(intervals[:-1]):
|
92 |
+
ranges.append((interv, intervals[idx + 1] - 1))
|
93 |
+
if sample == 'rand':
|
94 |
+
try:
|
95 |
+
frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
|
96 |
+
except:
|
97 |
+
frame_indices = np.random.permutation(vlen)[:acc_samples]
|
98 |
+
frame_indices.sort()
|
99 |
+
frame_indices = list(frame_indices)
|
100 |
+
elif fix_start is not None:
|
101 |
+
frame_indices = [x[0] + fix_start for x in ranges]
|
102 |
+
elif sample == 'middle':
|
103 |
+
frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
|
104 |
+
else:
|
105 |
+
raise NotImplementedError
|
106 |
+
|
107 |
+
if len(frame_indices) < num_frames: # padded with last frame
|
108 |
+
padded_frame_indices = [frame_indices[-1]] * num_frames
|
109 |
+
padded_frame_indices[:len(frame_indices)] = frame_indices
|
110 |
+
frame_indices = padded_frame_indices
|
111 |
+
elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
|
112 |
+
output_fps = float(sample[3:])
|
113 |
+
duration = float(vlen) / input_fps
|
114 |
+
delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
|
115 |
+
frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
|
116 |
+
frame_indices = np.around(frame_seconds * input_fps).astype(int)
|
117 |
+
frame_indices = [e for e in frame_indices if e < vlen]
|
118 |
+
if max_num_frames > 0 and len(frame_indices) > max_num_frames:
|
119 |
+
frame_indices = frame_indices[:max_num_frames]
|
120 |
+
# frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
|
121 |
+
else:
|
122 |
+
raise ValueError(f"Not support sample type: {sample}")
|
123 |
+
|
124 |
+
|
125 |
+
return frame_indices
|
126 |
+
|
127 |
+
|
128 |
+
def read_frames_av(video_path, num_frames, sample='rand', client=None, fix_start=None, min_num_frames=1, max_num_frames=-1, clip=None, local_num_frames=8):
|
129 |
+
if clip is not None:
|
130 |
+
raise NotImplementedError("av don't support clip!!!")
|
131 |
+
if 's3://' in video_path:
|
132 |
+
video_bytes = client.get(video_path)
|
133 |
+
byteio = io.BytesIO(video_bytes)
|
134 |
+
byteio.seek(0)
|
135 |
+
reader = av.open(byteio)
|
136 |
+
else:
|
137 |
+
byteio = None
|
138 |
+
reader = av.open(video_path)
|
139 |
+
frames = [f.to_rgb().to_ndarray() for f in reader.decode(video=0)]
|
140 |
+
vlen = len(frames)
|
141 |
+
duration = get_pyav_video_duration(reader)
|
142 |
+
fps = vlen / float(duration)
|
143 |
+
frame_indices = get_frame_indices(
|
144 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
145 |
+
input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
146 |
+
)
|
147 |
+
frames = np.stack([frames[idx] for idx in frame_indices]) # (T, H, W, C), torch.uint8
|
148 |
+
# frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
|
149 |
+
if byteio != None:
|
150 |
+
byteio.close()
|
151 |
+
|
152 |
+
reader.close()
|
153 |
+
|
154 |
+
return frames, frame_indices, float(fps), duration
|
155 |
+
|
156 |
+
|
157 |
+
def read_frames_gif(
|
158 |
+
video_path, num_frames, sample='rand', fix_start=None,
|
159 |
+
min_num_frames=1, max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
160 |
+
):
|
161 |
+
if clip is not None:
|
162 |
+
raise NotImplementedError("Gif don't support clip!!!")
|
163 |
+
if 's3://' in video_path:
|
164 |
+
video_bytes = client.get(video_path)
|
165 |
+
byteio = io.BytesIO(video_bytes)
|
166 |
+
gif = imageio.get_reader(byteio)
|
167 |
+
else:
|
168 |
+
byteio = None
|
169 |
+
gif = imageio.get_reader(video_path)
|
170 |
+
vlen = len(gif)
|
171 |
+
fps = 1.
|
172 |
+
duration = vlen / fps
|
173 |
+
frame_indices = get_frame_indices(
|
174 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
175 |
+
min_num_frames=min_num_frames,
|
176 |
+
max_num_frames=max_num_frames, local_num_frames=local_num_frames,
|
177 |
+
input_fps=fps
|
178 |
+
)
|
179 |
+
frames = []
|
180 |
+
|
181 |
+
min_h = min_w = 100000
|
182 |
+
hw_set = set()
|
183 |
+
for index, frame in enumerate(gif):
|
184 |
+
# for index in frame_idxs:
|
185 |
+
if index in frame_indices:
|
186 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
|
187 |
+
frame = frame.astype(np.uint8)
|
188 |
+
# # (H x W x C) to (C x H x W)
|
189 |
+
# frame = frame.permute(2, 0, 1)
|
190 |
+
frames.append(frame)
|
191 |
+
hw_set.add(frame.shape)
|
192 |
+
if frame.shape[0] < min_h:
|
193 |
+
min_h = frame.shape[0]
|
194 |
+
if frame.shape[1] < min_w:
|
195 |
+
min_w = frame.shape[1]
|
196 |
+
# print(hw_set, min_h, min_w)
|
197 |
+
if len(hw_set) > 1:
|
198 |
+
frames = [i[:min_h, :min_w] for i in frames]
|
199 |
+
|
200 |
+
frames = np.stack(frames) # .float() / 255
|
201 |
+
|
202 |
+
if byteio != None:
|
203 |
+
byteio.close()
|
204 |
+
|
205 |
+
return frames, frame_indices, float(fps), duration # for tgif
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
def read_frames_decord(
|
210 |
+
video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
|
211 |
+
max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
212 |
+
):
|
213 |
+
|
214 |
+
if video_path.endswith('.avi'):
|
215 |
+
return read_frames_av(video_path=video_path, num_frames=num_frames, sample=sample,
|
216 |
+
fix_start=fix_start, min_num_frames=min_num_frames, max_num_frames=max_num_frames,
|
217 |
+
client=client, clip=clip, local_num_frames=local_num_frames)
|
218 |
+
if 's3://' in video_path:
|
219 |
+
video_bytes = client.get(video_path)
|
220 |
+
if video_bytes is None or len(video_bytes) == 0:
|
221 |
+
raise ValueError(f"Can't read byte from {video_path}!")
|
222 |
+
byteio = io.BytesIO(video_bytes)
|
223 |
+
video_reader = VideoReader(byteio, num_threads=1)
|
224 |
+
else:
|
225 |
+
byteio = None
|
226 |
+
video_reader = VideoReader(video_path, num_threads=1)
|
227 |
+
vlen = len(video_reader)
|
228 |
+
fps = video_reader.get_avg_fps()
|
229 |
+
duration = vlen / float(fps)
|
230 |
+
|
231 |
+
|
232 |
+
if clip:
|
233 |
+
start, end = clip
|
234 |
+
start = max(0, start)
|
235 |
+
end = min(duration - 0.1, end)
|
236 |
+
duration = end - start
|
237 |
+
vlen = int(duration * fps)
|
238 |
+
start_index = int(start * fps)
|
239 |
+
|
240 |
+
frame_indices = get_frame_indices(
|
241 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
242 |
+
input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
243 |
+
)
|
244 |
+
if clip:
|
245 |
+
frame_indices = [f + start_index for f in frame_indices]
|
246 |
+
|
247 |
+
# print(fps, frame_indices)
|
248 |
+
frames = video_reader.get_batch(frame_indices).asnumpy() # (T, H, W, C), torch.uint8
|
249 |
+
# https://github.com/dmlc/decord/issues/208
|
250 |
+
video_reader.seek(0)
|
251 |
+
|
252 |
+
if byteio != None:
|
253 |
+
byteio.close()
|
254 |
+
# frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
|
255 |
+
return frames, frame_indices, float(fps), duration
|
256 |
+
|
257 |
+
|
258 |
+
|
259 |
+
def read_frames_img(
|
260 |
+
video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
|
261 |
+
max_num_frames=-1, client=None, clip=None, local_num_frames=8
|
262 |
+
):
|
263 |
+
def extract_frame_number(filename):
|
264 |
+
# Extract the numeric part from the filename using regular expressions
|
265 |
+
if filename.endswith('.jpg'):
|
266 |
+
match = re.search(r'_(\d+).jpg$', filename)
|
267 |
+
elif filename.endswith('.jpeg'):
|
268 |
+
match = re.search(r'_(\d+).jpeg$', filename)
|
269 |
+
elif filename.endswith('.png'):
|
270 |
+
match = re.search(r'_(\d+).png$', filename)
|
271 |
+
else:
|
272 |
+
raise NotImplementedError(f"Wrong filename: {filename}")
|
273 |
+
|
274 |
+
return int(match.group(1)) if match else -1
|
275 |
+
|
276 |
+
|
277 |
+
def sort_frames(frame_paths):
|
278 |
+
# Extract filenames from each path and sort by their numeric part
|
279 |
+
return sorted(frame_paths, key=lambda x: extract_frame_number(os.path.basename(x)))
|
280 |
+
|
281 |
+
# img_list=[]
|
282 |
+
|
283 |
+
if "s3://" in video_path:
|
284 |
+
img_list = sort_frames(client.list(video_path))
|
285 |
+
else:
|
286 |
+
img_list = sort_frames(list(os.listdir(video_path)))
|
287 |
+
|
288 |
+
|
289 |
+
if 'tvqa' in video_path.lower():
|
290 |
+
fps = 3.0
|
291 |
+
else:
|
292 |
+
fps = 1.0
|
293 |
+
|
294 |
+
if clip is not None:
|
295 |
+
start = float(clip[0])
|
296 |
+
end = float(clip[1])
|
297 |
+
start = max(0, start)
|
298 |
+
end = min(len(img_list) / fps, end)
|
299 |
+
vlen = (end - start) * fps
|
300 |
+
else:
|
301 |
+
vlen = len(img_list)
|
302 |
+
|
303 |
+
duration = vlen / fps
|
304 |
+
|
305 |
+
if min_num_frames > vlen:
|
306 |
+
if sample == 'dynamic_fps1':
|
307 |
+
min_num_frames = (vlen // local_num_frames) * local_num_frames
|
308 |
+
else:
|
309 |
+
min_num_frames = vlen
|
310 |
+
|
311 |
+
if sample == 'dynamic_fps1':
|
312 |
+
num_segments = int(duration // local_num_frames)
|
313 |
+
if num_segments == 0:
|
314 |
+
num_frames = local_num_frames
|
315 |
+
else:
|
316 |
+
num_frames = local_num_frames * num_segments
|
317 |
+
num_frames = min(num_frames, max_num_frames)
|
318 |
+
num_frames = max(min_num_frames, num_frames)
|
319 |
+
|
320 |
+
num_frames = int(num_frames)
|
321 |
+
if clip is not None:
|
322 |
+
def _get_index_by_time(start_sec, end_sec, num_segments=8, fps=1., max_frame=9999):
|
323 |
+
start_idx = max(1, round(start_sec * fps))
|
324 |
+
end_idx = min(round(end_sec * fps), max_frame)
|
325 |
+
seg_size = float(end_idx - start_idx) / (num_segments - 1)
|
326 |
+
offsets = np.array([start_idx + int(np.round(seg_size * idx)) for idx in range(num_segments)])
|
327 |
+
return offsets
|
328 |
+
|
329 |
+
frame_indices = _get_index_by_time(float(clip[0]), float(clip[1]), num_segments=num_frames, fps=fps, max_frame=len(img_list)-1)
|
330 |
+
else:
|
331 |
+
frame_indices = get_frame_indices(
|
332 |
+
num_frames, vlen, sample=sample, fix_start=fix_start,
|
333 |
+
min_num_frames=min_num_frames,
|
334 |
+
max_num_frames=max_num_frames, local_num_frames=local_num_frames
|
335 |
+
)
|
336 |
+
|
337 |
+
imgs = []
|
338 |
+
for idx in frame_indices:
|
339 |
+
frame_fname = os.path.join(video_path, img_list[idx])
|
340 |
+
if "s3://" in video_path:
|
341 |
+
img_bytes = client.get(frame_fname)
|
342 |
+
else:
|
343 |
+
with open(frame_fname, 'rb') as f:
|
344 |
+
img_bytes = f.read()
|
345 |
+
img_np = np.frombuffer(img_bytes, np.uint8)
|
346 |
+
img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
|
347 |
+
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
|
348 |
+
imgs.append(img)
|
349 |
+
|
350 |
+
frames = np.array(imgs, dtype=np.uint8)
|
351 |
+
|
352 |
+
|
353 |
+
return frames, frame_indices, fps, duration
|
354 |
+
|
355 |
+
|
356 |
+
|
357 |
+
VIDEO_READER_FUNCS = {
|
358 |
+
'av': read_frames_av,
|
359 |
+
'decord': read_frames_decord,
|
360 |
+
'gif': read_frames_gif,
|
361 |
+
'img': read_frames_img,
|
362 |
+
'frame': read_frames_img
|
363 |
+
}
|
364 |
+
|
365 |
+
|
366 |
+
|
367 |
+
def load_video(video_path, max_num_frames=512, media_dict=None): #, media_dict):
|
368 |
+
|
369 |
+
if media_dict is None:
|
370 |
+
media_dict = {'video_read_type': 'decord'}
|
371 |
+
|
372 |
+
if type(video_path) != str:
|
373 |
+
assert len(video_path) == 1, video_path
|
374 |
+
video_path = video_path[0]
|
375 |
+
|
376 |
+
if 'start' in media_dict:
|
377 |
+
clip = [media_dict['start'], media_dict['end']]
|
378 |
+
else:
|
379 |
+
clip = None
|
380 |
+
|
381 |
+
|
382 |
+
client = None
|
383 |
+
|
384 |
+
frames, frame_indices, fps, duration = VIDEO_READER_FUNCS[media_dict['video_read_type']](video_path=video_path, num_frames=max_num_frames, sample='dynamic_fps1', fix_start=None, min_num_frames=64, max_num_frames=max_num_frames, client=client, clip=clip, local_num_frames=8)
|
385 |
+
|
386 |
+
sec = [str(round(f / fps, 1)) for f in frame_indices]
|
387 |
+
|
388 |
+
msg = f"\nThe video lasts for {duration:.2f} seconds, and {len(sec)} frames are uniformly sampled from it. "
|
389 |
+
|
390 |
+
return frames, msg
|
391 |
+
|
392 |
+
|
393 |
+
######################## load video ########################
|
394 |
+
|
395 |
+
|
396 |
+
def resize_and_center_crop(image, shortest_edge_length):
|
397 |
+
# Calculate new dimensions and resize
|
398 |
+
aspect_ratio = float(image.width) / float(image.height)
|
399 |
+
if aspect_ratio > 1:
|
400 |
+
new_width = int(shortest_edge_length * aspect_ratio)
|
401 |
+
new_height = shortest_edge_length
|
402 |
+
else:
|
403 |
+
new_width = shortest_edge_length
|
404 |
+
new_height = int(shortest_edge_length / aspect_ratio)
|
405 |
+
resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
|
406 |
+
|
407 |
+
# Calculate the position and perform the center crop
|
408 |
+
left = (new_width - shortest_edge_length) / 2
|
409 |
+
top = (new_height - shortest_edge_length) / 2
|
410 |
+
right = (new_width + shortest_edge_length) / 2
|
411 |
+
bottom = (new_height + shortest_edge_length) / 2
|
412 |
+
cropped_image = resized_image.crop((left, top, right, bottom))
|
413 |
+
|
414 |
+
return cropped_image
|
415 |
+
|
416 |
+
|
417 |
+
def auto_pad_images(image, grid_params):
|
418 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
419 |
+
assert len(grid_params) > 0, "Grid parameters should not be empty"
|
420 |
+
|
421 |
+
# Step 1: Calculate and find the closest aspect ratio
|
422 |
+
input_width, input_height = image.size
|
423 |
+
input_aspect_ratio = input_width / input_height
|
424 |
+
candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
|
425 |
+
closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
|
426 |
+
|
427 |
+
candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
|
428 |
+
|
429 |
+
target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
|
430 |
+
|
431 |
+
resize_width, resize_height = target_resolution
|
432 |
+
if input_width > input_height:
|
433 |
+
resize_height = int(resize_width / input_aspect_ratio)
|
434 |
+
else:
|
435 |
+
resize_width = int(resize_height * input_aspect_ratio)
|
436 |
+
resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
|
437 |
+
|
438 |
+
# Step 5: Pad the resized image if necessary to match the target resolution
|
439 |
+
pad_width = target_resolution[0] - resize_width
|
440 |
+
pad_height = target_resolution[1] - resize_height
|
441 |
+
padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
|
442 |
+
padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
|
443 |
+
|
444 |
+
return padded_image
|
445 |
+
|
446 |
+
|
447 |
+
def extract_patches(image, patch_size, overlap_ratio):
|
448 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
449 |
+
assert patch_size > 0, "Patch size should be greater than 0"
|
450 |
+
assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
|
451 |
+
|
452 |
+
W, H = image.size
|
453 |
+
patches = []
|
454 |
+
|
455 |
+
stride = int(patch_size * (1 - overlap_ratio))
|
456 |
+
|
457 |
+
num_patches_y = (H - patch_size) // stride + 1
|
458 |
+
num_patches_x = (W - patch_size) // stride + 1
|
459 |
+
|
460 |
+
y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
|
461 |
+
x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
|
462 |
+
|
463 |
+
for y in range(y_start, y_start + num_patches_y * stride, stride):
|
464 |
+
for x in range(x_start, x_start + num_patches_x * stride, stride):
|
465 |
+
patch = image.crop((x, y, x + patch_size, y + patch_size))
|
466 |
+
patches.append(patch)
|
467 |
+
|
468 |
+
return patches
|
469 |
+
|
470 |
+
|
471 |
+
def process_highres_image_crop_split(image, data_args, processor=None):
|
472 |
+
crop_resolution = data_args.image_crop_resolution
|
473 |
+
split_resolution = data_args.image_split_resolution
|
474 |
+
if processor is None:
|
475 |
+
processor = data_args.image_processor
|
476 |
+
image_crop = resize_and_center_crop(image, crop_resolution)
|
477 |
+
image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
|
478 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
479 |
+
return torch.stack(image_patches, dim=0)
|
480 |
+
|
481 |
+
|
482 |
+
def process_highres_image(image, processor, grid_pinpoints):
|
483 |
+
grid_params = [int(x) for x in grid_pinpoints.split(",")]
|
484 |
+
width_height = max(image.size)
|
485 |
+
fit_grid_params = [x for x in grid_params if x >= width_height]
|
486 |
+
if len(fit_grid_params) == 0:
|
487 |
+
select_size = max(grid_params)
|
488 |
+
else:
|
489 |
+
select_size = min(fit_grid_params)
|
490 |
+
# FIXME: always select the 448
|
491 |
+
select_size = max(grid_params)
|
492 |
+
image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
|
493 |
+
|
494 |
+
# FIXME: this seems to be a bug that it always resizes instead of padding
|
495 |
+
image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
|
496 |
+
image_padded = image_padded.resize((select_size, select_size))
|
497 |
+
image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
|
498 |
+
image_patches = [image_original_resize] + image_patches
|
499 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
500 |
+
return torch.stack(image_patches, dim=0)
|
501 |
+
|
502 |
+
|
503 |
+
def select_best_resolution(original_size, possible_resolutions, max_resolutions, patch_size):
|
504 |
+
"""
|
505 |
+
Selects the best resolution from a list of possible resolutions based on the original size.
|
506 |
+
|
507 |
+
Args:
|
508 |
+
original_size (tuple): The original size of the image in the format (width, height).
|
509 |
+
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
|
510 |
+
|
511 |
+
Returns:
|
512 |
+
tuple: The best fit resolution in the format (width, height).
|
513 |
+
"""
|
514 |
+
original_width, original_height = original_size
|
515 |
+
best_fit = None
|
516 |
+
max_effective_resolution = 0
|
517 |
+
min_wasted_resolution = float("inf")
|
518 |
+
|
519 |
+
for width, height in possible_resolutions:
|
520 |
+
if max_resolutions != None and (width * height != patch_size * patch_size):
|
521 |
+
if (width * height+patch_size*patch_size) > max_resolutions: # NOTE 要算一个global
|
522 |
+
continue
|
523 |
+
# Calculate the downscaled size to keep the aspect ratio
|
524 |
+
scale = min(width / original_width, height / original_height)
|
525 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
526 |
+
|
527 |
+
# Calculate effective and wasted resolutions
|
528 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
529 |
+
wasted_resolution = (width * height) - effective_resolution
|
530 |
+
|
531 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
532 |
+
max_effective_resolution = effective_resolution
|
533 |
+
min_wasted_resolution = wasted_resolution
|
534 |
+
best_fit = (width, height)
|
535 |
+
|
536 |
+
# print(f"original_size={original_size}, possible_resolutions={possible_resolutions}, max_resolutions={max_resolutions}, best_fit={best_fit}")
|
537 |
+
assert best_fit is not None, f"Can't find suitable fit in {possible_resolutions} at max:{max_resolutions}"
|
538 |
+
return best_fit
|
539 |
+
|
540 |
+
|
541 |
+
def resize_and_pad_image(image, target_resolution):
|
542 |
+
"""
|
543 |
+
Resize and pad an image to a target resolution while maintaining aspect ratio.
|
544 |
+
|
545 |
+
Args:
|
546 |
+
image (PIL.Image.Image): The input image.
|
547 |
+
target_resolution (tuple): The target resolution (width, height) of the image.
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
PIL.Image.Image: The resized and padded image.
|
551 |
+
"""
|
552 |
+
original_width, original_height = image.size
|
553 |
+
target_width, target_height = target_resolution
|
554 |
+
|
555 |
+
# Determine which dimension (width or height) to fill
|
556 |
+
scale_w = target_width / original_width
|
557 |
+
scale_h = target_height / original_height
|
558 |
+
|
559 |
+
if scale_w < scale_h:
|
560 |
+
# Width will be filled completely
|
561 |
+
new_width = target_width
|
562 |
+
new_height = min(math.ceil(original_height * scale_w), target_height)
|
563 |
+
else:
|
564 |
+
# Height will be filled completely
|
565 |
+
new_height = target_height
|
566 |
+
new_width = min(math.ceil(original_width * scale_h), target_width)
|
567 |
+
|
568 |
+
# Resize the image
|
569 |
+
resized_image = image.resize((new_width, new_height))
|
570 |
+
|
571 |
+
# Create a new image with the target size and paste the resized image onto it
|
572 |
+
new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
|
573 |
+
paste_x = (target_width - new_width) // 2
|
574 |
+
paste_y = (target_height - new_height) // 2
|
575 |
+
new_image.paste(resized_image, (paste_x, paste_y))
|
576 |
+
|
577 |
+
return new_image
|
578 |
+
|
579 |
+
|
580 |
+
def divide_to_patches(image, patch_size):
|
581 |
+
"""
|
582 |
+
Divides an image into patches of a specified size.
|
583 |
+
|
584 |
+
Args:
|
585 |
+
image (PIL.Image.Image): The input image.
|
586 |
+
patch_size (int): The size of each patch.
|
587 |
+
|
588 |
+
Returns:
|
589 |
+
list: A list of PIL.Image.Image objects representing the patches.
|
590 |
+
"""
|
591 |
+
patches = []
|
592 |
+
width, height = image.size
|
593 |
+
for i in range(0, height, patch_size):
|
594 |
+
for j in range(0, width, patch_size):
|
595 |
+
box = (j, i, j + patch_size, i + patch_size)
|
596 |
+
patch = image.crop(box)
|
597 |
+
patches.append(patch)
|
598 |
+
|
599 |
+
return patches
|
600 |
+
|
601 |
+
|
602 |
+
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size, max_resolutions=None):
|
603 |
+
"""
|
604 |
+
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
|
605 |
+
|
606 |
+
Args:
|
607 |
+
image_size (tuple): The size of the input image in the format (width, height).
|
608 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
609 |
+
patch_size (int): The size of each image patch.
|
610 |
+
|
611 |
+
Returns:
|
612 |
+
tuple: The shape of the image patch grid in the format (width, height).
|
613 |
+
"""
|
614 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
615 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
616 |
+
# Use regex to extract the range from the input string
|
617 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
618 |
+
range_start = tuple(map(int, matches[0]))
|
619 |
+
range_end = tuple(map(int, matches[-1]))
|
620 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
621 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
622 |
+
# Multiply all elements by patch_size
|
623 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
624 |
+
if type(grid_pinpoints) is list:
|
625 |
+
possible_resolutions = grid_pinpoints
|
626 |
+
else:
|
627 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
628 |
+
width, height = select_best_resolution(image_size, possible_resolutions, max_resolutions=max_resolutions, patch_size=patch_size)
|
629 |
+
|
630 |
+
# print("get width/patch size", width, patch_size, flush=True)
|
631 |
+
|
632 |
+
return width // patch_size, height // patch_size
|
633 |
+
|
634 |
+
|
635 |
+
def process_anyres_image(image, processor, grid_pinpoints):
|
636 |
+
"""
|
637 |
+
Process an image with variable resolutions.
|
638 |
+
|
639 |
+
Args:
|
640 |
+
image (PIL.Image.Image): The input image to be processed.
|
641 |
+
processor: The image processor object.
|
642 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
643 |
+
|
644 |
+
Returns:
|
645 |
+
torch.Tensor: A tensor containing the processed image patches.
|
646 |
+
"""
|
647 |
+
raise NotImplementedError
|
648 |
+
# Convert grid_pinpoints from string to list
|
649 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
650 |
+
try:
|
651 |
+
patch_size = processor.size[0]
|
652 |
+
except Exception as e:
|
653 |
+
patch_size = processor.size["shortest_edge"]
|
654 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
655 |
+
# Use regex to extract the range from the input string
|
656 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
657 |
+
range_start = tuple(map(int, matches[0]))
|
658 |
+
range_end = tuple(map(int, matches[-1]))
|
659 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
660 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
661 |
+
# Multiply all elements by patch_size
|
662 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
663 |
+
|
664 |
+
if type(grid_pinpoints) is list:
|
665 |
+
possible_resolutions = grid_pinpoints
|
666 |
+
else:
|
667 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
668 |
+
best_resolution = select_best_resolution(image.size, possible_resolutions)
|
669 |
+
image_padded = resize_and_pad_image(image, best_resolution)
|
670 |
+
|
671 |
+
patches = divide_to_patches(image_padded, processor.crop_size["height"])
|
672 |
+
|
673 |
+
# FIXME: this seems to be a bug that it resizes instead of pad.
|
674 |
+
# but to keep it consistent with previous, i will keep it as it is
|
675 |
+
# TODO: uncomment below to ablate with the padding
|
676 |
+
if isinstance(processor.size, dict):
|
677 |
+
shortest_edge = processor.size["shortest_edge"]
|
678 |
+
else:
|
679 |
+
shortest_edge = min(processor.size)
|
680 |
+
image_original_resize = image.resize((shortest_edge, shortest_edge))
|
681 |
+
# image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
682 |
+
# image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
683 |
+
|
684 |
+
image_patches = [image_original_resize] + patches
|
685 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
686 |
+
|
687 |
+
# print("image.size", image.size, "len(image_patches):", len(image_patches), "patch_size:", image_patches[0].shape)
|
688 |
+
return torch.stack(image_patches, dim=0)
|
689 |
+
|
690 |
+
def process_anyres_image_nopad(image, processor, grid_pinpoints):
|
691 |
+
"""
|
692 |
+
Process an image with variable resolutions.
|
693 |
+
|
694 |
+
Args:
|
695 |
+
image (PIL.Image.Image): The input image to be processed.
|
696 |
+
processor: The image processor object.
|
697 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
698 |
+
|
699 |
+
Returns:
|
700 |
+
torch.Tensor: A tensor containing the processed image patches.
|
701 |
+
"""
|
702 |
+
# Convert grid_pinpoints from string to list
|
703 |
+
try:
|
704 |
+
patch_size = processor.size[0]
|
705 |
+
except Exception as e:
|
706 |
+
patch_size = processor.size["shortest_edge"]
|
707 |
+
|
708 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
709 |
+
|
710 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
711 |
+
|
712 |
+
# Use regex to extract the range from the input string
|
713 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
714 |
+
range_start = tuple(map(int, matches[0]))
|
715 |
+
range_end = tuple(map(int, matches[-1]))
|
716 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
717 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
718 |
+
# Multiply all elements by patch_size
|
719 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
720 |
+
|
721 |
+
if type(grid_pinpoints) is list:
|
722 |
+
possible_resolutions = grid_pinpoints
|
723 |
+
else:
|
724 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
725 |
+
best_resolution = select_best_resolution(image.size, possible_resolutions, max_resolutions=None, patch_size=patch_size) # 目前图像无限制
|
726 |
+
# image_padded = resize_and_pad_image(image, best_resolution)
|
727 |
+
|
728 |
+
patches = divide_to_patches(image.resize(best_resolution), patch_size)
|
729 |
+
|
730 |
+
# FIXME: this seems to be a bug that it resizes instead of pad.
|
731 |
+
# but to keep it consistent with previous, i will keep it as it is
|
732 |
+
# TODO: uncomment below to ablate with the padding
|
733 |
+
if isinstance(processor.size, dict):
|
734 |
+
shortest_edge = processor.size["shortest_edge"]
|
735 |
+
else:
|
736 |
+
shortest_edge = min(processor.size)
|
737 |
+
image_original_resize = image.resize((shortest_edge, shortest_edge))
|
738 |
+
# image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
739 |
+
# image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
740 |
+
|
741 |
+
image_patches = [image_original_resize] + patches
|
742 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
743 |
+
|
744 |
+
# raise ValueError(f"image.size: {image.size} len(image_patches): {len(image_patches)}, patch_size:, {image_patches[0].shape}, possible_resolutions:, {possible_resolutions}, best: {best_resolution}")
|
745 |
+
return torch.stack(image_patches, dim=0)
|
746 |
+
|
747 |
+
|
748 |
+
def load_image_from_base64(image):
|
749 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
750 |
+
|
751 |
+
|
752 |
+
def expand2square(pil_img, background_color):
|
753 |
+
width, height = pil_img.size
|
754 |
+
if width == height:
|
755 |
+
return pil_img
|
756 |
+
elif width > height:
|
757 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
758 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
759 |
+
return result
|
760 |
+
else:
|
761 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
762 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
763 |
+
return result
|
764 |
+
|
765 |
+
|
766 |
+
def process_images(images, image_processor, model_cfg):
|
767 |
+
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
768 |
+
new_images = []
|
769 |
+
if image_aspect_ratio == "highres":
|
770 |
+
raise NotImplementedError
|
771 |
+
for image in images:
|
772 |
+
image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
773 |
+
new_images.append(image)
|
774 |
+
elif "anyres" in image_aspect_ratio:
|
775 |
+
for image in images:
|
776 |
+
if "nopad" in image_aspect_ratio:
|
777 |
+
image = process_anyres_image_nopad(image, image_processor, model_cfg.image_grid_pinpoints)
|
778 |
+
else:
|
779 |
+
image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
780 |
+
new_images.append(image)
|
781 |
+
elif image_aspect_ratio == "crop_split":
|
782 |
+
raise NotImplementedError
|
783 |
+
for image in images:
|
784 |
+
image = process_highres_image_crop_split(image, model_cfg, image_processor)
|
785 |
+
new_images.append(image)
|
786 |
+
elif image_aspect_ratio == "pad":
|
787 |
+
for image in images:
|
788 |
+
image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
|
789 |
+
image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
|
790 |
+
new_images.append(image)
|
791 |
+
else:
|
792 |
+
return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
|
793 |
+
if all(x.shape == new_images[0].shape for x in new_images):
|
794 |
+
new_images = torch.stack(new_images, dim=0)
|
795 |
+
return new_images
|
796 |
+
|
797 |
+
|
798 |
+
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
799 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
|
800 |
+
|
801 |
+
def insert_separator(X, sep):
|
802 |
+
return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
|
803 |
+
|
804 |
+
input_ids = []
|
805 |
+
offset = 0
|
806 |
+
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
807 |
+
offset = 1
|
808 |
+
input_ids.append(prompt_chunks[0][0])
|
809 |
+
|
810 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
811 |
+
input_ids.extend(x[offset:])
|
812 |
+
|
813 |
+
if return_tensors is not None:
|
814 |
+
if return_tensors == "pt":
|
815 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
816 |
+
raise ValueError(f"Unsupported tensor type: {return_tensors}")
|
817 |
+
return input_ids
|
818 |
+
|
819 |
+
|
820 |
+
def get_model_name_from_path(model_path):
|
821 |
+
model_path = model_path.strip("/")
|
822 |
+
model_paths = model_path.split("/")
|
823 |
+
if model_paths[-1].startswith("checkpoint-"):
|
824 |
+
return model_paths[-2] + "_" + model_paths[-1]
|
825 |
+
else:
|
826 |
+
return model_paths[-1]
|
827 |
+
|
828 |
+
|
829 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
830 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
831 |
+
self.keywords = keywords
|
832 |
+
self.keyword_ids = []
|
833 |
+
for keyword in keywords:
|
834 |
+
cur_keyword_ids = tokenizer(keyword).input_ids
|
835 |
+
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
836 |
+
cur_keyword_ids = cur_keyword_ids[1:]
|
837 |
+
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
838 |
+
self.tokenizer = tokenizer
|
839 |
+
self.start_len = input_ids.shape[1]
|
840 |
+
|
841 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
842 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
843 |
+
offset = min(output_ids.shape[1] - self.start_len, 3)
|
844 |
+
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
845 |
+
for keyword_id in self.keyword_ids:
|
846 |
+
if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
|
847 |
+
return True
|
848 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
849 |
+
for keyword in self.keywords:
|
850 |
+
if keyword in outputs:
|
851 |
+
return True
|
852 |
+
return False
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b28e4935375bd056b0a8a8756e151a79ab92b2e8f3eb28ceee0cb3607cbbac9c
|
3 |
+
size 4997418264
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:41e2bb894136fffc6128c94f2458a7f4fa4263403d0d3b42cc43c6f08321afaf
|
3 |
+
size 4999754984
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9559bd7ed20929eeafba7793c9a8cca581fabf27e3ab18b598473a19e0978bfd
|
3 |
+
size 4998910488
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:66338e387f62ebc1f4a480bcf30837b55f2561af2409fda64a41d716debd8176
|
3 |
+
size 1324572984
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 16320578048
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
7 |
+
"model.embed_tokens.weight": "model-00001-of-00004.safetensors",
|
8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
13 |
+
"model.layers.0.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
14 |
+
"model.layers.0.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
15 |
+
"model.layers.0.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
16 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
17 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
18 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
19 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
20 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
21 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
22 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
23 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
24 |
+
"model.layers.1.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
25 |
+
"model.layers.1.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
26 |
+
"model.layers.1.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
27 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
28 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
29 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
30 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
31 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
32 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
33 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
34 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
35 |
+
"model.layers.10.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
36 |
+
"model.layers.10.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
37 |
+
"model.layers.10.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
38 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
39 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
40 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
41 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
42 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
43 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
44 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
45 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
46 |
+
"model.layers.11.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
47 |
+
"model.layers.11.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
48 |
+
"model.layers.11.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
49 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
50 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
51 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
52 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
53 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
54 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
55 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
56 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
57 |
+
"model.layers.12.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
58 |
+
"model.layers.12.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
59 |
+
"model.layers.12.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
60 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
61 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
62 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
63 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
64 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
65 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
66 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
67 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
68 |
+
"model.layers.13.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
69 |
+
"model.layers.13.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
70 |
+
"model.layers.13.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
71 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
72 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
73 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
74 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
75 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
76 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
77 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
78 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
79 |
+
"model.layers.14.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
80 |
+
"model.layers.14.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
81 |
+
"model.layers.14.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
82 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
83 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
84 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
85 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
86 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
87 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
88 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
89 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
90 |
+
"model.layers.15.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
91 |
+
"model.layers.15.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
92 |
+
"model.layers.15.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
93 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
94 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
95 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
96 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
97 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
98 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
99 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
100 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
101 |
+
"model.layers.16.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
102 |
+
"model.layers.16.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
103 |
+
"model.layers.16.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
104 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
105 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
106 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
107 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
108 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
109 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
110 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
111 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
112 |
+
"model.layers.17.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
113 |
+
"model.layers.17.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
114 |
+
"model.layers.17.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
115 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
116 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
117 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
118 |
+
"model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
119 |
+
"model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
120 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
121 |
+
"model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
122 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
123 |
+
"model.layers.18.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
124 |
+
"model.layers.18.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
125 |
+
"model.layers.18.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
126 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
127 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
128 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
129 |
+
"model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
130 |
+
"model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
131 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
132 |
+
"model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
133 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
134 |
+
"model.layers.19.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
135 |
+
"model.layers.19.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
136 |
+
"model.layers.19.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
137 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
138 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
139 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
140 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
141 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
142 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
143 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
144 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
145 |
+
"model.layers.2.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
146 |
+
"model.layers.2.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
147 |
+
"model.layers.2.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
148 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
149 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
150 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
151 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
152 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
153 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
154 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
155 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
156 |
+
"model.layers.20.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
157 |
+
"model.layers.20.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
158 |
+
"model.layers.20.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
159 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
160 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
161 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
162 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
163 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
164 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
165 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
166 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
167 |
+
"model.layers.21.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
168 |
+
"model.layers.21.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
169 |
+
"model.layers.21.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
170 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
171 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
172 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
173 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
174 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
175 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
176 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
177 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
178 |
+
"model.layers.22.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
179 |
+
"model.layers.22.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
180 |
+
"model.layers.22.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
181 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
182 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
183 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
184 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
185 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
186 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
187 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
188 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
189 |
+
"model.layers.23.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
190 |
+
"model.layers.23.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
191 |
+
"model.layers.23.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
192 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
193 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
194 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
195 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
196 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
197 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
198 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
199 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
200 |
+
"model.layers.24.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
201 |
+
"model.layers.24.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
202 |
+
"model.layers.24.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
203 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
204 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
205 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
206 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
207 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
208 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
209 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
210 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
211 |
+
"model.layers.25.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
212 |
+
"model.layers.25.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
213 |
+
"model.layers.25.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
214 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
215 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
216 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
217 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
218 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
219 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
220 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
221 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
222 |
+
"model.layers.26.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
223 |
+
"model.layers.26.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
224 |
+
"model.layers.26.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
225 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
226 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
227 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
228 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
229 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
230 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
231 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
232 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
233 |
+
"model.layers.27.self_attn.kv_a_proj_with_mqa.bias": "model-00003-of-00004.safetensors",
|
234 |
+
"model.layers.27.self_attn.kv_a_proj_with_mqa.weight": "model-00003-of-00004.safetensors",
|
235 |
+
"model.layers.27.self_attn.kv_b_proj.weight": "model-00003-of-00004.safetensors",
|
236 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
237 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
238 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
239 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
240 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
241 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
242 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
243 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
244 |
+
"model.layers.3.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
245 |
+
"model.layers.3.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
246 |
+
"model.layers.3.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
247 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
248 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
249 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
250 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
251 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
252 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
253 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
254 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
255 |
+
"model.layers.4.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
256 |
+
"model.layers.4.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
257 |
+
"model.layers.4.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
258 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
259 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
260 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
261 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
262 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
263 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
264 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
265 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
266 |
+
"model.layers.5.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
267 |
+
"model.layers.5.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
268 |
+
"model.layers.5.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
269 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
270 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
271 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
272 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
273 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
274 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
275 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
276 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
277 |
+
"model.layers.6.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
278 |
+
"model.layers.6.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
279 |
+
"model.layers.6.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
280 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
281 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
282 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
283 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
284 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
285 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
286 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
287 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
288 |
+
"model.layers.7.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
289 |
+
"model.layers.7.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
290 |
+
"model.layers.7.self_attn.kv_b_proj.weight": "model-00001-of-00004.safetensors",
|
291 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
292 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
293 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
294 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
295 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
296 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
297 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
298 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
299 |
+
"model.layers.8.self_attn.kv_a_proj_with_mqa.bias": "model-00001-of-00004.safetensors",
|
300 |
+
"model.layers.8.self_attn.kv_a_proj_with_mqa.weight": "model-00001-of-00004.safetensors",
|
301 |
+
"model.layers.8.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
302 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
303 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
304 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
305 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
306 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
307 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
308 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
309 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
310 |
+
"model.layers.9.self_attn.kv_a_proj_with_mqa.bias": "model-00002-of-00004.safetensors",
|
311 |
+
"model.layers.9.self_attn.kv_a_proj_with_mqa.weight": "model-00002-of-00004.safetensors",
|
312 |
+
"model.layers.9.self_attn.kv_b_proj.weight": "model-00002-of-00004.safetensors",
|
313 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
314 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
315 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
316 |
+
"model.mm_projector.mlp.0.bias": "model-00004-of-00004.safetensors",
|
317 |
+
"model.mm_projector.mlp.0.weight": "model-00004-of-00004.safetensors",
|
318 |
+
"model.mm_projector.mlp.2.bias": "model-00004-of-00004.safetensors",
|
319 |
+
"model.mm_projector.mlp.2.weight": "model-00004-of-00004.safetensors",
|
320 |
+
"model.norm.weight": "model-00003-of-00004.safetensors",
|
321 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.attn.proj.bias": "model-00003-of-00004.safetensors",
|
322 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.attn.proj.weight": "model-00003-of-00004.safetensors",
|
323 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.attn.q_bias": "model-00003-of-00004.safetensors",
|
324 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
325 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.attn.v_bias": "model-00003-of-00004.safetensors",
|
326 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
327 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
328 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
329 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
330 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.norm1.bias": "model-00003-of-00004.safetensors",
|
331 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.norm1.weight": "model-00003-of-00004.safetensors",
|
332 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.norm2.bias": "model-00003-of-00004.safetensors",
|
333 |
+
"model.vision_tower.vision_tower.encoder.blocks.0.norm2.weight": "model-00003-of-00004.safetensors",
|
334 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.attn.proj.bias": "model-00003-of-00004.safetensors",
|
335 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.attn.proj.weight": "model-00003-of-00004.safetensors",
|
336 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.attn.q_bias": "model-00003-of-00004.safetensors",
|
337 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
338 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.attn.v_bias": "model-00003-of-00004.safetensors",
|
339 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
340 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
341 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
342 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
343 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.norm1.bias": "model-00003-of-00004.safetensors",
|
344 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.norm1.weight": "model-00003-of-00004.safetensors",
|
345 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.norm2.bias": "model-00003-of-00004.safetensors",
|
346 |
+
"model.vision_tower.vision_tower.encoder.blocks.1.norm2.weight": "model-00003-of-00004.safetensors",
|
347 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.attn.proj.bias": "model-00003-of-00004.safetensors",
|
348 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.attn.proj.weight": "model-00003-of-00004.safetensors",
|
349 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.attn.q_bias": "model-00003-of-00004.safetensors",
|
350 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
351 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.attn.v_bias": "model-00003-of-00004.safetensors",
|
352 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
353 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
354 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
355 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
356 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.norm1.bias": "model-00003-of-00004.safetensors",
|
357 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.norm1.weight": "model-00003-of-00004.safetensors",
|
358 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.norm2.bias": "model-00003-of-00004.safetensors",
|
359 |
+
"model.vision_tower.vision_tower.encoder.blocks.10.norm2.weight": "model-00003-of-00004.safetensors",
|
360 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.attn.proj.bias": "model-00003-of-00004.safetensors",
|
361 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.attn.proj.weight": "model-00003-of-00004.safetensors",
|
362 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.attn.q_bias": "model-00003-of-00004.safetensors",
|
363 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
364 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.attn.v_bias": "model-00003-of-00004.safetensors",
|
365 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
366 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
367 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
368 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
369 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.norm1.bias": "model-00003-of-00004.safetensors",
|
370 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.norm1.weight": "model-00003-of-00004.safetensors",
|
371 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.norm2.bias": "model-00003-of-00004.safetensors",
|
372 |
+
"model.vision_tower.vision_tower.encoder.blocks.11.norm2.weight": "model-00003-of-00004.safetensors",
|
373 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.attn.proj.bias": "model-00003-of-00004.safetensors",
|
374 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.attn.proj.weight": "model-00003-of-00004.safetensors",
|
375 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.attn.q_bias": "model-00003-of-00004.safetensors",
|
376 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
377 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.attn.v_bias": "model-00003-of-00004.safetensors",
|
378 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
379 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
380 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
381 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
382 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.norm1.bias": "model-00003-of-00004.safetensors",
|
383 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.norm1.weight": "model-00003-of-00004.safetensors",
|
384 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.norm2.bias": "model-00003-of-00004.safetensors",
|
385 |
+
"model.vision_tower.vision_tower.encoder.blocks.12.norm2.weight": "model-00003-of-00004.safetensors",
|
386 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.attn.proj.bias": "model-00003-of-00004.safetensors",
|
387 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.attn.proj.weight": "model-00003-of-00004.safetensors",
|
388 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.attn.q_bias": "model-00003-of-00004.safetensors",
|
389 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
390 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.attn.v_bias": "model-00003-of-00004.safetensors",
|
391 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
392 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
393 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
394 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
395 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.norm1.bias": "model-00003-of-00004.safetensors",
|
396 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.norm1.weight": "model-00003-of-00004.safetensors",
|
397 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.norm2.bias": "model-00003-of-00004.safetensors",
|
398 |
+
"model.vision_tower.vision_tower.encoder.blocks.13.norm2.weight": "model-00003-of-00004.safetensors",
|
399 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.attn.proj.bias": "model-00003-of-00004.safetensors",
|
400 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.attn.proj.weight": "model-00003-of-00004.safetensors",
|
401 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.attn.q_bias": "model-00003-of-00004.safetensors",
|
402 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
403 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.attn.v_bias": "model-00003-of-00004.safetensors",
|
404 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
405 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
406 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
407 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
408 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.norm1.bias": "model-00003-of-00004.safetensors",
|
409 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.norm1.weight": "model-00003-of-00004.safetensors",
|
410 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.norm2.bias": "model-00003-of-00004.safetensors",
|
411 |
+
"model.vision_tower.vision_tower.encoder.blocks.14.norm2.weight": "model-00003-of-00004.safetensors",
|
412 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.attn.proj.bias": "model-00004-of-00004.safetensors",
|
413 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.attn.proj.weight": "model-00004-of-00004.safetensors",
|
414 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.attn.q_bias": "model-00003-of-00004.safetensors",
|
415 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
416 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.attn.v_bias": "model-00003-of-00004.safetensors",
|
417 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
418 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
419 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
420 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
421 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.norm1.bias": "model-00003-of-00004.safetensors",
|
422 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.norm1.weight": "model-00003-of-00004.safetensors",
|
423 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.norm2.bias": "model-00004-of-00004.safetensors",
|
424 |
+
"model.vision_tower.vision_tower.encoder.blocks.15.norm2.weight": "model-00004-of-00004.safetensors",
|
425 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.attn.proj.bias": "model-00004-of-00004.safetensors",
|
426 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.attn.proj.weight": "model-00004-of-00004.safetensors",
|
427 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.attn.q_bias": "model-00004-of-00004.safetensors",
|
428 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
429 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.attn.v_bias": "model-00004-of-00004.safetensors",
|
430 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
431 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
432 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
433 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
434 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.norm1.bias": "model-00004-of-00004.safetensors",
|
435 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.norm1.weight": "model-00004-of-00004.safetensors",
|
436 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.norm2.bias": "model-00004-of-00004.safetensors",
|
437 |
+
"model.vision_tower.vision_tower.encoder.blocks.16.norm2.weight": "model-00004-of-00004.safetensors",
|
438 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.attn.proj.bias": "model-00004-of-00004.safetensors",
|
439 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.attn.proj.weight": "model-00004-of-00004.safetensors",
|
440 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.attn.q_bias": "model-00004-of-00004.safetensors",
|
441 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
442 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.attn.v_bias": "model-00004-of-00004.safetensors",
|
443 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
444 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
445 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
446 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
447 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.norm1.bias": "model-00004-of-00004.safetensors",
|
448 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.norm1.weight": "model-00004-of-00004.safetensors",
|
449 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.norm2.bias": "model-00004-of-00004.safetensors",
|
450 |
+
"model.vision_tower.vision_tower.encoder.blocks.17.norm2.weight": "model-00004-of-00004.safetensors",
|
451 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.attn.proj.bias": "model-00004-of-00004.safetensors",
|
452 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.attn.proj.weight": "model-00004-of-00004.safetensors",
|
453 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.attn.q_bias": "model-00004-of-00004.safetensors",
|
454 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
455 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.attn.v_bias": "model-00004-of-00004.safetensors",
|
456 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
457 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
458 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
459 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
460 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.norm1.bias": "model-00004-of-00004.safetensors",
|
461 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.norm1.weight": "model-00004-of-00004.safetensors",
|
462 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.norm2.bias": "model-00004-of-00004.safetensors",
|
463 |
+
"model.vision_tower.vision_tower.encoder.blocks.18.norm2.weight": "model-00004-of-00004.safetensors",
|
464 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.attn.proj.bias": "model-00004-of-00004.safetensors",
|
465 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.attn.proj.weight": "model-00004-of-00004.safetensors",
|
466 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.attn.q_bias": "model-00004-of-00004.safetensors",
|
467 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
468 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.attn.v_bias": "model-00004-of-00004.safetensors",
|
469 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
470 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
471 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
472 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
473 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.norm1.bias": "model-00004-of-00004.safetensors",
|
474 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.norm1.weight": "model-00004-of-00004.safetensors",
|
475 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.norm2.bias": "model-00004-of-00004.safetensors",
|
476 |
+
"model.vision_tower.vision_tower.encoder.blocks.19.norm2.weight": "model-00004-of-00004.safetensors",
|
477 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.attn.proj.bias": "model-00003-of-00004.safetensors",
|
478 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.attn.proj.weight": "model-00003-of-00004.safetensors",
|
479 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.attn.q_bias": "model-00003-of-00004.safetensors",
|
480 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
481 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.attn.v_bias": "model-00003-of-00004.safetensors",
|
482 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
483 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
484 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
485 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
486 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.norm1.bias": "model-00003-of-00004.safetensors",
|
487 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.norm1.weight": "model-00003-of-00004.safetensors",
|
488 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.norm2.bias": "model-00003-of-00004.safetensors",
|
489 |
+
"model.vision_tower.vision_tower.encoder.blocks.2.norm2.weight": "model-00003-of-00004.safetensors",
|
490 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.attn.proj.bias": "model-00004-of-00004.safetensors",
|
491 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.attn.proj.weight": "model-00004-of-00004.safetensors",
|
492 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.attn.q_bias": "model-00004-of-00004.safetensors",
|
493 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
494 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.attn.v_bias": "model-00004-of-00004.safetensors",
|
495 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
496 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
497 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
498 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
499 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.norm1.bias": "model-00004-of-00004.safetensors",
|
500 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.norm1.weight": "model-00004-of-00004.safetensors",
|
501 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.norm2.bias": "model-00004-of-00004.safetensors",
|
502 |
+
"model.vision_tower.vision_tower.encoder.blocks.20.norm2.weight": "model-00004-of-00004.safetensors",
|
503 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.attn.proj.bias": "model-00004-of-00004.safetensors",
|
504 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.attn.proj.weight": "model-00004-of-00004.safetensors",
|
505 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.attn.q_bias": "model-00004-of-00004.safetensors",
|
506 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
507 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.attn.v_bias": "model-00004-of-00004.safetensors",
|
508 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
509 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
510 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
511 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
512 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.norm1.bias": "model-00004-of-00004.safetensors",
|
513 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.norm1.weight": "model-00004-of-00004.safetensors",
|
514 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.norm2.bias": "model-00004-of-00004.safetensors",
|
515 |
+
"model.vision_tower.vision_tower.encoder.blocks.21.norm2.weight": "model-00004-of-00004.safetensors",
|
516 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.attn.proj.bias": "model-00004-of-00004.safetensors",
|
517 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.attn.proj.weight": "model-00004-of-00004.safetensors",
|
518 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.attn.q_bias": "model-00004-of-00004.safetensors",
|
519 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.attn.qkv.weight": "model-00004-of-00004.safetensors",
|
520 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.attn.v_bias": "model-00004-of-00004.safetensors",
|
521 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc1.bias": "model-00004-of-00004.safetensors",
|
522 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc1.weight": "model-00004-of-00004.safetensors",
|
523 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc2.bias": "model-00004-of-00004.safetensors",
|
524 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc2.weight": "model-00004-of-00004.safetensors",
|
525 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.norm1.bias": "model-00004-of-00004.safetensors",
|
526 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.norm1.weight": "model-00004-of-00004.safetensors",
|
527 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.norm2.bias": "model-00004-of-00004.safetensors",
|
528 |
+
"model.vision_tower.vision_tower.encoder.blocks.22.norm2.weight": "model-00004-of-00004.safetensors",
|
529 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.attn.proj.bias": "model-00003-of-00004.safetensors",
|
530 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.attn.proj.weight": "model-00003-of-00004.safetensors",
|
531 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.attn.q_bias": "model-00003-of-00004.safetensors",
|
532 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
533 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.attn.v_bias": "model-00003-of-00004.safetensors",
|
534 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
535 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
536 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
537 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
538 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.norm1.bias": "model-00003-of-00004.safetensors",
|
539 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.norm1.weight": "model-00003-of-00004.safetensors",
|
540 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.norm2.bias": "model-00003-of-00004.safetensors",
|
541 |
+
"model.vision_tower.vision_tower.encoder.blocks.3.norm2.weight": "model-00003-of-00004.safetensors",
|
542 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.attn.proj.bias": "model-00003-of-00004.safetensors",
|
543 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.attn.proj.weight": "model-00003-of-00004.safetensors",
|
544 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.attn.q_bias": "model-00003-of-00004.safetensors",
|
545 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
546 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.attn.v_bias": "model-00003-of-00004.safetensors",
|
547 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
548 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
549 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
550 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
551 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.norm1.bias": "model-00003-of-00004.safetensors",
|
552 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.norm1.weight": "model-00003-of-00004.safetensors",
|
553 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.norm2.bias": "model-00003-of-00004.safetensors",
|
554 |
+
"model.vision_tower.vision_tower.encoder.blocks.4.norm2.weight": "model-00003-of-00004.safetensors",
|
555 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.attn.proj.bias": "model-00003-of-00004.safetensors",
|
556 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.attn.proj.weight": "model-00003-of-00004.safetensors",
|
557 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.attn.q_bias": "model-00003-of-00004.safetensors",
|
558 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
559 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.attn.v_bias": "model-00003-of-00004.safetensors",
|
560 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
561 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
562 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
563 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
564 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.norm1.bias": "model-00003-of-00004.safetensors",
|
565 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.norm1.weight": "model-00003-of-00004.safetensors",
|
566 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.norm2.bias": "model-00003-of-00004.safetensors",
|
567 |
+
"model.vision_tower.vision_tower.encoder.blocks.5.norm2.weight": "model-00003-of-00004.safetensors",
|
568 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.attn.proj.bias": "model-00003-of-00004.safetensors",
|
569 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.attn.proj.weight": "model-00003-of-00004.safetensors",
|
570 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.attn.q_bias": "model-00003-of-00004.safetensors",
|
571 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
572 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.attn.v_bias": "model-00003-of-00004.safetensors",
|
573 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
574 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
575 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
576 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
577 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.norm1.bias": "model-00003-of-00004.safetensors",
|
578 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.norm1.weight": "model-00003-of-00004.safetensors",
|
579 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.norm2.bias": "model-00003-of-00004.safetensors",
|
580 |
+
"model.vision_tower.vision_tower.encoder.blocks.6.norm2.weight": "model-00003-of-00004.safetensors",
|
581 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.attn.proj.bias": "model-00003-of-00004.safetensors",
|
582 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.attn.proj.weight": "model-00003-of-00004.safetensors",
|
583 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.attn.q_bias": "model-00003-of-00004.safetensors",
|
584 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
585 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.attn.v_bias": "model-00003-of-00004.safetensors",
|
586 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
587 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
588 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
589 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
590 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.norm1.bias": "model-00003-of-00004.safetensors",
|
591 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.norm1.weight": "model-00003-of-00004.safetensors",
|
592 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.norm2.bias": "model-00003-of-00004.safetensors",
|
593 |
+
"model.vision_tower.vision_tower.encoder.blocks.7.norm2.weight": "model-00003-of-00004.safetensors",
|
594 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.attn.proj.bias": "model-00003-of-00004.safetensors",
|
595 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.attn.proj.weight": "model-00003-of-00004.safetensors",
|
596 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.attn.q_bias": "model-00003-of-00004.safetensors",
|
597 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
598 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.attn.v_bias": "model-00003-of-00004.safetensors",
|
599 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
600 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
601 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
602 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
603 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.norm1.bias": "model-00003-of-00004.safetensors",
|
604 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.norm1.weight": "model-00003-of-00004.safetensors",
|
605 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.norm2.bias": "model-00003-of-00004.safetensors",
|
606 |
+
"model.vision_tower.vision_tower.encoder.blocks.8.norm2.weight": "model-00003-of-00004.safetensors",
|
607 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.attn.proj.bias": "model-00003-of-00004.safetensors",
|
608 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.attn.proj.weight": "model-00003-of-00004.safetensors",
|
609 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.attn.q_bias": "model-00003-of-00004.safetensors",
|
610 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.attn.qkv.weight": "model-00003-of-00004.safetensors",
|
611 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.attn.v_bias": "model-00003-of-00004.safetensors",
|
612 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc1.bias": "model-00003-of-00004.safetensors",
|
613 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc1.weight": "model-00003-of-00004.safetensors",
|
614 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc2.bias": "model-00003-of-00004.safetensors",
|
615 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc2.weight": "model-00003-of-00004.safetensors",
|
616 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.norm1.bias": "model-00003-of-00004.safetensors",
|
617 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.norm1.weight": "model-00003-of-00004.safetensors",
|
618 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.norm2.bias": "model-00003-of-00004.safetensors",
|
619 |
+
"model.vision_tower.vision_tower.encoder.blocks.9.norm2.weight": "model-00003-of-00004.safetensors",
|
620 |
+
"model.vision_tower.vision_tower.encoder.patch_embed.proj.bias": "model-00003-of-00004.safetensors",
|
621 |
+
"model.vision_tower.vision_tower.encoder.patch_embed.proj.weight": "model-00003-of-00004.safetensors",
|
622 |
+
"model.vision_tower.vision_tower.encoder.vision_layernorm.bias": "model-00004-of-00004.safetensors",
|
623 |
+
"model.vision_tower.vision_tower.encoder.vision_layernorm.weight": "model-00004-of-00004.safetensors"
|
624 |
+
}
|
625 |
+
}
|
modeling_qwen2_mla.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Tuple, Union
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from transformers.cache_utils import Cache
|
7 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
8 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
9 |
+
from transformers.processing_utils import Unpack
|
10 |
+
|
11 |
+
from transformers.models.qwen2.modeling_qwen2 import (
|
12 |
+
Qwen2Model,
|
13 |
+
Qwen2DecoderLayer,
|
14 |
+
Qwen2PreTrainedModel,
|
15 |
+
Qwen2ForCausalLM
|
16 |
+
)
|
17 |
+
from .configuration_qwen2_mla import Qwen2MLAConfig
|
18 |
+
|
19 |
+
from transformers.models.gemma2.modeling_gemma2 import (
|
20 |
+
eager_attention_forward, # for supporting softcap
|
21 |
+
logger
|
22 |
+
)
|
23 |
+
from transformers.models.deepseek_v3.modeling_deepseek_v3 import (
|
24 |
+
apply_rotary_pos_emb_interleave,
|
25 |
+
DeepseekV3RMSNorm
|
26 |
+
)
|
27 |
+
|
28 |
+
|
29 |
+
class MLAAttention(nn.Module):
|
30 |
+
"""
|
31 |
+
Modified from `transformers.models.llama.modeling_deepseek_v3.DeepseekV3Attention`
|
32 |
+
add support for attention bias and softcapping
|
33 |
+
"""
|
34 |
+
def __init__(self, config, layer_idx: int):
|
35 |
+
|
36 |
+
super().__init__()
|
37 |
+
self.config = config
|
38 |
+
self.layer_idx = layer_idx
|
39 |
+
|
40 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
41 |
+
self.attention_dropout = config.attention_dropout
|
42 |
+
self.num_heads = config.num_attention_heads
|
43 |
+
self.rope_theta = config.rope_theta
|
44 |
+
self.q_lora_rank = config.q_lora_rank
|
45 |
+
self.kv_lora_rank = config.kv_lora_rank
|
46 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
47 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
48 |
+
self.v_head_dim = config.v_head_dim
|
49 |
+
self.qk_head_dim = config.qk_head_dim
|
50 |
+
|
51 |
+
self.qk_latent_layernorm = getattr(config, "qk_latent_layernorm", True)
|
52 |
+
|
53 |
+
self.is_causal = True
|
54 |
+
if self.q_lora_rank is None:
|
55 |
+
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=config.attention_bias)
|
56 |
+
else:
|
57 |
+
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
|
58 |
+
if self.qk_latent_layernorm:
|
59 |
+
self.q_a_layernorm = DeepseekV3RMSNorm(self.q_lora_rank)
|
60 |
+
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=config.attention_bias)
|
61 |
+
|
62 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
63 |
+
config.hidden_size,
|
64 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
65 |
+
bias=config.attention_bias,
|
66 |
+
)
|
67 |
+
if self.qk_latent_layernorm:
|
68 |
+
self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
|
69 |
+
self.kv_b_proj = nn.Linear(
|
70 |
+
self.kv_lora_rank,
|
71 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
72 |
+
bias=False,
|
73 |
+
)
|
74 |
+
|
75 |
+
self.o_proj = nn.Linear(
|
76 |
+
self.num_heads * self.v_head_dim,
|
77 |
+
config.hidden_size,
|
78 |
+
bias=False,
|
79 |
+
)
|
80 |
+
|
81 |
+
self.scaling = self.qk_head_dim**-0.5
|
82 |
+
|
83 |
+
def forward(
|
84 |
+
self,
|
85 |
+
hidden_states: torch.Tensor,
|
86 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
87 |
+
attention_mask: Optional[torch.Tensor],
|
88 |
+
past_key_value: Optional[Cache] = None,
|
89 |
+
cache_position: Optional[torch.LongTensor] = None,
|
90 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
91 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
92 |
+
batch_size, seq_length = hidden_states.shape[:-1]
|
93 |
+
query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
|
94 |
+
key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
|
95 |
+
|
96 |
+
if self.q_lora_rank is None:
|
97 |
+
q_states = self.q_proj(hidden_states)
|
98 |
+
elif self.qk_latent_layernorm:
|
99 |
+
q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
100 |
+
else:
|
101 |
+
q_states = self.q_b_proj(self.q_a_proj(hidden_states))
|
102 |
+
q_states = q_states.view(query_shape).transpose(1, 2)
|
103 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
104 |
+
|
105 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
106 |
+
k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
107 |
+
|
108 |
+
if self.qk_latent_layernorm:
|
109 |
+
k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
|
110 |
+
else:
|
111 |
+
k_pass = self.kv_b_proj(k_pass).view(key_shape).transpose(1, 2)
|
112 |
+
k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
113 |
+
|
114 |
+
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
|
115 |
+
|
116 |
+
cos, sin = position_embeddings
|
117 |
+
q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
|
118 |
+
k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
|
119 |
+
|
120 |
+
query_states = torch.cat((q_pass, q_rot), dim=-1)
|
121 |
+
key_states = torch.cat((k_pass, k_rot), dim=-1)
|
122 |
+
|
123 |
+
if past_key_value is not None:
|
124 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
125 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
126 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
127 |
+
|
128 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
129 |
+
value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
|
130 |
+
|
131 |
+
attention_interface = eager_attention_forward
|
132 |
+
if self.config._attn_implementation != "eager":
|
133 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
134 |
+
logger.warning_once(
|
135 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
136 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
137 |
+
)
|
138 |
+
else:
|
139 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
140 |
+
|
141 |
+
attn_output, attn_weights = attention_interface(
|
142 |
+
self,
|
143 |
+
query_states,
|
144 |
+
key_states,
|
145 |
+
value_states,
|
146 |
+
attention_mask,
|
147 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
148 |
+
scaling=self.scaling,
|
149 |
+
softcap=getattr(self.config, "attn_logit_softcapping", None),
|
150 |
+
**kwargs,
|
151 |
+
)
|
152 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
153 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
154 |
+
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
|
155 |
+
attn_output = self.o_proj(attn_output)
|
156 |
+
return attn_output, attn_weights
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
class Qwen2MLADecoderLayer(Qwen2DecoderLayer):
|
161 |
+
"""
|
162 |
+
Qwen2 decoder layer with MLA (Multi-Head Latent Attention) instead of standard attention.
|
163 |
+
This class inherits from Qwen2DecoderLayer and only replaces the self_attn component.
|
164 |
+
"""
|
165 |
+
|
166 |
+
def __init__(self, config: Qwen2MLAConfig, layer_idx: int):
|
167 |
+
super().__init__(config, layer_idx)
|
168 |
+
# Replace the standard Qwen2 attention with MLA attention
|
169 |
+
self.self_attn = MLAAttention(config, layer_idx)
|
170 |
+
|
171 |
+
|
172 |
+
class Qwen2MLAPreTrainedModel(Qwen2PreTrainedModel):
|
173 |
+
"""
|
174 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
175 |
+
models for Qwen2 with MLA attention.
|
176 |
+
"""
|
177 |
+
|
178 |
+
config_class = Qwen2MLAConfig
|
179 |
+
_no_split_modules = ["Qwen2MLADecoderLayer"]
|
180 |
+
|
181 |
+
|
182 |
+
class Qwen2MLAModel(Qwen2MLAPreTrainedModel, Qwen2Model):
|
183 |
+
"""
|
184 |
+
The Qwen2 model with MLA attention layers.
|
185 |
+
|
186 |
+
This model inherits from both Qwen2MLAPreTrainedModel and Qwen2Model,
|
187 |
+
replacing the standard Qwen2 decoder layers with MLA-enabled ones.
|
188 |
+
"""
|
189 |
+
|
190 |
+
def __init__(self, config: Qwen2MLAConfig):
|
191 |
+
super().__init__(config)
|
192 |
+
|
193 |
+
# Replace the layers with MLA-enabled decoder layers
|
194 |
+
self.layers = nn.ModuleList(
|
195 |
+
[Qwen2MLADecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
196 |
+
)
|
197 |
+
|
198 |
+
|
199 |
+
class Qwen2MLAForCausalLM(Qwen2MLAPreTrainedModel, Qwen2ForCausalLM):
|
200 |
+
"""
|
201 |
+
The Qwen2 model with MLA attention for causal language modeling.
|
202 |
+
|
203 |
+
This model can be used for text generation tasks, providing the same
|
204 |
+
interface as Qwen2ForCausalLM but with MLA attention mechanism.
|
205 |
+
"""
|
206 |
+
|
207 |
+
def __init__(self, config: Qwen2MLAConfig):
|
208 |
+
super().__init__(config)
|
209 |
+
# Replace the base model with the MLA version
|
210 |
+
self.model = Qwen2MLAModel(config)
|
211 |
+
|
212 |
+
|
213 |
+
# Export the main classes for external use
|
214 |
+
__all__ = [
|
215 |
+
"Qwen2MLAForCausalLM",
|
216 |
+
"Qwen2MLAModel",
|
217 |
+
"Qwen2MLAPreTrainedModel",
|
218 |
+
]
|
modeling_videochat_flash.py
ADDED
@@ -0,0 +1,716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
from abc import ABC, abstractmethod
|
16 |
+
import re
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
import random
|
20 |
+
from typing import List, Optional, Tuple, Union, Dict
|
21 |
+
|
22 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
23 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
24 |
+
from transformers.generation.utils import GenerateOutput
|
25 |
+
|
26 |
+
from .vision_tower_builder import build_vision_tower
|
27 |
+
from .mm_projector_builder import build_vision_projector
|
28 |
+
|
29 |
+
from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
|
30 |
+
from .conversation import conv_templates, SeparatorStyle
|
31 |
+
from .mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, get_anyres_image_grid_shape, load_video
|
32 |
+
from .modeling_qwen2_mla import Qwen2MLAModel, Qwen2MLAForCausalLM
|
33 |
+
|
34 |
+
|
35 |
+
from .configuration_qwen2_mla import Qwen2MLAConfig
|
36 |
+
|
37 |
+
|
38 |
+
|
39 |
+
class LlavaMetaModel:
|
40 |
+
|
41 |
+
def __init__(self, config):
|
42 |
+
super(LlavaMetaModel, self).__init__(config)
|
43 |
+
|
44 |
+
if hasattr(config, "mm_vision_tower"):
|
45 |
+
delay_load = getattr(config, "delay_load", False)
|
46 |
+
self.vision_tower = build_vision_tower(config, delay_load=delay_load)
|
47 |
+
self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
|
48 |
+
|
49 |
+
if "unpad" in getattr(config, "mm_patch_merge_type", ""):
|
50 |
+
self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
51 |
+
if "nopad" in getattr(config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
|
52 |
+
self.frame_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
53 |
+
|
54 |
+
def get_vision_tower(self):
|
55 |
+
vision_tower = getattr(self, "vision_tower", None)
|
56 |
+
if type(vision_tower) is list:
|
57 |
+
vision_tower = vision_tower[0]
|
58 |
+
return vision_tower
|
59 |
+
|
60 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
61 |
+
vision_tower = model_args.vision_tower
|
62 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
63 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
64 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
65 |
+
mm_patch_merge_type = model_args.mm_patch_merge_type
|
66 |
+
|
67 |
+
self.config.mm_vision_tower = vision_tower
|
68 |
+
self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
|
69 |
+
|
70 |
+
if self.get_vision_tower() is None:
|
71 |
+
vision_tower = build_vision_tower(model_args)
|
72 |
+
|
73 |
+
if fsdp is not None and len(fsdp) > 0:
|
74 |
+
self.vision_tower = [vision_tower]
|
75 |
+
else:
|
76 |
+
self.vision_tower = vision_tower
|
77 |
+
else:
|
78 |
+
if fsdp is not None and len(fsdp) > 0:
|
79 |
+
vision_tower = self.vision_tower[0]
|
80 |
+
else:
|
81 |
+
vision_tower = self.vision_tower
|
82 |
+
vision_tower.load_model()
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
self.config.use_mm_proj = True
|
87 |
+
self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
|
88 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
89 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
90 |
+
self.config.mm_patch_merge_type = mm_patch_merge_type
|
91 |
+
|
92 |
+
if getattr(self, "mm_projector", None) is None:
|
93 |
+
self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
|
94 |
+
|
95 |
+
if "unpad" in mm_patch_merge_type:
|
96 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
97 |
+
self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
98 |
+
if "nopad" in getattr(self.config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
|
99 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
100 |
+
self.frame_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
101 |
+
else:
|
102 |
+
# In case it is frozen by LoRA
|
103 |
+
for p in self.mm_projector.parameters():
|
104 |
+
p.requires_grad = True
|
105 |
+
|
106 |
+
if pretrain_mm_mlp_adapter is not None:
|
107 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
|
108 |
+
|
109 |
+
def get_w(weights, keyword):
|
110 |
+
return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
|
111 |
+
|
112 |
+
if self.config.mm_projector_type =='lxh_qformer':
|
113 |
+
incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"), strict=False)
|
114 |
+
else:
|
115 |
+
incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
|
116 |
+
print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
117 |
+
|
118 |
+
|
119 |
+
class LlavaMetaForCausalLM(ABC):
|
120 |
+
|
121 |
+
@abstractmethod
|
122 |
+
def get_model(self):
|
123 |
+
pass
|
124 |
+
|
125 |
+
def get_vision_tower(self):
|
126 |
+
return self.get_model().get_vision_tower()
|
127 |
+
|
128 |
+
|
129 |
+
def encode_video_image(self, images_list, video_idx_in_batch):
|
130 |
+
# video encoder编码后按图像的connector处理
|
131 |
+
bs = len(images_list)
|
132 |
+
|
133 |
+
concat_images = []
|
134 |
+
concat_videos = []
|
135 |
+
for idx, image in enumerate(images_list):
|
136 |
+
if idx in video_idx_in_batch:
|
137 |
+
concat_videos.append(image)
|
138 |
+
else:
|
139 |
+
concat_images.append(image)
|
140 |
+
# print(concat_videos[0].shape)
|
141 |
+
has_image = len(concat_images) > 0
|
142 |
+
has_video = len(concat_videos) > 0
|
143 |
+
|
144 |
+
mm_local_num_frames = getattr(self.config, "mm_local_num_frames", -1)
|
145 |
+
assert mm_local_num_frames != -1
|
146 |
+
if has_image:
|
147 |
+
image_split_sizes = [image.shape[0] for image in concat_images]
|
148 |
+
concat_images = torch.cat([image.unsqueeze(1) for image in concat_images], dim=0)
|
149 |
+
# print("input vit image.shape:", concat_images.shape)
|
150 |
+
images_features = self.get_model().get_vision_tower()(concat_images) # B_i, N, D
|
151 |
+
images_features = torch.split(images_features, image_split_sizes)
|
152 |
+
|
153 |
+
if has_video:
|
154 |
+
video_split_sizes = [video.shape[0] // mm_local_num_frames for video in concat_videos]
|
155 |
+
concat_videos = torch.cat([video.reshape(video.shape[0] // mm_local_num_frames, mm_local_num_frames, video.shape[1], video.shape[2], video.shape[3]) for video in concat_videos], dim=0)
|
156 |
+
# print("input vit video.shape:", concat_videos.shape)
|
157 |
+
videos_features = self.get_model().get_vision_tower()(concat_videos) # B_v, N, D
|
158 |
+
videos_features = [v.reshape(-1, v.shape[-2] // mm_local_num_frames, v.shape[-1]) for v in torch.split(videos_features, video_split_sizes)]
|
159 |
+
|
160 |
+
|
161 |
+
all_videos_or_images_features = []
|
162 |
+
img_idx = 0
|
163 |
+
vid_idx = 0
|
164 |
+
|
165 |
+
for idx in range(bs):
|
166 |
+
|
167 |
+
if idx in video_idx_in_batch:
|
168 |
+
feat = self.get_model().mm_projector(videos_features[vid_idx], compress=True, local_num_frames=getattr(self.config, "mm_local_num_frames", -1))
|
169 |
+
|
170 |
+
vid_idx += 1
|
171 |
+
else:
|
172 |
+
feat = self.get_model().mm_projector(images_features[img_idx], compress=False)
|
173 |
+
img_idx += 1
|
174 |
+
# print("video_idx_in_batch:", video_idx_in_batch)
|
175 |
+
all_videos_or_images_features.append(feat)
|
176 |
+
|
177 |
+
if has_video:
|
178 |
+
assert vid_idx == len(videos_features), f"vid: {vid_idx} != {len(videos_features)}"
|
179 |
+
if has_image:
|
180 |
+
assert img_idx == len(images_features), f"img: {img_idx} != {len(images_features)}"
|
181 |
+
|
182 |
+
return all_videos_or_images_features
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
|
187 |
+
assert type(modalities) is list, modalities
|
188 |
+
|
189 |
+
vision_tower = self.get_vision_tower()
|
190 |
+
# rank_print(modalities)
|
191 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
192 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
193 |
+
|
194 |
+
if type(images) is list or images.ndim == 5:
|
195 |
+
if type(images) is list:
|
196 |
+
images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
|
197 |
+
|
198 |
+
video_idx_in_batch = []
|
199 |
+
for _ in range(len(modalities)):
|
200 |
+
if modalities[_] == "video":
|
201 |
+
video_idx_in_batch.append(_)
|
202 |
+
|
203 |
+
images_list = []
|
204 |
+
for image in images:
|
205 |
+
if image.ndim == 4:
|
206 |
+
images_list.append(image)
|
207 |
+
else:
|
208 |
+
images_list.append(image.unsqueeze(0))
|
209 |
+
|
210 |
+
|
211 |
+
vision_encode_type = getattr(self.config, "vision_encode_type", "image")
|
212 |
+
mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
|
213 |
+
image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
|
214 |
+
frame_aspect_ratio = getattr(self.config, "frame_aspect_ratio", "square")
|
215 |
+
mm_newline_position = getattr(self.config, "mm_newline_position", "nothing")
|
216 |
+
|
217 |
+
|
218 |
+
if vision_encode_type == "video_image": # video backbone, process video with compress
|
219 |
+
image_features = self.encode_video_image(images_list, video_idx_in_batch=video_idx_in_batch)
|
220 |
+
else:
|
221 |
+
raise NotImplementedError(vision_encode_type)
|
222 |
+
|
223 |
+
|
224 |
+
if mm_patch_merge_type == "flat":
|
225 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
226 |
+
elif mm_patch_merge_type.startswith("spatial"):
|
227 |
+
new_image_features = []
|
228 |
+
for image_idx, image_feature in enumerate(image_features):
|
229 |
+
|
230 |
+
if image_idx in video_idx_in_batch: # video operations
|
231 |
+
|
232 |
+
if "anyres" in frame_aspect_ratio:
|
233 |
+
raise NotImplementedError
|
234 |
+
else:
|
235 |
+
frame_feature = image_feature
|
236 |
+
|
237 |
+
if "pad" in mm_patch_merge_type:
|
238 |
+
if mm_newline_position == 'one_token':
|
239 |
+
frame_feature = frame_feature.flatten(0, 1)
|
240 |
+
if "unpad" in mm_patch_merge_type:
|
241 |
+
frame_feature = torch.cat((frame_feature, self.model.image_newline[None].to(frame_feature.device)), dim=0)
|
242 |
+
else:
|
243 |
+
frame_feature = torch.cat((frame_feature, self.model.frame_newline[None].to(frame_feature.device)), dim=0)
|
244 |
+
elif mm_newline_position == 'nothing':
|
245 |
+
frame_feature = frame_feature.flatten(0, 1)
|
246 |
+
else:
|
247 |
+
raise NotImplementedError("add pad please!!")
|
248 |
+
else:
|
249 |
+
frame_feature = frame_feature.flatten(0, 1)
|
250 |
+
|
251 |
+
# print(f"final video frame_feature.shape: {frame_feature.shape}")
|
252 |
+
image_feature = frame_feature
|
253 |
+
|
254 |
+
elif image_feature.shape[0] > 1: # multi patches and multi images operations
|
255 |
+
base_image_feature = image_feature[0]
|
256 |
+
image_feature = image_feature[1:]
|
257 |
+
origin_size = image_feature.shape
|
258 |
+
|
259 |
+
height = width = self.get_model().mm_projector.num_image_patches_per_side
|
260 |
+
assert height * width == base_image_feature.shape[0], f"height:{height}, width: {width}, base_image_feature: {base_image_feature.shape}"
|
261 |
+
|
262 |
+
if "anyres_max" in image_aspect_ratio:
|
263 |
+
matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
|
264 |
+
if matched_anyres_max_num_patches:
|
265 |
+
max_num_patches = int(matched_anyres_max_num_patches.group(1))
|
266 |
+
|
267 |
+
if "anyres" in image_aspect_ratio:
|
268 |
+
if hasattr(self.get_vision_tower(), "image_size"):
|
269 |
+
vision_tower_image_size = self.get_vision_tower().image_size
|
270 |
+
else:
|
271 |
+
raise ValueError("vision_tower_image_size is not found in the vision tower.")
|
272 |
+
try:
|
273 |
+
num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size, max_resolutions=None)
|
274 |
+
except Exception as e:
|
275 |
+
print(f"Error: {e}")
|
276 |
+
raise e
|
277 |
+
# num_patch_width, num_patch_height = 2, 2
|
278 |
+
|
279 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
280 |
+
else:
|
281 |
+
raise NotImplementedError(image_aspect_ratio)
|
282 |
+
image_feature = image_feature.view(2, 2, height, width, -1)
|
283 |
+
|
284 |
+
if "maxpool2x2" in mm_patch_merge_type:
|
285 |
+
raise NotImplementedError
|
286 |
+
elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
|
287 |
+
raise NotImplementedError
|
288 |
+
elif "unpad" in mm_patch_merge_type:
|
289 |
+
raise NotImplementedError
|
290 |
+
else:
|
291 |
+
image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
|
292 |
+
image_feature = image_feature.flatten(0, 3)
|
293 |
+
if "nobase" in mm_patch_merge_type:
|
294 |
+
pass
|
295 |
+
else:
|
296 |
+
try:
|
297 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
298 |
+
except Exception as e:
|
299 |
+
raise ValueError(f"{num_patch_width} {num_patch_height} now: base_image_feature: {base_image_feature.shape}, {image_feature.shape}, image_sizes[image_idx]: {image_sizes[image_idx]}, origin_size: {origin_size}, {image_sizes[image_idx]}, {self.config.image_grid_pinpoints}, {vision_tower_image_size}")
|
300 |
+
else: # single image operations
|
301 |
+
image_feature = image_feature[0]
|
302 |
+
if "unpad" in mm_patch_merge_type:
|
303 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
|
304 |
+
|
305 |
+
# print(f"image/video_feature.shape: {image_feature.shape}")
|
306 |
+
new_image_features.append(image_feature)
|
307 |
+
image_features = new_image_features
|
308 |
+
else:
|
309 |
+
raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
|
310 |
+
else:
|
311 |
+
# raise NotImplementedError(f"images.shape={images.shape}, modalities={modalities}")
|
312 |
+
image_features = self.encode_image(images)
|
313 |
+
|
314 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
315 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
|
316 |
+
raise NotImplementedError
|
317 |
+
# print(f"Total images len(image_features: {len(image_features)}")
|
318 |
+
|
319 |
+
# Let's just add dummy tensors if they do not exist,
|
320 |
+
# it is a headache to deal with None all the time.
|
321 |
+
# But it is not ideal, and if you have a better idea,
|
322 |
+
# please open an issue / submit a PR, thanks.
|
323 |
+
_labels = labels
|
324 |
+
_position_ids = position_ids
|
325 |
+
_attention_mask = attention_mask
|
326 |
+
if attention_mask is None:
|
327 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
328 |
+
else:
|
329 |
+
attention_mask = attention_mask.bool()
|
330 |
+
if position_ids is None:
|
331 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
332 |
+
if labels is None:
|
333 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
334 |
+
|
335 |
+
|
336 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
337 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
338 |
+
|
339 |
+
new_input_embeds = []
|
340 |
+
new_labels = []
|
341 |
+
cur_image_idx = 0
|
342 |
+
|
343 |
+
mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
|
344 |
+
|
345 |
+
if mm_llm_compress:
|
346 |
+
self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
|
347 |
+
self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
|
348 |
+
self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
|
349 |
+
first_image_token_position = []
|
350 |
+
text_prompt_lens = []
|
351 |
+
else:
|
352 |
+
self.model.llm_compress_type = "attention"
|
353 |
+
self.model.llm_compress_layer_list = []
|
354 |
+
self.model.llm_image_token_ratio_list = []
|
355 |
+
first_image_token_position = []
|
356 |
+
text_prompt_lens = []
|
357 |
+
|
358 |
+
# rank_print("Inserting Images embedding")
|
359 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
360 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
361 |
+
|
362 |
+
if mm_llm_compress:
|
363 |
+
####### copy from pdrop, only support single image/video NOTE ##################
|
364 |
+
# record image position for further dropping
|
365 |
+
image_index = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
|
366 |
+
assert len(image_index) == 1, f"Only support singe/video: {image_index}"
|
367 |
+
if image_index == []:
|
368 |
+
first_image_token_position.append(-1)
|
369 |
+
else:
|
370 |
+
first_image_token_position.append(image_index[0])
|
371 |
+
|
372 |
+
|
373 |
+
# record input instruction length in inference mode
|
374 |
+
if not self.training:
|
375 |
+
if image_index == []:
|
376 |
+
assert num_images == 0, num_images
|
377 |
+
else:
|
378 |
+
assert num_images == 1, f"num_images={num_images}"
|
379 |
+
text_prompt_lens.append(cur_input_ids.shape[0] - num_images) # consider image place holder
|
380 |
+
|
381 |
+
###############################################
|
382 |
+
|
383 |
+
# print(f"num_images={num_images}")
|
384 |
+
if num_images == 0:
|
385 |
+
cur_image_features = image_features[cur_image_idx]
|
386 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
387 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
388 |
+
new_input_embeds.append(cur_input_embeds)
|
389 |
+
new_labels.append(labels[batch_idx])
|
390 |
+
cur_image_idx += 1
|
391 |
+
continue
|
392 |
+
|
393 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
394 |
+
cur_input_ids_noim = []
|
395 |
+
cur_labels = labels[batch_idx]
|
396 |
+
cur_labels_noim = []
|
397 |
+
for i in range(len(image_token_indices) - 1):
|
398 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
399 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
400 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
401 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
402 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
403 |
+
cur_new_input_embeds = []
|
404 |
+
cur_new_labels = []
|
405 |
+
|
406 |
+
for i in range(num_images + 1):
|
407 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
408 |
+
cur_new_labels.append(cur_labels_noim[i])
|
409 |
+
if i < num_images:
|
410 |
+
try:
|
411 |
+
cur_image_features = image_features[cur_image_idx]
|
412 |
+
except IndexError:
|
413 |
+
print(f"cur_image_idx={cur_image_idx} is not ok")
|
414 |
+
cur_image_features = image_features[cur_image_idx - 1]
|
415 |
+
cur_image_idx += 1
|
416 |
+
cur_new_input_embeds.append(cur_image_features)
|
417 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
418 |
+
|
419 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
420 |
+
|
421 |
+
# import pdb; pdb.set_trace()
|
422 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
423 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
424 |
+
|
425 |
+
new_input_embeds.append(cur_new_input_embeds)
|
426 |
+
new_labels.append(cur_new_labels)
|
427 |
+
|
428 |
+
|
429 |
+
if mm_llm_compress:
|
430 |
+
self.model.first_image_token_position = first_image_token_position
|
431 |
+
self.model.text_prompt_lens = text_prompt_lens
|
432 |
+
self.model.num_image_token_lens = [image_feature.shape[0] for image_feature in image_features]
|
433 |
+
|
434 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
435 |
+
tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
|
436 |
+
# rank_print("Finishing Inserting")
|
437 |
+
|
438 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
439 |
+
new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
440 |
+
|
441 |
+
# Combine them
|
442 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
443 |
+
batch_size = len(new_input_embeds)
|
444 |
+
|
445 |
+
new_input_embeds_padded = []
|
446 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
447 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
448 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
449 |
+
# print("Prepare pos id")
|
450 |
+
|
451 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
452 |
+
cur_len = cur_new_embed.shape[0]
|
453 |
+
if getattr(self.config, "tokenizer_padding_side", "right") == "left":
|
454 |
+
new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
|
455 |
+
if cur_len > 0:
|
456 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
457 |
+
attention_mask[i, -cur_len:] = True
|
458 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
459 |
+
else:
|
460 |
+
new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
|
461 |
+
if cur_len > 0:
|
462 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
463 |
+
attention_mask[i, :cur_len] = True
|
464 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
465 |
+
|
466 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
467 |
+
# print("tokenizer padding")
|
468 |
+
|
469 |
+
if _labels is None:
|
470 |
+
new_labels = None
|
471 |
+
else:
|
472 |
+
new_labels = new_labels_padded
|
473 |
+
|
474 |
+
if _attention_mask is None:
|
475 |
+
attention_mask = None
|
476 |
+
else:
|
477 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
478 |
+
|
479 |
+
if _position_ids is None:
|
480 |
+
position_ids = None
|
481 |
+
if getattr(self.config, "use_pos_skipping", False) and self.training:
|
482 |
+
position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
|
483 |
+
split_position = random.randint(0, new_input_embeds.size(1))
|
484 |
+
left_add = random.randint(0, self.config.pos_skipping_range)
|
485 |
+
right_add = random.randint(left_add, self.config.pos_skipping_range)
|
486 |
+
position_ids[:, :split_position] += left_add
|
487 |
+
position_ids[:, split_position:] += right_add
|
488 |
+
# import pdb; pdb.set_trace()
|
489 |
+
# print("Finish preparing")
|
490 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
491 |
+
|
492 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer):
|
493 |
+
if model_args.mm_use_im_patch_token:
|
494 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
495 |
+
self.resize_token_embeddings(len(tokenizer))
|
496 |
+
|
497 |
+
if model_args.mm_use_im_start_end:
|
498 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
499 |
+
self.resize_token_embeddings(len(tokenizer))
|
500 |
+
|
501 |
+
if num_new_tokens > 0:
|
502 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
503 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
504 |
+
|
505 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
506 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
507 |
+
|
508 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
509 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
510 |
+
|
511 |
+
if model_args.tune_mm_mlp_adapter:
|
512 |
+
for p in self.get_input_embeddings().parameters():
|
513 |
+
p.requires_grad = True
|
514 |
+
for p in self.get_output_embeddings().parameters():
|
515 |
+
p.requires_grad = False
|
516 |
+
|
517 |
+
if model_args.pretrain_mm_mlp_adapter:
|
518 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
|
519 |
+
embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
|
520 |
+
assert num_new_tokens == 2
|
521 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
522 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
523 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
524 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
525 |
+
else:
|
526 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
527 |
+
elif model_args.mm_use_im_patch_token:
|
528 |
+
if model_args.tune_mm_mlp_adapter:
|
529 |
+
for p in self.get_input_embeddings().parameters():
|
530 |
+
p.requires_grad = False
|
531 |
+
for p in self.get_output_embeddings().parameters():
|
532 |
+
p.requires_grad = False
|
533 |
+
|
534 |
+
|
535 |
+
|
536 |
+
class VideoChatFlashQwenConfig(Qwen2MLAConfig):
|
537 |
+
model_type = "videochat_flash_qwen"
|
538 |
+
|
539 |
+
|
540 |
+
class VideoChatFlashQwenModel(LlavaMetaModel, Qwen2MLAModel):
|
541 |
+
config_class = VideoChatFlashQwenConfig
|
542 |
+
|
543 |
+
def __init__(self, config: VideoChatFlashQwenConfig):
|
544 |
+
super(VideoChatFlashQwenModel, self).__init__(config)
|
545 |
+
|
546 |
+
|
547 |
+
class VideoChatFlashQwenForCausalLM(LlavaMetaForCausalLM, Qwen2MLAForCausalLM):
|
548 |
+
config_class = VideoChatFlashQwenConfig
|
549 |
+
|
550 |
+
def __init__(self, config):
|
551 |
+
# super(Qwen2MLAForCausalLM, self).__init__(config)
|
552 |
+
Qwen2MLAForCausalLM.__init__(self, config)
|
553 |
+
config.model_type = "videochat_flash_qwen"
|
554 |
+
# config.rope_scaling = None
|
555 |
+
|
556 |
+
self.model = VideoChatFlashQwenModel(config)
|
557 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
558 |
+
# Initialize weights and apply final processing
|
559 |
+
self.post_init()
|
560 |
+
|
561 |
+
def get_model(self):
|
562 |
+
return self.model
|
563 |
+
|
564 |
+
def forward(
|
565 |
+
self,
|
566 |
+
input_ids: torch.LongTensor = None,
|
567 |
+
attention_mask: Optional[torch.Tensor] = None,
|
568 |
+
position_ids: Optional[torch.LongTensor] = None,
|
569 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
570 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
571 |
+
labels: Optional[torch.LongTensor] = None,
|
572 |
+
use_cache: Optional[bool] = None,
|
573 |
+
output_attentions: Optional[bool] = None,
|
574 |
+
output_hidden_states: Optional[bool] = None,
|
575 |
+
images: Optional[torch.FloatTensor] = None,
|
576 |
+
image_sizes: Optional[List[List[int]]] = None,
|
577 |
+
return_dict: Optional[bool] = None,
|
578 |
+
modalities: Optional[List[str]] = ["image"],
|
579 |
+
dpo_forward: Optional[bool] = False,
|
580 |
+
cache_position=None,
|
581 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
582 |
+
|
583 |
+
if inputs_embeds is None:
|
584 |
+
(input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
|
585 |
+
|
586 |
+
# print("inputs_embeds.shape:", inputs_embeds.shape)
|
587 |
+
if dpo_forward:
|
588 |
+
raise NotImplementedError
|
589 |
+
else:
|
590 |
+
return super().forward(
|
591 |
+
input_ids=input_ids,
|
592 |
+
attention_mask=attention_mask,
|
593 |
+
position_ids=position_ids,
|
594 |
+
past_key_values=past_key_values,
|
595 |
+
inputs_embeds=inputs_embeds,
|
596 |
+
labels=labels,
|
597 |
+
use_cache=use_cache,
|
598 |
+
output_attentions=output_attentions,
|
599 |
+
output_hidden_states=output_hidden_states,
|
600 |
+
return_dict=return_dict,
|
601 |
+
)
|
602 |
+
|
603 |
+
@torch.no_grad()
|
604 |
+
def generate(
|
605 |
+
self,
|
606 |
+
inputs: Optional[torch.Tensor] = None,
|
607 |
+
images: Optional[torch.Tensor] = None,
|
608 |
+
image_sizes: Optional[torch.Tensor] = None,
|
609 |
+
modalities: Optional[List[str]] = ["image"],
|
610 |
+
**kwargs,
|
611 |
+
) -> Union[GenerateOutput, torch.LongTensor]:
|
612 |
+
position_ids = kwargs.pop("position_ids", None)
|
613 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
614 |
+
if "inputs_embeds" in kwargs:
|
615 |
+
raise NotImplementedError("`inputs_embeds` is not supported")
|
616 |
+
|
617 |
+
if images is not None:
|
618 |
+
(inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
|
619 |
+
else:
|
620 |
+
self.model.image_token_posi = [-1]
|
621 |
+
self.model.prompt_len = None
|
622 |
+
self.model.image_tokens = [0]
|
623 |
+
inputs_embeds = self.get_model().embed_tokens(inputs)
|
624 |
+
|
625 |
+
return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
|
626 |
+
|
627 |
+
@torch.no_grad()
|
628 |
+
def chat(self,
|
629 |
+
video_path,
|
630 |
+
tokenizer,
|
631 |
+
user_prompt,
|
632 |
+
chat_history=None,
|
633 |
+
return_history=True,
|
634 |
+
max_num_frames=512,
|
635 |
+
media_dict=None,
|
636 |
+
generation_config={}):
|
637 |
+
|
638 |
+
frames, time_msg = load_video(video_path, max_num_frames=max_num_frames, media_dict=media_dict)
|
639 |
+
|
640 |
+
image_sizes = [frames[0].shape[:2]]
|
641 |
+
|
642 |
+
frames = [self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.dtype).cuda()]
|
643 |
+
|
644 |
+
conv = conv_templates["qwen_2"].copy()
|
645 |
+
|
646 |
+
if chat_history is None or len(chat_history) == 0:
|
647 |
+
user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{time_msg.strip()} {user_prompt}'
|
648 |
+
else:
|
649 |
+
assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
|
650 |
+
for msg in chat_history:
|
651 |
+
conv.append_message(msg['role'], msg['content'])
|
652 |
+
|
653 |
+
conv.append_message(conv.roles[0], user_prompt)
|
654 |
+
conv.append_message(conv.roles[1], None)
|
655 |
+
|
656 |
+
prompt = conv.get_prompt()
|
657 |
+
|
658 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
|
659 |
+
|
660 |
+
if tokenizer.pad_token_id is None:
|
661 |
+
if "qwen" in tokenizer.name_or_path.lower():
|
662 |
+
print("Setting pad token to bos token for qwen model.")
|
663 |
+
tokenizer.pad_token_id = 151643
|
664 |
+
|
665 |
+
attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
|
666 |
+
|
667 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
668 |
+
keywords = [stop_str]
|
669 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
670 |
+
|
671 |
+
with torch.inference_mode():
|
672 |
+
output_ids = self.generate(
|
673 |
+
inputs=input_ids,
|
674 |
+
images=frames,
|
675 |
+
attention_mask=attention_masks,
|
676 |
+
modalities=["video"],
|
677 |
+
image_sizes=image_sizes,
|
678 |
+
use_cache=True,
|
679 |
+
stopping_criteria=[stopping_criteria],
|
680 |
+
**generation_config
|
681 |
+
)
|
682 |
+
|
683 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
684 |
+
if outputs.endswith(stop_str):
|
685 |
+
outputs = outputs[: -len(stop_str)]
|
686 |
+
|
687 |
+
outputs = outputs.strip()
|
688 |
+
|
689 |
+
# print(f"\033[91m== Question: \033[0m\n{prompt}\n")
|
690 |
+
# print(f"\033[91m== Response: \033[0m\n{outputs}\n")
|
691 |
+
|
692 |
+
if chat_history is None:
|
693 |
+
chat_history = []
|
694 |
+
|
695 |
+
chat_history.append({"role":conv.roles[0], "content":user_prompt})
|
696 |
+
chat_history.append({"role":conv.roles[1], "content":outputs})
|
697 |
+
if return_history:
|
698 |
+
return outputs, chat_history
|
699 |
+
else:
|
700 |
+
return outputs
|
701 |
+
|
702 |
+
|
703 |
+
|
704 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
705 |
+
images = kwargs.pop("images", None)
|
706 |
+
image_sizes = kwargs.pop("image_sizes", None)
|
707 |
+
inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
|
708 |
+
if images is not None:
|
709 |
+
inputs["images"] = images
|
710 |
+
if image_sizes is not None:
|
711 |
+
inputs["image_sizes"] = image_sizes
|
712 |
+
return inputs
|
713 |
+
|
714 |
+
|
715 |
+
AutoConfig.register("videochat_flash_qwen", VideoChatFlashQwenConfig)
|
716 |
+
AutoModelForCausalLM.register(VideoChatFlashQwenConfig, VideoChatFlashQwenForCausalLM)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|object_ref_start|>",
|
6 |
+
"<|object_ref_end|>",
|
7 |
+
"<|box_start|>",
|
8 |
+
"<|box_end|>",
|
9 |
+
"<|quad_start|>",
|
10 |
+
"<|quad_end|>",
|
11 |
+
"<|vision_start|>",
|
12 |
+
"<|vision_end|>",
|
13 |
+
"<|vision_pad|>",
|
14 |
+
"<|image_pad|>",
|
15 |
+
"<|video_pad|>"
|
16 |
+
],
|
17 |
+
"eos_token": {
|
18 |
+
"content": "<|im_end|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"pad_token": {
|
25 |
+
"content": "<|endoftext|>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": false,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
}
|
31 |
+
}
|
test.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8da3fb45df69e628d09809e88b3f3725568de5d094a45361dea2a54d3e205f17
|
3 |
+
size 608283
|
test.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModel, AutoTokenizer
|
2 |
+
import torch
|
3 |
+
from modeling_videochat_flash import VideoChatFlashQwenForCausalLM
|
4 |
+
|
5 |
+
# model setting
|
6 |
+
model_path = './'
|
7 |
+
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
9 |
+
model = VideoChatFlashQwenForCausalLM.from_pretrained(model_path).to(torch.bfloat16).cuda()
|
10 |
+
image_processor = model.get_vision_tower().image_processor
|
11 |
+
|
12 |
+
mm_llm_compress = False # use the global compress or not
|
13 |
+
if mm_llm_compress:
|
14 |
+
model.config.mm_llm_compress = True
|
15 |
+
model.config.llm_compress_type = "uniform0_attention"
|
16 |
+
model.config.llm_compress_layer_list = [4, 18]
|
17 |
+
model.config.llm_image_token_ratio_list = [1, 0.75, 0.25]
|
18 |
+
else:
|
19 |
+
model.config.mm_llm_compress = False
|
20 |
+
|
21 |
+
# evaluation setting
|
22 |
+
max_num_frames = 512
|
23 |
+
generation_config = dict(
|
24 |
+
do_sample=False,
|
25 |
+
temperature=0.0,
|
26 |
+
max_new_tokens=1024,
|
27 |
+
top_p=0.1,
|
28 |
+
num_beams=1
|
29 |
+
)
|
30 |
+
|
31 |
+
video_path = "test.mp4"
|
32 |
+
|
33 |
+
# single-turn conversation
|
34 |
+
question1 = "Describe this video in detail."
|
35 |
+
output1, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question1, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
|
36 |
+
|
37 |
+
print(output1)
|
38 |
+
|
39 |
+
# # multi-turn conversation
|
40 |
+
# question2 = "How many people appear in the video?"
|
41 |
+
# output2, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question2, chat_history=chat_history, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
|
42 |
+
|
43 |
+
# print(output2)
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:540b7fbf60b80e8293593a86960df91d2263723d69107ffc1afc89a7c08cda12
|
3 |
+
size 11422162
|
tokenizer_config.json
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
}
|
181 |
+
},
|
182 |
+
"additional_special_tokens": [
|
183 |
+
"<|im_start|>",
|
184 |
+
"<|im_end|>",
|
185 |
+
"<|object_ref_start|>",
|
186 |
+
"<|object_ref_end|>",
|
187 |
+
"<|box_start|>",
|
188 |
+
"<|box_end|>",
|
189 |
+
"<|quad_start|>",
|
190 |
+
"<|quad_end|>",
|
191 |
+
"<|vision_start|>",
|
192 |
+
"<|vision_end|>",
|
193 |
+
"<|vision_pad|>",
|
194 |
+
"<|image_pad|>",
|
195 |
+
"<|video_pad|>"
|
196 |
+
],
|
197 |
+
"bos_token": null,
|
198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
199 |
+
"clean_up_tokenization_spaces": false,
|
200 |
+
"eos_token": "<|im_end|>",
|
201 |
+
"errors": "replace",
|
202 |
+
"extra_special_tokens": {},
|
203 |
+
"model_max_length": 32768,
|
204 |
+
"pad_token": "<|endoftext|>",
|
205 |
+
"padding_side": "right",
|
206 |
+
"split_special_tokens": false,
|
207 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
208 |
+
"unk_token": null
|
209 |
+
}
|
vision_tower_builder.py
ADDED
@@ -0,0 +1,632 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Tuple, Union, Dict
|
2 |
+
from dataclasses import dataclass
|
3 |
+
from functools import partial, reduce
|
4 |
+
from PIL import Image
|
5 |
+
import os
|
6 |
+
from transformers.image_processing_utils import BatchFeature, get_size_dict
|
7 |
+
from transformers.image_transforms import (
|
8 |
+
convert_to_rgb,
|
9 |
+
normalize,
|
10 |
+
rescale,
|
11 |
+
resize,
|
12 |
+
to_channel_dimension_format,
|
13 |
+
)
|
14 |
+
from transformers.image_utils import (
|
15 |
+
ChannelDimension,
|
16 |
+
PILImageResampling,
|
17 |
+
to_numpy_array,
|
18 |
+
)
|
19 |
+
import numpy as np
|
20 |
+
import torch
|
21 |
+
import torch.nn as nn
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint as checkpoint
|
24 |
+
from functools import partial
|
25 |
+
try:
|
26 |
+
from flash_attn import flash_attn_qkvpacked_func
|
27 |
+
use_flash_attn = True
|
28 |
+
except:
|
29 |
+
use_flash_attn = False
|
30 |
+
print("You need to install flash_attn to be faster!")
|
31 |
+
|
32 |
+
try:
|
33 |
+
from timm.layers import drop_path, to_2tuple, trunc_normal_
|
34 |
+
except:
|
35 |
+
from timm.models.layers import drop_path, trunc_normal_, to_2tuple
|
36 |
+
|
37 |
+
|
38 |
+
|
39 |
+
class DropPath(nn.Module):
|
40 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
41 |
+
"""
|
42 |
+
def __init__(self, drop_prob=None):
|
43 |
+
super(DropPath, self).__init__()
|
44 |
+
self.drop_prob = drop_prob
|
45 |
+
|
46 |
+
def forward(self, x):
|
47 |
+
return drop_path(x, self.drop_prob, self.training)
|
48 |
+
|
49 |
+
def extra_repr(self) -> str:
|
50 |
+
return 'p={}'.format(self.drop_prob)
|
51 |
+
|
52 |
+
|
53 |
+
class Mlp(nn.Module):
|
54 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
55 |
+
super().__init__()
|
56 |
+
out_features = out_features or in_features
|
57 |
+
hidden_features = hidden_features or in_features
|
58 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
59 |
+
self.act = act_layer()
|
60 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
61 |
+
self.drop = nn.Dropout(drop)
|
62 |
+
|
63 |
+
def forward(self, x):
|
64 |
+
x = self.fc1(x)
|
65 |
+
x = self.act(x)
|
66 |
+
x = self.drop(x)
|
67 |
+
x = self.fc2(x)
|
68 |
+
x = self.drop(x)
|
69 |
+
return x
|
70 |
+
|
71 |
+
class Attention(nn.Module):
|
72 |
+
def __init__(
|
73 |
+
self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
|
74 |
+
proj_drop=0., attn_head_dim=None,
|
75 |
+
attn_type='flash_v2'):
|
76 |
+
|
77 |
+
if use_flash_attn:
|
78 |
+
attn_type = attn_type
|
79 |
+
else:
|
80 |
+
attn_type = 'origin'
|
81 |
+
|
82 |
+
print(attn_type)
|
83 |
+
|
84 |
+
super().__init__()
|
85 |
+
self.num_heads = num_heads
|
86 |
+
head_dim = dim // num_heads
|
87 |
+
if attn_head_dim is not None:
|
88 |
+
head_dim = attn_head_dim
|
89 |
+
all_head_dim = head_dim * self.num_heads
|
90 |
+
self.scale = qk_scale or head_dim ** -0.5
|
91 |
+
|
92 |
+
self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
|
93 |
+
if qkv_bias:
|
94 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
95 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
96 |
+
else:
|
97 |
+
self.q_bias = None
|
98 |
+
self.v_bias = None
|
99 |
+
|
100 |
+
if attn_type not in ['origin', 'flash_v2']:
|
101 |
+
raise NotImplementedError(f"Not support attn_type: {attn_type}")
|
102 |
+
|
103 |
+
# print('umt:', f'attn_type: {attn_type}')
|
104 |
+
|
105 |
+
self.attn_type = attn_type
|
106 |
+
if attn_type == 'flash_v2':
|
107 |
+
self.attn_drop = attn_drop
|
108 |
+
else:
|
109 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
110 |
+
self.proj = nn.Linear(all_head_dim, dim)
|
111 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
112 |
+
|
113 |
+
def forward(self, x):
|
114 |
+
B, N, C = x.shape
|
115 |
+
qkv_bias = None
|
116 |
+
if self.q_bias is not None:
|
117 |
+
qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
|
118 |
+
# qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
119 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
120 |
+
|
121 |
+
if self.attn_type == 'flash_v2':
|
122 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1)
|
123 |
+
x = flash_attn_qkvpacked_func(qkv, dropout_p=self.attn_drop, softmax_scale=self.scale, causal=False).reshape(B, N, -1)
|
124 |
+
else:
|
125 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
126 |
+
q, k, v = qkv[0], qkv[1], qkv[
|
127 |
+
2] # make torchscript happy (cannot use tensor as tuple)
|
128 |
+
# B num_heads N head_dim
|
129 |
+
|
130 |
+
q = q * self.scale
|
131 |
+
attn = (q @ k.transpose(-2, -1))
|
132 |
+
|
133 |
+
attn = attn.softmax(dim=-1)
|
134 |
+
attn = self.attn_drop(attn)
|
135 |
+
|
136 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
137 |
+
|
138 |
+
x = self.proj(x)
|
139 |
+
x = self.proj_drop(x)
|
140 |
+
return x
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
class Block(nn.Module):
|
146 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
147 |
+
drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
|
148 |
+
attn_head_dim=None):
|
149 |
+
super().__init__()
|
150 |
+
self.norm1 = norm_layer(dim)
|
151 |
+
self.attn = Attention(
|
152 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
153 |
+
attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim)
|
154 |
+
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
|
155 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
156 |
+
self.norm2 = norm_layer(dim)
|
157 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
158 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
159 |
+
|
160 |
+
if init_values > 0:
|
161 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
|
162 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
|
163 |
+
else:
|
164 |
+
self.gamma_1, self.gamma_2 = None, None
|
165 |
+
|
166 |
+
def forward(self, x):
|
167 |
+
if self.gamma_1 is None:
|
168 |
+
x = x + self.drop_path(self.attn(self.norm1(x)))
|
169 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
170 |
+
else:
|
171 |
+
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
|
172 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
173 |
+
return x
|
174 |
+
|
175 |
+
|
176 |
+
class PatchEmbed(nn.Module):
|
177 |
+
""" Image to Patch Embedding
|
178 |
+
"""
|
179 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, num_frames=16, tubelet_size=2):
|
180 |
+
super().__init__()
|
181 |
+
img_size = to_2tuple(img_size)
|
182 |
+
patch_size = to_2tuple(patch_size)
|
183 |
+
self.tubelet_size = int(tubelet_size)
|
184 |
+
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (num_frames // self.tubelet_size)
|
185 |
+
self.img_size = img_size
|
186 |
+
self.patch_size = patch_size
|
187 |
+
self.num_patches = num_patches
|
188 |
+
self.proj = nn.Conv3d(
|
189 |
+
in_channels=in_chans, out_channels=embed_dim,
|
190 |
+
kernel_size=(self.tubelet_size, patch_size[0], patch_size[1]),
|
191 |
+
stride=(self.tubelet_size, patch_size[0], patch_size[1])
|
192 |
+
)
|
193 |
+
# print('umt:', f'Num of patches: {num_patches}')
|
194 |
+
|
195 |
+
def forward(self, x, **kwargs):
|
196 |
+
B, C, T, H, W = x.shape
|
197 |
+
# FIXME look at relaxing size constraints
|
198 |
+
# assert H == self.img_size[0] and W == self.img_size[1], \
|
199 |
+
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
200 |
+
x = self.proj(x).flatten(2).transpose(1, 2)
|
201 |
+
return x
|
202 |
+
|
203 |
+
# sin-cos position encoding
|
204 |
+
# https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
|
205 |
+
def get_sinusoid_encoding_table(n_position, d_hid, ckpt_num_frame=-1, cur_frame=12):
|
206 |
+
''' Sinusoid position encoding table '''
|
207 |
+
# TODO: make it with torch instead of numpy
|
208 |
+
def get_position_angle_vec(position):
|
209 |
+
return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
|
210 |
+
|
211 |
+
if ckpt_num_frame != -1 and ckpt_num_frame != cur_frame:
|
212 |
+
# print('umt:', f"Interpolate position embedding")
|
213 |
+
# print('umt:', f"Testing frame: {cur_frame}")
|
214 |
+
# print('umt:', f"Checkpoint frame: {ckpt_num_frame}")
|
215 |
+
|
216 |
+
T = ckpt_num_frame # checkpoint frame
|
217 |
+
new_T = cur_frame # testing frame
|
218 |
+
n_position = n_position // new_T * T # generate checkpoint position embedding
|
219 |
+
sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
|
220 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
221 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
222 |
+
sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
|
223 |
+
# interpolate
|
224 |
+
P = int((n_position // T) ** 0.5)
|
225 |
+
C = d_hid
|
226 |
+
sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
|
227 |
+
sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
|
228 |
+
sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
|
229 |
+
sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
|
230 |
+
sinusoid_table = sinusoid_table.flatten(1, 3)
|
231 |
+
return sinusoid_table
|
232 |
+
else:
|
233 |
+
sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
|
234 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
235 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
236 |
+
return torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
|
237 |
+
|
238 |
+
|
239 |
+
def get_sinusoid_encoding_table2(n_position=784, d_hid=1024, cur_frame=8, ckpt_num_frame=4, pre_n_position=784):
|
240 |
+
''' Sinusoid position encoding table '''
|
241 |
+
# TODO: make it with torch instead of numpy
|
242 |
+
def get_position_angle_vec(position):
|
243 |
+
return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
|
244 |
+
|
245 |
+
# generate checkpoint position embedding
|
246 |
+
sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(pre_n_position)])
|
247 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
248 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
249 |
+
sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
|
250 |
+
|
251 |
+
# print(f"n_position: {n_position}")
|
252 |
+
# print(f"pre_n_position: {pre_n_position}")
|
253 |
+
|
254 |
+
if n_position != pre_n_position:
|
255 |
+
T = ckpt_num_frame # checkpoint frame
|
256 |
+
P = 14 # checkpoint size
|
257 |
+
C = d_hid
|
258 |
+
new_P = int((n_position // cur_frame) ** 0.5) # testing size
|
259 |
+
# print(f'Pretraining uses 14x14, but current version is {new_P}x{new_P}')
|
260 |
+
# print(f'Interpolate the position embedding')
|
261 |
+
sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
|
262 |
+
sinusoid_table = sinusoid_table.reshape(-1, P, P, C).permute(0, 3, 1, 2)
|
263 |
+
sinusoid_table = torch.nn.functional.interpolate(
|
264 |
+
sinusoid_table, size=(new_P, new_P), mode='bicubic', align_corners=False)
|
265 |
+
# BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
|
266 |
+
sinusoid_table = sinusoid_table.permute(0, 2, 3, 1).reshape(-1, T, new_P, new_P, C)
|
267 |
+
sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
|
268 |
+
|
269 |
+
if cur_frame != ckpt_num_frame:
|
270 |
+
# print(f'Pretraining uses 4 frames, but current frame is {cur_frame}')
|
271 |
+
# print(f'Interpolate the position embedding')
|
272 |
+
T = ckpt_num_frame # checkpoint frame
|
273 |
+
new_T = cur_frame # testing frame
|
274 |
+
# interpolate
|
275 |
+
P = int((n_position // cur_frame) ** 0.5) # testing size
|
276 |
+
C = d_hid
|
277 |
+
sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
|
278 |
+
sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
|
279 |
+
sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
|
280 |
+
sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
|
281 |
+
sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
|
282 |
+
|
283 |
+
return sinusoid_table
|
284 |
+
|
285 |
+
|
286 |
+
class PretrainVisionTransformerEncoder(nn.Module):
|
287 |
+
""" Vision Transformer with support for patch or hybrid CNN input stage
|
288 |
+
"""
|
289 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12,
|
290 |
+
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
291 |
+
drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, num_frames=8, tubelet_size=1,
|
292 |
+
use_learnable_pos_emb=False,
|
293 |
+
use_checkpoint=False, checkpoint_num=0,
|
294 |
+
ckpt_num_frame=-1, with_ln=True, return_index=-1
|
295 |
+
):
|
296 |
+
super().__init__()
|
297 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
298 |
+
self.patch_embed = PatchEmbed(
|
299 |
+
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
|
300 |
+
num_frames=num_frames, tubelet_size=tubelet_size
|
301 |
+
)
|
302 |
+
num_patches = self.patch_embed.num_patches
|
303 |
+
self.depth = depth + return_index + 1
|
304 |
+
self.use_checkpoint = use_checkpoint
|
305 |
+
self.checkpoint_num = checkpoint_num
|
306 |
+
# print('umt:', f"Use checkpoint: {use_checkpoint}")
|
307 |
+
# print('umt:', f"Checkpoint number: {checkpoint_num}")
|
308 |
+
# print('UMT:', f"Real runing depth: {self.depth}")
|
309 |
+
|
310 |
+
# TODO: Add the cls token
|
311 |
+
if use_learnable_pos_emb:
|
312 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
|
313 |
+
self.img_pos_embed = nn.Parameter(torch.zeros(1, num_patches//(num_frames//tubelet_size) + 1, embed_dim))
|
314 |
+
else:
|
315 |
+
# sine-cosine positional embeddings
|
316 |
+
if img_size != 224:
|
317 |
+
self.pos_embed = get_sinusoid_encoding_table2(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
|
318 |
+
self.img_pos_embed = get_sinusoid_encoding_table2(num_patches//(num_frames//tubelet_size), embed_dim, cur_frame=1, ckpt_num_frame=1, pre_n_position=14*14)
|
319 |
+
else:
|
320 |
+
self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
|
321 |
+
self.img_pos_embed = get_sinusoid_encoding_table(num_patches//(num_frames//tubelet_size), embed_dim)
|
322 |
+
|
323 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
324 |
+
self.blocks = nn.ModuleList([
|
325 |
+
Block(
|
326 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
327 |
+
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
|
328 |
+
init_values=init_values)
|
329 |
+
for i in range(self.depth)])
|
330 |
+
|
331 |
+
if with_ln:
|
332 |
+
self.vision_layernorm = nn.LayerNorm(embed_dim, eps=1e-12)
|
333 |
+
else:
|
334 |
+
self.vision_layernorm = nn.Identity()
|
335 |
+
|
336 |
+
if use_learnable_pos_emb:
|
337 |
+
trunc_normal_(self.pos_embed, std=.02)
|
338 |
+
|
339 |
+
@torch.jit.ignore
|
340 |
+
def no_weight_decay(self):
|
341 |
+
return {'pos_embed', 'cls_token'}
|
342 |
+
|
343 |
+
def forward_features(self, x, use_image=False):
|
344 |
+
x = self.patch_embed(x)
|
345 |
+
|
346 |
+
if use_image:
|
347 |
+
x = x + self.img_pos_embed.type_as(x).to(x.device).clone().detach()
|
348 |
+
else:
|
349 |
+
x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
|
350 |
+
|
351 |
+
B, _, C = x.shape
|
352 |
+
x_vis = x
|
353 |
+
|
354 |
+
for idx, blk in enumerate(self.blocks):
|
355 |
+
if self.use_checkpoint and idx < self.checkpoint_num:
|
356 |
+
x_vis = checkpoint.checkpoint(blk, x_vis)
|
357 |
+
else:
|
358 |
+
x_vis = blk(x_vis)
|
359 |
+
|
360 |
+
# with ln ot not
|
361 |
+
x_vis = self.vision_layernorm(x_vis)
|
362 |
+
return x_vis
|
363 |
+
|
364 |
+
def forward(self, x, use_image=False):
|
365 |
+
x_vis = self.forward_features(x, use_image)
|
366 |
+
return x_vis
|
367 |
+
|
368 |
+
|
369 |
+
class PretrainVisionTransformer(nn.Module):
|
370 |
+
""" Vision Transformer with support for patch or hybrid CNN input stage
|
371 |
+
"""
|
372 |
+
def __init__(self,
|
373 |
+
img_size=224,
|
374 |
+
patch_size=16,
|
375 |
+
encoder_in_chans=3,
|
376 |
+
encoder_embed_dim=768,
|
377 |
+
encoder_depth=12,
|
378 |
+
encoder_num_heads=12,
|
379 |
+
mlp_ratio=4.,
|
380 |
+
qkv_bias=True,
|
381 |
+
qk_scale=None,
|
382 |
+
drop_rate=0.,
|
383 |
+
attn_drop_rate=0.,
|
384 |
+
drop_path_rate=0.,
|
385 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6),
|
386 |
+
init_values=0.,
|
387 |
+
use_learnable_pos_emb=False,
|
388 |
+
num_frames=8,
|
389 |
+
tubelet_size=1,
|
390 |
+
use_checkpoint=False,
|
391 |
+
checkpoint_num=0,
|
392 |
+
ckpt_num_frame=4, # the pretrained model uses 4 frames
|
393 |
+
return_index=-1,
|
394 |
+
with_ln=False
|
395 |
+
):
|
396 |
+
super().__init__()
|
397 |
+
|
398 |
+
self.encoder = PretrainVisionTransformerEncoder(
|
399 |
+
img_size=img_size,
|
400 |
+
patch_size=patch_size,
|
401 |
+
in_chans=encoder_in_chans,
|
402 |
+
embed_dim=encoder_embed_dim,
|
403 |
+
depth=encoder_depth,
|
404 |
+
num_heads=encoder_num_heads,
|
405 |
+
mlp_ratio=mlp_ratio,
|
406 |
+
qkv_bias=qkv_bias,
|
407 |
+
qk_scale=qk_scale,
|
408 |
+
drop_rate=drop_rate,
|
409 |
+
attn_drop_rate=attn_drop_rate,
|
410 |
+
drop_path_rate=drop_path_rate,
|
411 |
+
norm_layer=norm_layer,
|
412 |
+
init_values=init_values,
|
413 |
+
num_frames=num_frames,
|
414 |
+
tubelet_size=tubelet_size,
|
415 |
+
use_learnable_pos_emb=use_learnable_pos_emb,
|
416 |
+
use_checkpoint=use_checkpoint,
|
417 |
+
checkpoint_num=checkpoint_num,
|
418 |
+
ckpt_num_frame=ckpt_num_frame,
|
419 |
+
with_ln=with_ln,
|
420 |
+
return_index=return_index
|
421 |
+
)
|
422 |
+
# print('umt:', f'With LN: {with_ln}')
|
423 |
+
# print('UMT:', f'Total {encoder_depth} layer')
|
424 |
+
# print('UMT:', f'Return {encoder_depth+return_index+1}-th layer')
|
425 |
+
|
426 |
+
self.apply(self._init_weights)
|
427 |
+
|
428 |
+
def _init_weights(self, m):
|
429 |
+
if isinstance(m, nn.Linear):
|
430 |
+
nn.init.xavier_uniform_(m.weight)
|
431 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
432 |
+
nn.init.constant_(m.bias, 0)
|
433 |
+
elif isinstance(m, nn.LayerNorm):
|
434 |
+
nn.init.constant_(m.bias, 0)
|
435 |
+
nn.init.constant_(m.weight, 1.0)
|
436 |
+
|
437 |
+
@torch.jit.ignore
|
438 |
+
def no_weight_decay(self):
|
439 |
+
return {'pos_embed', 'cls_token', 'clip_pos_embed'}
|
440 |
+
|
441 |
+
def forward(self, x, use_image=False):
|
442 |
+
T = x.shape[2]
|
443 |
+
x_vis = self.encoder(x, use_image) # [B, N_vis, C_e]
|
444 |
+
B, TL, C = x_vis.shape
|
445 |
+
x_vis = x_vis.view(B, T, TL // T, C)
|
446 |
+
|
447 |
+
return x_vis
|
448 |
+
|
449 |
+
|
450 |
+
|
451 |
+
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
class UMTImageProcessor:
|
456 |
+
def __init__(self, image_mean=(0.485, 0.456, 0.406), image_std=(0.229, 0.224, 0.225), size=(224, 224), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
|
457 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
458 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
459 |
+
|
460 |
+
self.image_mean = image_mean
|
461 |
+
self.image_std = image_std
|
462 |
+
self.size = size
|
463 |
+
self.resample = resample
|
464 |
+
self.rescale_factor = rescale_factor
|
465 |
+
self.data_format = data_format
|
466 |
+
self.crop_size = crop_size
|
467 |
+
|
468 |
+
def preprocess(self, images, return_tensors, target_size=None):
|
469 |
+
if isinstance(images, Image.Image):
|
470 |
+
images = [images]
|
471 |
+
else:
|
472 |
+
# to adapt video data
|
473 |
+
images = [to_numpy_array(image) for image in images]
|
474 |
+
assert isinstance(images, list)
|
475 |
+
|
476 |
+
if target_size is None:
|
477 |
+
target_size = self.size
|
478 |
+
|
479 |
+
transforms = [
|
480 |
+
convert_to_rgb,
|
481 |
+
to_numpy_array,
|
482 |
+
partial(resize, size=target_size, resample=self.resample, data_format=self.data_format),
|
483 |
+
partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
|
484 |
+
partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
|
485 |
+
partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
|
486 |
+
]
|
487 |
+
|
488 |
+
images = reduce(lambda x, f: [*map(f, x)], transforms, images)
|
489 |
+
data = {"pixel_values": images}
|
490 |
+
|
491 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
492 |
+
|
493 |
+
|
494 |
+
class UMTVisionConfig:
|
495 |
+
model_type = "umt_vision_model"
|
496 |
+
|
497 |
+
def __init__(
|
498 |
+
self,
|
499 |
+
num_frames=4,
|
500 |
+
hidden_size=1024,
|
501 |
+
num_hidden_layers=24,
|
502 |
+
num_attention_heads=16,
|
503 |
+
num_channels=3,
|
504 |
+
image_size=224,
|
505 |
+
patch_size=16,
|
506 |
+
return_idx=-2
|
507 |
+
# **kwargs,
|
508 |
+
):
|
509 |
+
# super().__init__(**kwargs)
|
510 |
+
self.num_frames = num_frames
|
511 |
+
self.hidden_size = hidden_size
|
512 |
+
self.num_hidden_layers = num_hidden_layers
|
513 |
+
self.num_attention_heads = num_attention_heads
|
514 |
+
self.num_channels = num_channels
|
515 |
+
self.patch_size = patch_size
|
516 |
+
self.image_size = image_size
|
517 |
+
self.return_idx = return_idx
|
518 |
+
|
519 |
+
|
520 |
+
def build_vit(config, pt_type='origin'):
|
521 |
+
model = PretrainVisionTransformer(
|
522 |
+
img_size=config.image_size,
|
523 |
+
patch_size=16,
|
524 |
+
encoder_embed_dim=1024,
|
525 |
+
encoder_depth=24,
|
526 |
+
encoder_num_heads=16,
|
527 |
+
drop_path_rate=0.,
|
528 |
+
num_frames=config.num_frames,
|
529 |
+
tubelet_size=1,
|
530 |
+
use_checkpoint=False,
|
531 |
+
checkpoint_num=24,
|
532 |
+
return_index=config.return_idx,
|
533 |
+
with_ln=True, # merge vision_layernorm in it
|
534 |
+
)
|
535 |
+
|
536 |
+
# no need to load pt
|
537 |
+
|
538 |
+
return model
|
539 |
+
|
540 |
+
|
541 |
+
|
542 |
+
class UMTVisionTower(nn.Module):
|
543 |
+
def __init__(self, vision_tower, vision_tower_cfg, delay_load=False, pt_type='origin', image_size=224):
|
544 |
+
super().__init__()
|
545 |
+
|
546 |
+
self.is_loaded = False
|
547 |
+
self.pt_type = pt_type
|
548 |
+
|
549 |
+
self.config = UMTVisionConfig(num_frames=vision_tower_cfg.mm_local_num_frames, return_idx=vision_tower_cfg.mm_vision_select_layer, image_size=image_size)
|
550 |
+
|
551 |
+
self.vision_tower_name = vision_tower
|
552 |
+
|
553 |
+
self.image_processor = UMTImageProcessor(size=(image_size, image_size))
|
554 |
+
|
555 |
+
if not delay_load:
|
556 |
+
print(f"Loading vision tower: {vision_tower}")
|
557 |
+
self.load_model()
|
558 |
+
elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
|
559 |
+
# TODO: better detector is needed.
|
560 |
+
print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
561 |
+
self.load_model()
|
562 |
+
elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
|
563 |
+
print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
564 |
+
self.load_model()
|
565 |
+
else:
|
566 |
+
self.cfg_only = self.config
|
567 |
+
|
568 |
+
def load_model(self, device_map=None):
|
569 |
+
if self.is_loaded:
|
570 |
+
print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
571 |
+
return
|
572 |
+
|
573 |
+
self.vision_tower = build_vit(self.config, pt_type=self.pt_type)
|
574 |
+
self.vision_tower.requires_grad_(False)
|
575 |
+
|
576 |
+
self.is_loaded = True
|
577 |
+
|
578 |
+
def forward(self, images):
|
579 |
+
if type(images) is list:
|
580 |
+
raise NotImplementedError
|
581 |
+
else:
|
582 |
+
# input: B T C H W
|
583 |
+
# output: B T*L C
|
584 |
+
T = images.shape[1]
|
585 |
+
images = images.permute(0, 2, 1, 3, 4)
|
586 |
+
image_embeds = self.vision_tower(images, use_image=(T == 1))
|
587 |
+
B, T, L, C = image_embeds.shape
|
588 |
+
image_embeds = image_embeds.reshape(B, -1, C)
|
589 |
+
|
590 |
+
return image_embeds
|
591 |
+
|
592 |
+
@property
|
593 |
+
def dummy_feature(self):
|
594 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
595 |
+
|
596 |
+
@property
|
597 |
+
def dtype(self):
|
598 |
+
for p in self.vision_tower.parameters():
|
599 |
+
return p.dtype
|
600 |
+
|
601 |
+
@property
|
602 |
+
def device(self):
|
603 |
+
for p in self.vision_tower.parameters():
|
604 |
+
return p.device
|
605 |
+
|
606 |
+
@property
|
607 |
+
def hidden_size(self):
|
608 |
+
return self.config.hidden_size
|
609 |
+
|
610 |
+
@property
|
611 |
+
def num_patches(self):
|
612 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
613 |
+
|
614 |
+
@property
|
615 |
+
def num_patches_per_side(self):
|
616 |
+
return self.config.image_size // self.config.patch_size
|
617 |
+
|
618 |
+
@property
|
619 |
+
def image_size(self):
|
620 |
+
return self.config.image_size
|
621 |
+
|
622 |
+
|
623 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
624 |
+
vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
|
625 |
+
|
626 |
+
|
627 |
+
if "umt-hd" in vision_tower:
|
628 |
+
return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, image_size=448, **kwargs)
|
629 |
+
elif "umt" in vision_tower:
|
630 |
+
return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
|
631 |
+
|
632 |
+
raise ValueError(f"Unknown vision tower: {vision_tower}")
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|