jaronfei commited on
Commit
4d478a8
·
1 Parent(s): 4346e4a

first commit

Browse files
README.md CHANGED
@@ -1,3 +1,34 @@
1
  ---
2
  license: mit
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
  ---
4
+
5
+ ## Model Summary
6
+
7
+ Video-CCAM-14B is a lightweight Video-MLLM built on [Phi-3-medium-4k-instruct](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct) and [SigLIP SO400M](https://huggingface.co/google/siglip-so400m-patch14-384).
8
+
9
+ ## Usage
10
+
11
+ Inference using Huggingface transformers on NVIDIA GPUs. Requirements tested on python 3.10:
12
+ ```
13
+ torch==2.1.0
14
+ torchvision==0.16.0
15
+ transformers==4.40.2
16
+ peft==0.10.0
17
+ ```
18
+
19
+ ## Inference & Evaluation
20
+
21
+ Please refer to [Video-CCAM](https://github.com/QQ-MM/Video-CCAM) on inference and evaluation.
22
+
23
+ ### Video-MME: 53.2/57.4 (96 frames)
24
+
25
+ ### MVBench: 61.43 (16 frames)
26
+
27
+ ## Acknowledgement
28
+
29
+ * [xtuner](https://github.com/InternLM/xtuner): Video-CCAM-14B is trained using the xtuner framework. Thanks for their excellent works!
30
+ * [Phi-3-medium-4k-instruct](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct): Powerful language models developed by Microsoft.
31
+ * [SigLIP SO400M](https://huggingface.co/google/siglip-so400m-patch14-384): Outstanding vision encoder developed by Google.
32
+
33
+ ## License
34
+ The model is licensed under the MIT license.
llm_adapter/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: peft
3
+ ---
4
+ ## Training procedure
5
+
6
+ ### Framework versions
7
+
8
+
9
+ - PEFT 0.5.0
llm_adapter/adapter_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_mapping": null,
3
+ "base_model_name_or_path": "/group/40006/jaronfei/models/Phi-3-medium-4k-instruct",
4
+ "bias": "none",
5
+ "fan_in_fan_out": false,
6
+ "inference_mode": true,
7
+ "init_lora_weights": true,
8
+ "layers_pattern": null,
9
+ "layers_to_transform": null,
10
+ "lora_alpha": 256,
11
+ "lora_dropout": 0.05,
12
+ "modules_to_save": null,
13
+ "peft_type": "LORA",
14
+ "r": 512,
15
+ "revision": null,
16
+ "target_modules": [
17
+ "gate_up_proj",
18
+ "down_proj",
19
+ "o_proj",
20
+ "qkv_proj"
21
+ ],
22
+ "task_type": "CAUSAL_LM"
23
+ }
llm_adapter/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e5a25ac87ffdacee283346ab4fd532515d872b16263538f7e19a5cb8ae33e64
3
+ size 3565202960
projector/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CCAMModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ccam_projector.CCAMConfig",
8
+ "AutoModel": "modeling_ccam_projector.CCAMModel"
9
+ },
10
+ "cross_attention_frequency": 1,
11
+ "encoder_hidden_size": 1152,
12
+ "hidden_act": "gelu",
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 1152,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 4096,
17
+ "layer_norm_eps": 1e-12,
18
+ "max_position_embeddings": 512,
19
+ "model_type": "ccam_projector",
20
+ "num_attention_heads": 18,
21
+ "num_hidden_layers": 1,
22
+ "num_query_tokens": 1024,
23
+ "output_size": 5120,
24
+ "pad_token_id": 0,
25
+ "position_embedding_type": "absolute",
26
+ "query_attn_mask_type": "full",
27
+ "spatial_pos_embed_type": "none",
28
+ "spatial_resolution": [
29
+ 1,
30
+ 1
31
+ ],
32
+ "temporal_pos_embed_type": "none",
33
+ "temporal_resolution": 16,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.41.2",
36
+ "visual_attn_mask_type": "ccam",
37
+ "vocab_size": 30522
38
+ }
projector/configuration_ccam_projector.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ ================================================
5
+ @author: Jaron
6
+ @time: 2024/02/20 16:37:16
7
+ @email: fjjth98@163.com
8
+ @description: different projector in Video-LLM
9
+ ================================================
10
+ """
11
+
12
+ from transformers.models.blip_2.configuration_blip_2 import Blip2QFormerConfig
13
+
14
+
15
+ class CCAMConfig(Blip2QFormerConfig):
16
+ model_type = 'ccam_projector'
17
+ _auto_class = 'AutoConfig'
18
+
19
+ def __init__(
20
+ self,
21
+ spatial_pos_embed_type: str = 'learnable', # ['none', 'learnable', 'cosine']
22
+ spatial_resolution: tuple[int, int] = (1, 1), # (H, W)
23
+ temporal_pos_embed_type: str = 'learnable',
24
+ temporal_resolution: int = 0, # T
25
+ num_query_tokens: int = 512,
26
+ visual_attn_mask_type: str = 'ccam', # ['ccam', 'full']
27
+ query_attn_mask_type: str = 'full', # ['causal', 'full']
28
+ num_hidden_layers=1,
29
+ cross_attention_frequency=1,
30
+ output_size=4096, # llm dimension
31
+ encoder_hidden_size=1024, # visual dimension
32
+ hidden_size=1024,
33
+ vocab_size=30522, num_attention_heads=16, intermediate_size=4096, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=0, position_embedding_type="absolute", **kwargs):
34
+ super().__init__(vocab_size, hidden_size, num_hidden_layers, num_attention_heads, intermediate_size, hidden_act, hidden_dropout_prob, attention_probs_dropout_prob, max_position_embeddings, initializer_range, layer_norm_eps, pad_token_id, position_embedding_type, cross_attention_frequency, encoder_hidden_size, **kwargs)
35
+ self.spatial_pos_embed_type = spatial_pos_embed_type
36
+ self.spatial_resolution = spatial_resolution
37
+ self.temporal_pos_embed_type = temporal_pos_embed_type
38
+ self.temporal_resolution = temporal_resolution
39
+ self.num_query_tokens = num_query_tokens
40
+ self.visual_attn_mask_type = visual_attn_mask_type
41
+ self.query_attn_mask_type = query_attn_mask_type
42
+ self.output_size = output_size
projector/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1c084ea5630b683e021444e0b247fb1ad1554ab1fce974beaabebbd88c9093d
3
+ size 128788400
projector/modeling_ccam_projector.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ ================================================
5
+ @author: Jaron
6
+ @time: 2024/02/20 16:21:56
7
+ @email: fjjth98@163.com
8
+ @description: QFormer projector, convert image and video into fixed-length tokens
9
+ ================================================
10
+ """
11
+
12
+ import math
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.nn.functional import interpolate
16
+ from transformers.models.blip_2.modeling_blip_2 import Blip2QFormerModel, Blip2QFormerEncoder
17
+
18
+ from .configuration_ccam_projector import CCAMConfig
19
+
20
+
21
+ class SimpleQFormerOutput(nn.Module):
22
+ # replace last residual MLP with normal MLP
23
+ def __init__(self, config):
24
+ super().__init__()
25
+ self.dense = nn.Linear(config.intermediate_size, config.output_size)
26
+
27
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor = None) -> torch.Tensor:
28
+ return self.dense(hidden_states)
29
+
30
+
31
+ class SimpleQFormerIdentity(nn.Module):
32
+ # just to replace the first attention module with identity, since it is useless
33
+
34
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
35
+ return hidden_states,
36
+
37
+
38
+ class CCAMModel(Blip2QFormerModel):
39
+ _auto_class = 'AutoModel'
40
+ config_class = CCAMConfig
41
+ base_model_prefix = 'model'
42
+ supports_gradient_checkpointing = True
43
+
44
+ def __init__(self, config: CCAMConfig):
45
+ super(Blip2QFormerModel, self).__init__(config)
46
+ self.gradient_checkpointing = False
47
+ self.config = config
48
+ self.num_query_tokens = config.num_query_tokens
49
+ self.visual_attn_mask_type = config.visual_attn_mask_type
50
+
51
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
52
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
53
+ self.encoder = Blip2QFormerEncoder(config)
54
+ self.encoder.layer[0].attention = SimpleQFormerIdentity() # replace the 1st attention module with identity
55
+ self.encoder.layer[-1].output_query = SimpleQFormerOutput(config)
56
+
57
+ # initialize query tokens
58
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.hidden_size))
59
+
60
+ # initialize pos embed
61
+ self.spatial_pos_embed = self._create_pos_embed(*config.spatial_resolution, type=config.spatial_pos_embed_type) # (H, W, C)
62
+ self.temporal_pos_embed = self._create_pos_embed(config.temporal_resolution, type=config.temporal_pos_embed_type) # (T, C)
63
+
64
+ # initialize query attn mask
65
+ if config.query_attn_mask_type == 'full':
66
+ self.query_attn_mask = None
67
+ elif config.query_attn_mask_type == 'causal':
68
+ query_attn_mask = torch.ones(self.num_query_tokens, self.num_query_tokens)
69
+ q = torch.arange(self.num_query_tokens)
70
+ query_attn_mask.masked_fill_(q > q[:, None], 0)
71
+ self.query_attn_mask = query_attn_mask[None]
72
+ else:
73
+ raise NotImplementedError(f'Do not support {self.query_attn_mask} query_attn_mask')
74
+
75
+ self.post_init()
76
+
77
+ def _create_pos_embed(self, *size: int, type: str = 'none') -> torch.Tensor:
78
+ C = self.config.encoder_hidden_size
79
+ if type == 'none':
80
+ pos_embed = None
81
+ elif type == 'learnable':
82
+ pos_embed = nn.Parameter(.02 * torch.randn(*size, C))
83
+ elif type == 'cosine':
84
+ total_len = 1
85
+ for i in size:
86
+ total_len *= i
87
+ raw = torch.outer(torch.arange(total_len), torch.exp(torch.arange(0, C, 2) * (-math.log(10000.) / C)))
88
+ pos_embed = nn.Parameter(torch.stack((raw.sin(), raw.cos()), dim=-1).view(*size, C), requires_grad=False)
89
+ else:
90
+ raise NotImplementedError(f'Do not support {type} position embeddings')
91
+ return pos_embed
92
+
93
+ def get_attn_mask(self, embeddings: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
94
+ """Get visual_attn_mask and query_attn_mask if needed
95
+ embeddings (torch.Tensor): (B, T, L, C)
96
+ """
97
+ B, T, L, _ = embeddings.size()
98
+ device = embeddings.device
99
+
100
+ # visual attn mask only work for videos
101
+ if T > 1:
102
+ if self.visual_attn_mask_type == 'ccam':
103
+ base_attn_mask = torch.ones(T, T, device=device)
104
+ t = torch.arange(T, device=device)
105
+ base_attn_mask.masked_fill_(t > t[:, None], 0)
106
+ visual_attn_mask = torch.cat((
107
+ torch.kron(
108
+ base_attn_mask,
109
+ torch.ones(self.num_query_tokens // T, L, device=device)
110
+ ),
111
+ torch.ones(self.num_query_tokens % T, T * L, device=device)
112
+ ), dim=0)[None].expand(B, -1, -1)
113
+ elif self.visual_attn_mask_type == 'full':
114
+ visual_attn_mask = None
115
+ else:
116
+ raise NotImplementedError(f'Do not support {self.visual_attn_mask_type} attn_mask')
117
+ else:
118
+ visual_attn_mask = None
119
+
120
+ if self.query_attn_mask is None:
121
+ query_attn_mask = None
122
+ else:
123
+ query_attn_mask = self.query_attn_mask.expand(B, -1, -1)
124
+
125
+ return visual_attn_mask, query_attn_mask
126
+
127
+ def batch_forward_no_spatial(self, visual_embeds: torch.Tensor) -> torch.Tensor:
128
+ """Batch forward without spatial mask position embeddings
129
+
130
+ Args:
131
+ visual_embeds (torch.Tensor): (B, T, L, C)
132
+
133
+ Returns:
134
+ torch.Tensor: (B, Q, C)
135
+ """
136
+ B, T, _, C = visual_embeds.size()
137
+ query_embeds = self.query_tokens.expand(B, -1, -1)
138
+ visual_attn_mask, query_attn_mask = self.get_attn_mask(visual_embeds)
139
+
140
+ # add temporal position embeddings
141
+ if self.temporal_pos_embed is not None:
142
+ if T == self.temporal_pos_embed.size(0):
143
+ pos_embed = self.temporal_pos_embed
144
+ elif T == 1:
145
+ pos_embed = 0. * self.temporal_pos_embed[:1] # for deepspeed
146
+ else:
147
+ pos_embed = interpolate(
148
+ self.temporal_pos_embed.T[None], # (1, C, t)
149
+ size=(T,),
150
+ mode='linear',
151
+ align_corners=False
152
+ )[0].T # (T, C)
153
+ visual_embeds = visual_embeds + pos_embed.view(1, T, 1, C)
154
+ visual_embeds = visual_embeds.flatten(1, 2)
155
+
156
+ return super().forward(
157
+ query_embeds=query_embeds,
158
+ attention_mask=query_attn_mask,
159
+ encoder_hidden_states=visual_embeds,
160
+ encoder_attention_mask=visual_attn_mask
161
+ )[0]
162
+
163
+ def forward(self, visual_embeds: torch.Tensor, split_sizes: list[int], unmasked_ids: torch.LongTensor = None):
164
+ """
165
+ visual_embeds (torch.Tensor): (T, L, C)
166
+ split_sizes (list[int]): [t0, t1, ...] sum_i ti=T
167
+ unmasked_ids (torch.LongTensor): If provided, should be in the shape of (T, L) whose value v 0<=v<=HW-1
168
+ output_attentions (_type_, optional): _description_. Defaults to None.
169
+ output_hidden_states (_type_, optional): _description_. Defaults to None.
170
+ return_dict (_type_, optional): _description_. Defaults to None.
171
+ """
172
+ _, L, C = visual_embeds.size()
173
+
174
+ # add spatial position embeddings
175
+ if self.spatial_pos_embed is not None:
176
+ pos_embed = self.spatial_pos_embed.view(-1, C) # (H*W, C)
177
+ if unmasked_ids is None:
178
+ pos_embed = pos_embed.view(1, L, C) # if not provided, L must equals to H*W
179
+ else:
180
+ pos_embed = pos_embed[unmasked_ids] # (T, L, C)
181
+ visual_embeds = visual_embeds + pos_embed
182
+
183
+ # all inputs in this batch has the same t
184
+ if len(set(split_sizes)) == 1:
185
+ visual_embeds = visual_embeds.view(len(split_sizes), split_sizes[0], L, C)
186
+ output = self.batch_forward_no_spatial(visual_embeds)
187
+ else:
188
+ visual_embeds = visual_embeds.split(split_sizes, dim=0)
189
+ # group visual_embeds accoding to the number of frames
190
+ output, group_visual_embeds = [None] * len(split_sizes), {}
191
+ for idx, (embed, t) in enumerate(zip(visual_embeds, split_sizes)):
192
+ if t in group_visual_embeds:
193
+ group_visual_embeds[t][0].append(idx)
194
+ group_visual_embeds[t][1].append(embed)
195
+ else:
196
+ group_visual_embeds[t] = [[idx], [embed]]
197
+ for idx, embeds in group_visual_embeds.values():
198
+ cur_output = self.batch_forward_no_spatial(torch.stack(embeds, dim=0))
199
+ for i, j in enumerate(idx):
200
+ output[j] = cur_output[i]
201
+ output = torch.stack(output, dim=0)
202
+
203
+ return output
visual_encoder_adapter/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: peft
3
+ ---
4
+ ## Training procedure
5
+
6
+ ### Framework versions
7
+
8
+
9
+ - PEFT 0.5.0
visual_encoder_adapter/adapter_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_mapping": {
3
+ "base_model_class": "SiglipVisionModel",
4
+ "parent_library": "xtuner.model.modules.visual_encoder.factory"
5
+ },
6
+ "base_model_name_or_path": "/group/40006/jaronfei/models/siglip-so400m-patch14-384",
7
+ "bias": "none",
8
+ "fan_in_fan_out": false,
9
+ "inference_mode": true,
10
+ "init_lora_weights": true,
11
+ "layers_pattern": null,
12
+ "layers_to_transform": null,
13
+ "lora_alpha": 16,
14
+ "lora_dropout": 0.05,
15
+ "modules_to_save": null,
16
+ "peft_type": "LORA",
17
+ "r": 64,
18
+ "revision": null,
19
+ "target_modules": [
20
+ "v_proj",
21
+ "k_proj",
22
+ "fc1",
23
+ "out_proj",
24
+ "q_proj",
25
+ "fc2"
26
+ ],
27
+ "task_type": null
28
+ }
visual_encoder_adapter/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9626605daead810d7d4c34215b22119ac009551eb65607ae6448bd48a265ec41
3
+ size 142556624