morpheushoc
commited on
Upload InternVideo2_Classification_test
Browse files- README.md +199 -0
- config.json +53 -0
- model.safetensors +3 -0
- modeling_videochat2_classification.py +420 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"InternVideo2_Classification_test"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoModel": "modeling_videochat2_classification.InternVideo2_Classification_test"
|
7 |
+
},
|
8 |
+
"bridge": {
|
9 |
+
"extra_num_query_token": 64,
|
10 |
+
"name": "qformer",
|
11 |
+
"num_query_token": 32,
|
12 |
+
"qformer_attention_probs_dropout_prob": 0.1,
|
13 |
+
"qformer_drop_path_rate": 0.2,
|
14 |
+
"qformer_hidden_dropout_prob": 0.1
|
15 |
+
},
|
16 |
+
"freeze_bridge": false,
|
17 |
+
"freeze_llm": false,
|
18 |
+
"freeze_vision_encoder": false,
|
19 |
+
"llm": {
|
20 |
+
"lora_alpha": 32,
|
21 |
+
"lora_dropout": 0.1,
|
22 |
+
"lora_r": 16,
|
23 |
+
"name": "mistral_7b",
|
24 |
+
"pretrained_llm_path": "mistralai/Mistral-7B-Instruct-v0.3",
|
25 |
+
"use_lora": true
|
26 |
+
},
|
27 |
+
"loss": {
|
28 |
+
"use_vision_regression_loss": false
|
29 |
+
},
|
30 |
+
"model_config": {},
|
31 |
+
"model_type": "InternVideo2_Classification_test",
|
32 |
+
"pretrained_paths": {},
|
33 |
+
"torch_dtype": "float32",
|
34 |
+
"transformers_version": "4.46.1",
|
35 |
+
"use_flash_attention": true,
|
36 |
+
"vision_encoder": {
|
37 |
+
"checkpoint_num": 48,
|
38 |
+
"d_model": 1408,
|
39 |
+
"encoder_embed_dim": 1408,
|
40 |
+
"img_size": 224,
|
41 |
+
"name": "internvideo2-1B",
|
42 |
+
"num_frames": 8,
|
43 |
+
"origin_num_frames": 4,
|
44 |
+
"patch_size": 14,
|
45 |
+
"pretrained": null,
|
46 |
+
"sep_image_video_pos_embed": true,
|
47 |
+
"tubelet_size": 1,
|
48 |
+
"use_checkpoint": true,
|
49 |
+
"vit_add_ln": true,
|
50 |
+
"x_vis_only": true,
|
51 |
+
"x_vis_return_idx": -2
|
52 |
+
}
|
53 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c2e92eec0623bf8e345a2310b4baff5fd2ecb0897a3b6eb94e5de89951a2de3c
|
3 |
+
size 42488
|
modeling_videochat2_classification.py
ADDED
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import os
|
3 |
+
import torch
|
4 |
+
import torch.utils.checkpoint
|
5 |
+
from torch import nn
|
6 |
+
from torch.cuda.amp import autocast as autocast
|
7 |
+
from typing import Optional
|
8 |
+
from modeling_internvideo2_vit import pretrain_internvideo2_giant_patch14_224_clean
|
9 |
+
from modeling_qformer import build_qformer
|
10 |
+
# from .flash_attention_class import FlashAttention
|
11 |
+
from model_config import VideoChat2Config
|
12 |
+
|
13 |
+
from transformers import AutoTokenizer,AutoModel, AutoConfig, PreTrainedModel, PretrainedConfig
|
14 |
+
import logging
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
token = os.environ['HF_TOKEN']
|
18 |
+
|
19 |
+
IMG_TOKEN = "[<IMG_PLH>]"
|
20 |
+
VID_TOKEN = "[<VID_PLH>]"
|
21 |
+
|
22 |
+
DEFAULT_PAD_TOKEN = "[PAD]"
|
23 |
+
DEFAULT_BOS_TOKEN = '<s>'
|
24 |
+
DEFAULT_EOS_TOKEN = '</s>'
|
25 |
+
DEFAULT_UNK_TOKEN = "<unk>"
|
26 |
+
|
27 |
+
DEFAULT_IMAGE_TOKEN = "[IMAGETOKEN]"
|
28 |
+
DEFAULT_VIDEO_TOKEN = "[VIDEOTOKEN]"
|
29 |
+
|
30 |
+
DEFAULT_IMG_PLACEHOLDER = "[<IMG_PLH>]"
|
31 |
+
DEFAULT_VID_PLACEHOLDER = "[<VID_PLH>]"
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def disabled_train(self, mode=True):
|
36 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
37 |
+
does not change anymore."""
|
38 |
+
return self
|
39 |
+
|
40 |
+
|
41 |
+
def freeze_module(module):
|
42 |
+
for _, param in module.named_parameters():
|
43 |
+
param.requires_grad = False
|
44 |
+
module = module.eval()
|
45 |
+
module.train = disabled_train
|
46 |
+
return module
|
47 |
+
|
48 |
+
|
49 |
+
class InternVideo2_Classification(PreTrainedModel):
|
50 |
+
config_class = VideoChat2Config
|
51 |
+
def __init__(self, config):
|
52 |
+
self.model_config = config.model_config
|
53 |
+
# config.model_config = None
|
54 |
+
super().__init__(config)
|
55 |
+
self.build_vision_encoder()
|
56 |
+
self.build_llm()
|
57 |
+
self.build_bridge()
|
58 |
+
# NOTE place it after freeze llm
|
59 |
+
for n, p in self.named_parameters():
|
60 |
+
if p.requires_grad:
|
61 |
+
logger.info(f'{n} requires_grad')
|
62 |
+
|
63 |
+
|
64 |
+
def forward(
|
65 |
+
self,
|
66 |
+
input_ids: torch.LongTensor = None,
|
67 |
+
attention_mask: Optional[torch.Tensor] = None,
|
68 |
+
labels: Optional[torch.LongTensor] = None,
|
69 |
+
image: Optional[torch.Tensor] = None,
|
70 |
+
video: Optional[torch.Tensor] = None,
|
71 |
+
instruction = None,
|
72 |
+
video_idx = None,
|
73 |
+
image_idx = None,
|
74 |
+
):
|
75 |
+
if self.use_vision_regression_loss:
|
76 |
+
text_embeds, visual, visual_idx = self.pad_text_embeds(input_ids=input_ids, image=image,video=video, return_visual=True, video_idx=video_idx, image_idx=image_idx, instruction = instruction)
|
77 |
+
else:
|
78 |
+
text_embeds = self.pad_text_embeds(input_ids=input_ids, image=image, video=video, return_visual=False, video_idx=video_idx, image_idx=image_idx, instruction = instruction)
|
79 |
+
|
80 |
+
outputs = self.lm(
|
81 |
+
inputs_embeds=text_embeds,
|
82 |
+
attention_mask=attention_mask,
|
83 |
+
labels=labels,
|
84 |
+
output_hidden_states=True,
|
85 |
+
return_dict=True,
|
86 |
+
)
|
87 |
+
|
88 |
+
return outputs
|
89 |
+
|
90 |
+
|
91 |
+
def build_vision_encoder(self):
|
92 |
+
# load pretrained internvideo2-1b here, simplified as it receives no args
|
93 |
+
# note that we haven't load the internvideo pretrained version
|
94 |
+
if 'internvideo2' in self.model_config.vision_encoder.name.lower():
|
95 |
+
encoder_name = self.model_config.vision_encoder.name
|
96 |
+
logger.info(f"Build vision_encoder: {encoder_name}")
|
97 |
+
if encoder_name == 'internvideo2-1B':
|
98 |
+
self.vision_encoder = pretrain_internvideo2_giant_patch14_224_clean(self.model_config)
|
99 |
+
else:
|
100 |
+
raise ValueError(f"Not implemented: {encoder_name}")
|
101 |
+
else:
|
102 |
+
raise NotImplementedError(self.model_config.vision_encoder.name)
|
103 |
+
|
104 |
+
if self.model_config.vision_encoder.vit_add_ln:
|
105 |
+
self.vision_layernorm = nn.LayerNorm(self.model_config.vision_encoder.encoder_embed_dim, eps=1e-12)
|
106 |
+
else:
|
107 |
+
self.vision_layernorm = nn.Identity()
|
108 |
+
|
109 |
+
self.freeze_vision_encoder = self.model_config.get("freeze_vision_encoder", False)
|
110 |
+
|
111 |
+
if self.freeze_vision_encoder:
|
112 |
+
logger.info("freeze vision encoder")
|
113 |
+
freeze_module(self.vision_encoder)
|
114 |
+
freeze_module(self.vision_layernorm)
|
115 |
+
|
116 |
+
|
117 |
+
def build_bridge(self):
|
118 |
+
# ViT to LM: 1792 -> 6656 NOTE 768 is qformer dim
|
119 |
+
self.project_up = nn.Linear(768, self.lm.config.hidden_size) # whether bias is needed?
|
120 |
+
# LM to ViT: 6656 -> 1792
|
121 |
+
self.project_down = nn.Linear(self.lm.config.hidden_size, 768)
|
122 |
+
|
123 |
+
if 'qformer' in self.model_config.bridge.name.lower():
|
124 |
+
from transformers import BertTokenizer
|
125 |
+
self.qformer_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased", truncation_side="left")
|
126 |
+
self.qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"})
|
127 |
+
self.qformer_tokenizer.padding_side = "left"
|
128 |
+
if self.model_config.bridge.name == 'qformer':
|
129 |
+
self.qformer, self.query_tokens = build_qformer(
|
130 |
+
self.model_config.bridge.num_query_token, self.model_config.vision_encoder.encoder_embed_dim,
|
131 |
+
qformer_hidden_dropout_prob=self.model_config.bridge.qformer_hidden_dropout_prob,
|
132 |
+
qformer_attention_probs_dropout_prob=self.model_config.bridge.qformer_attention_probs_dropout_prob,
|
133 |
+
qformer_drop_path_rate=self.model_config.bridge.qformer_drop_path_rate,
|
134 |
+
)
|
135 |
+
self.qformer.resize_token_embeddings(len(self.qformer_tokenizer))
|
136 |
+
self.qformer.cls = None
|
137 |
+
self.extra_num_query_token = self.model_config.bridge.extra_num_query_token
|
138 |
+
if self.model_config.bridge.extra_num_query_token > 0:
|
139 |
+
logger.info(f"Add extra {self.model_config.bridge.extra_num_query_token} tokens in QFormer")
|
140 |
+
self.extra_query_tokens = nn.Parameter(
|
141 |
+
torch.zeros(1, self.model_config.bridge.extra_num_query_token, self.query_tokens.shape[-1])
|
142 |
+
)
|
143 |
+
|
144 |
+
self.freeze_bridge = self.model_config.get("freeze_bridge", False)
|
145 |
+
if self.freeze_bridge:
|
146 |
+
logger.info("freeze bridge")
|
147 |
+
freeze_module(self.qformer)
|
148 |
+
self.query_tokens.requires_grad = False
|
149 |
+
|
150 |
+
|
151 |
+
def build_llm(self):
|
152 |
+
self.lm_name = self.model_config.llm.name
|
153 |
+
if self.model_config.llm.name == 'mistral_7b':
|
154 |
+
from transformers import AutoModelForSequenceClassification
|
155 |
+
config = AutoConfig.from_pretrained(
|
156 |
+
self.model_config.llm.pretrained_llm_path,
|
157 |
+
torch_dtype=torch.bfloat16,
|
158 |
+
token=token,
|
159 |
+
# attn_implementation="flash_attention_2",
|
160 |
+
)
|
161 |
+
self.lm = AutoModelForSequenceClassification.from_config(config)
|
162 |
+
elif self.model_config.llm.name == 'internlm_20b':
|
163 |
+
from transformers import AutoModelForSequenceClassification
|
164 |
+
self.lm = AutoModelForSequenceClassification.from_pretrained(
|
165 |
+
self.model_config.llm.pretrained_llm_path,
|
166 |
+
torch_dtype=torch.bfloat16,
|
167 |
+
trust_remote_code=True,
|
168 |
+
)
|
169 |
+
self.lm.gradient_checkpointing = True
|
170 |
+
self.lm._set_gradient_checkpointing()
|
171 |
+
elif self.model_config.llm.name == 'internlm2_5_7b':
|
172 |
+
from transformers import AutoModelForSequenceClassification
|
173 |
+
self.lm = AutoModelForSequenceClassification.from_pretrained(
|
174 |
+
self.model_config.llm.pretrained_llm_path,
|
175 |
+
torch_dtype=torch.bfloat16,
|
176 |
+
trust_remote_code=True,
|
177 |
+
local_files_only=True,
|
178 |
+
)
|
179 |
+
else:
|
180 |
+
raise NotImplementedError(self.model_config.llm.name)
|
181 |
+
|
182 |
+
self.freeze_llm = self.model_config.get("freeze_llm", True)
|
183 |
+
logger.info(f'freeze_llm: {self.freeze_llm}')
|
184 |
+
if self.freeze_llm:
|
185 |
+
logger.info("freeze llm")
|
186 |
+
freeze_module(self.lm)
|
187 |
+
|
188 |
+
if self.model_config.llm.use_lora:
|
189 |
+
self.use_lora = True
|
190 |
+
from peft import get_peft_model, LoraConfig, TaskType
|
191 |
+
logger.info("Use lora")
|
192 |
+
if self.model_config.llm.name == 'internlm_20b':
|
193 |
+
peft_config = LoraConfig(
|
194 |
+
task_type=TaskType.CAUSAL_LM, inference_mode=False,
|
195 |
+
r=self.model_config.llm.lora_r, lora_alpha=self.model_config.llm.lora_alpha, lora_dropout=self.model_config.llm.lora_dropout,
|
196 |
+
target_modules=['wqkv', 'wo', 'w1', 'w2', 'w3', 'output']
|
197 |
+
)
|
198 |
+
else:
|
199 |
+
peft_config = LoraConfig(
|
200 |
+
task_type=TaskType.CAUSAL_LM, inference_mode=False,
|
201 |
+
r=self.model_config.llm.lora_r, lora_alpha=self.model_config.llm.lora_alpha, lora_dropout=self.model_config.llm.lora_dropout,
|
202 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
|
203 |
+
"gate_proj", "up_proj", "down_proj", "lm_head"]
|
204 |
+
)
|
205 |
+
|
206 |
+
self.lm = get_peft_model(self.lm, peft_config)
|
207 |
+
self.lm.enable_input_require_grads()
|
208 |
+
self.lm.print_trainable_parameters()
|
209 |
+
else:
|
210 |
+
self.use_lora = False
|
211 |
+
|
212 |
+
|
213 |
+
def build_conversation(self,instruction, user_prompt,media_type='video',msg=''):
|
214 |
+
|
215 |
+
conversation = ""
|
216 |
+
if instruction:
|
217 |
+
conversation += instruction
|
218 |
+
conversation += ("[INST]" + " ")
|
219 |
+
|
220 |
+
if media_type == 'image':
|
221 |
+
conversation +=( "<Image>" + IMG_TOKEN + "</Image>")#*ilen
|
222 |
+
else:
|
223 |
+
conversation += ("<Video>" + VID_TOKEN + "</Video>")#*ilen
|
224 |
+
|
225 |
+
conversation += (msg.rstrip() + "[/INST]")
|
226 |
+
conversation += (" [INST] " + user_prompt + " [/INST]")
|
227 |
+
conversation += ("")
|
228 |
+
return conversation
|
229 |
+
|
230 |
+
|
231 |
+
def pad_text_embeds(
|
232 |
+
self,
|
233 |
+
input_ids: torch.LongTensor = None,
|
234 |
+
image: Optional[torch.Tensor] = None,
|
235 |
+
video: Optional[torch.Tensor] = None,
|
236 |
+
image_idx = None,
|
237 |
+
video_idx = None,
|
238 |
+
return_visual: bool = False,
|
239 |
+
instruction = None,
|
240 |
+
):
|
241 |
+
# text_embeds
|
242 |
+
text_embeds = self.lm.get_input_embeddings()(input_ids.long()).detach()
|
243 |
+
|
244 |
+
visual = None
|
245 |
+
visual_idx = None
|
246 |
+
|
247 |
+
if image is not None:
|
248 |
+
B, T, C, H, W = image.shape
|
249 |
+
image = image.permute(0, 2, 1, 3, 4)
|
250 |
+
prompt_image_embeds = self.encode_vision(image, instruction=instruction)
|
251 |
+
visual = prompt_image_embeds
|
252 |
+
prompt_image_embeds = self.project_up(prompt_image_embeds)
|
253 |
+
prompt_image_embeds = prompt_image_embeds.view(-1, prompt_image_embeds.shape[-1])
|
254 |
+
visual_idx = image_idx
|
255 |
+
text_embeds[image_idx == 1] = text_embeds[image_idx == 1] * 0 + prompt_image_embeds.to(text_embeds.device)
|
256 |
+
elif video is not None:
|
257 |
+
if len(video.shape) == 5:
|
258 |
+
B, T, C, H, W = video.shape
|
259 |
+
N = 1
|
260 |
+
else:
|
261 |
+
B, N, T, C, H, W = video.shape
|
262 |
+
video = video.reshape(B*N, T, C, H, W).permute(0, 2, 1, 3, 4)
|
263 |
+
prompt_video_embeds = self.encode_vision(video, instruction=instruction)
|
264 |
+
visual = prompt_video_embeds
|
265 |
+
prompt_video_embeds = self.project_up(prompt_video_embeds)
|
266 |
+
prompt_video_embeds = prompt_video_embeds.view(-1, prompt_video_embeds.shape[-1])
|
267 |
+
visual_idx = video_idx
|
268 |
+
text_embeds[video_idx == 1] = text_embeds[video_idx == 1] * 0 + prompt_video_embeds.to(text_embeds.device).to(text_embeds.dtype)
|
269 |
+
else:
|
270 |
+
logger.warn(f"don't get visual input, input_ids: {input_ids}")
|
271 |
+
|
272 |
+
if return_visual:
|
273 |
+
return text_embeds, visual, visual_idx
|
274 |
+
|
275 |
+
return text_embeds
|
276 |
+
|
277 |
+
|
278 |
+
def encode_vision(
|
279 |
+
self,
|
280 |
+
image,
|
281 |
+
instruction
|
282 |
+
):
|
283 |
+
device = image.device
|
284 |
+
B = image.shape[0]
|
285 |
+
T = image.shape[2]
|
286 |
+
use_image = True if T == 1 else False
|
287 |
+
image_embeds = self.vision_encoder(image, use_image=use_image)
|
288 |
+
C = image_embeds.shape[-1]
|
289 |
+
image_embeds = image_embeds.reshape(B, -1, C)
|
290 |
+
image_embeds = self.vision_layernorm(image_embeds).to(device) # [B, T*L, C]
|
291 |
+
|
292 |
+
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device)
|
293 |
+
if self.extra_num_query_token > 0:
|
294 |
+
query_tokens = torch.cat([self.query_tokens, self.extra_query_tokens], dim=1)
|
295 |
+
query_tokens = query_tokens.expand(image_embeds.shape[0], -1, -1)
|
296 |
+
if instruction is not None:
|
297 |
+
text_Qformer = self.qformer_tokenizer(
|
298 |
+
instruction,
|
299 |
+
padding='longest',
|
300 |
+
truncation=True,
|
301 |
+
max_length=512,
|
302 |
+
return_tensors="pt",
|
303 |
+
).to(image_embeds.device)
|
304 |
+
query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(image_embeds.device)
|
305 |
+
Qformer_atts = torch.cat([query_atts, text_Qformer.attention_mask], dim=1)
|
306 |
+
query_output = self.qformer.bert(
|
307 |
+
text_Qformer.input_ids,
|
308 |
+
attention_mask=Qformer_atts,
|
309 |
+
query_embeds=query_tokens,
|
310 |
+
encoder_hidden_states=image_embeds,
|
311 |
+
encoder_attention_mask=image_atts,
|
312 |
+
return_dict=True,
|
313 |
+
)
|
314 |
+
else:
|
315 |
+
query_output = self.qformer.bert(
|
316 |
+
query_embeds=query_tokens,
|
317 |
+
encoder_hidden_states=image_embeds,
|
318 |
+
encoder_attention_mask=image_atts,
|
319 |
+
return_dict=True,
|
320 |
+
)
|
321 |
+
|
322 |
+
return query_output.last_hidden_state[:, :query_tokens.size(1), :]
|
323 |
+
|
324 |
+
|
325 |
+
def build_input_ids(
|
326 |
+
self,
|
327 |
+
tokenizer,
|
328 |
+
conversation,
|
329 |
+
max_length,
|
330 |
+
add_special_tokens,
|
331 |
+
truncation,
|
332 |
+
image = None,
|
333 |
+
video = None,
|
334 |
+
padding = "longest",
|
335 |
+
return_tensors = "pt",
|
336 |
+
image_placeholder: str = DEFAULT_IMG_PLACEHOLDER,
|
337 |
+
video_placeholder: str = DEFAULT_VID_PLACEHOLDER,
|
338 |
+
):
|
339 |
+
input_ids = []
|
340 |
+
indexs = []
|
341 |
+
attention_mask = []
|
342 |
+
start, total_len = 0, 0
|
343 |
+
while True:
|
344 |
+
index1 = conversation.find(image_placeholder, start)
|
345 |
+
index2 = conversation.find(video_placeholder, start)
|
346 |
+
if index1 == -1 and index2 == -1:
|
347 |
+
index = -1
|
348 |
+
elif index1 == -1:
|
349 |
+
index = index2
|
350 |
+
elif index2 == -1:
|
351 |
+
index = index1
|
352 |
+
else:
|
353 |
+
index = min(index1, index2)
|
354 |
+
assert index != -1
|
355 |
+
if index == -1:
|
356 |
+
inputs = tokenizer(conversation[start:], max_length=max_length-total_len, truncation=truncation, padding=padding, return_tensors=return_tensors)
|
357 |
+
else:
|
358 |
+
inputs = tokenizer(conversation[start:index], max_length=max_length, truncation=truncation, padding='longest', return_tensors=return_tensors)
|
359 |
+
|
360 |
+
input_ids += inputs.input_ids
|
361 |
+
attention_mask += inputs.attention_mask
|
362 |
+
total_len += inputs.input_ids[0].shape[0]
|
363 |
+
indexs += torch.zeros_like(inputs.input_ids)
|
364 |
+
|
365 |
+
if index != -1:
|
366 |
+
input_ids += [torch.zeros(96).long()]
|
367 |
+
attention_mask += [torch.ones(96).long()]
|
368 |
+
indexs += [torch.ones(96)]
|
369 |
+
|
370 |
+
if index == -1:
|
371 |
+
return {
|
372 |
+
'input_ids': torch.cat(input_ids),
|
373 |
+
'attention_mask': torch.cat(attention_mask),
|
374 |
+
'index': torch.cat(indexs).to(torch.bool),
|
375 |
+
}
|
376 |
+
start = index + len(DEFAULT_IMG_PLACEHOLDER)
|
377 |
+
|
378 |
+
|
379 |
+
@property
|
380 |
+
def dtype(self):
|
381 |
+
return self.lm.dtype
|
382 |
+
|
383 |
+
@property
|
384 |
+
def device(self):
|
385 |
+
return self.lm.device
|
386 |
+
|
387 |
+
|
388 |
+
class InternVideo2_Classification_test(PreTrainedModel):
|
389 |
+
config_class = VideoChat2Config
|
390 |
+
def __init__(self, config):
|
391 |
+
super().__init__(config)
|
392 |
+
self.conv1 = nn.Conv2d(1, 20, 5)
|
393 |
+
self.conv2 = nn.Conv2d(20, 20, 5)
|
394 |
+
|
395 |
+
def forward(self, x):
|
396 |
+
x = self.conv1(x)
|
397 |
+
return self.conv2(x)
|
398 |
+
|
399 |
+
def test_lol(self, x):
|
400 |
+
return x
|
401 |
+
|
402 |
+
if __name__ == "__main__":
|
403 |
+
|
404 |
+
tokenizer = AutoTokenizer.from_pretrained('OpenGVLab/InternVideo2-Chat-8B',trust_remote_code=True,use_fast=False)
|
405 |
+
config = AutoConfig.from_pretrained('OpenGVLab/InternVideo2-Chat-8B', torch_dtype=torch.bfloat16,trust_remote_code=True)
|
406 |
+
model = InternVideo2_Classification(config).cuda()
|
407 |
+
|
408 |
+
B, T, C, H, W = 1, 8, 3, 224, 224
|
409 |
+
video_tensor = torch.randn(B,T,C,H,W).cuda()
|
410 |
+
user_prompt = "this is a user prompt"
|
411 |
+
instruction = "this is an instruction"
|
412 |
+
|
413 |
+
conversation = model.build_conversation(instruction=instruction, user_prompt=user_prompt, media_type='video')
|
414 |
+
tokenized = model.build_input_ids(tokenizer,conversation,max_length=248,add_special_tokens=True,truncation=False,padding=False,return_tensors='pt')
|
415 |
+
|
416 |
+
input_ids = tokenized['input_ids'].unsqueeze(0).to(model.device)
|
417 |
+
attn_mask = tokenized['attention_mask'].unsqueeze(0).to(model.device)
|
418 |
+
indexes = tokenized['index'].unsqueeze(0)
|
419 |
+
text_embeds = model.pad_text_embeds(input_ids = input_ids,video = video_tensor,video_idx = indexes)
|
420 |
+
outputs = model.lm(inputs_embeds=text_embeds, attention_mask=attn_mask,output_hidden_states=True,return_dict=True)
|