ynhe commited on
Commit
6cc79fe
β€’
1 Parent(s): c11cba3

[Init] Add app file

Browse files
README.md CHANGED
@@ -1,13 +1,151 @@
1
  ---
2
- title: VideoChatGPT
3
- emoji: ⚑
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 3.29.0
8
  app_file: app.py
9
  pinned: false
10
- license: cc-by-sa-4.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Ask-Anything:ChatGPT with Video Understanding
3
+ emoji: movie_camera
4
+ colorFrom: green
5
+ colorTo: green
6
  sdk: gradio
7
+ python_version: 3.8.16
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
+ # 🦜 VideoChat [[paper](https://arxiv.org/abs/2305.06355)]
14
+
15
+ ![images](assert/framework.png)
16
+ In this study, we initiate an exploration into video understanding by introducing VideoChat, an **end-to-end chat-centric video understanding system**. It integrates video foundation models and large language models via a learnable neural interface, excelling in **spatiotemporal reasoning, event localization, and causal relationship inference**. To instructively tune this system, we propose a **video-centric instruction dataset**, composed of thousands of videos matched with detailed descriptions and conversations. This dataset emphasizes **spatiotemporal reasoning and causal relationships**, providing a valuable asset for training chat-centric video understanding systems. Preliminary qualitative experiments reveal our system’s potential across a broad spectrum of video applications and set the standard for future research.
17
+
18
+
19
+ # :fire: Updates
20
+ - **2023/05/11**: Release the 🦜**VideoChat V1**, which can **handle both image and video understanding!**
21
+ - [Model](https://drive.google.com/file/d/1BqmWHWCZBPkhTNWDAq0IfGpbkKLz9C0V/view?usp=share_link) and [Data](https://github.com/OpenGVLab/InternVideo/blob/main/Data/instruction_data.md).
22
+ - πŸ§‘β€πŸ’» *Online demo is Preparing*.
23
+ - πŸ§‘β€πŸ”§ *Tuning scripts are cleaning*.
24
+
25
+ # :hourglass_flowing_sand: Schedule
26
+
27
+ - [x] Small-scale video instuction data and tuning
28
+ - [x] Instruction tuning on BLIP+UniFormerV2+Vicuna
29
+ - [ ] Large-scale and complex video instuction data
30
+ - [ ] Instruction tuning on strong video foundation model
31
+ - [ ] User-friendly interactions with longer videos
32
+ - [ ] ...
33
+
34
+ # :speech_balloon: Example
35
+
36
+ <div align="center">
37
+ <b>
38
+ <font size="4">Comparison with ChatGPT, MiniGPT-4, LLaVA and mPLUG-Owl. </font>
39
+ <br>
40
+ <font size="4" color="red">Our VideoChat can handle both image and video understanding well!</font>
41
+ </b>
42
+ </div>
43
+ <div align="center">
44
+ <img src="assert/comparison.png" width="90%">
45
+ </div>
46
+
47
+ <div align="center">
48
+ <font size="4">
49
+ <a href="https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/papers/media/jesse_dance.mp4">[Video]</a> <b>Why the video is funny?</b>
50
+ </font>
51
+ </div>
52
+ <div align="center">
53
+ <img src="assert/humor.png" width="50%">
54
+ </div>
55
+
56
+ <div align="center">
57
+ <font size="4">
58
+ <a href="https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/papers/media/jp_dance.mp4">[Video]</a> <b>Spatial perception</b>
59
+ </font>
60
+ </div>
61
+ <div align="center">
62
+ <img src="assert/spatial.png" width="50%">
63
+ </div>
64
+
65
+ <div align="center">
66
+ <font size="4">
67
+ <a href="https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/papers/media/car_accident.mp4">[Video]</a> <b>Temporal perception</b>
68
+ </font>
69
+ </div>
70
+ <div align="center">
71
+ <img src="assert/temporal.png" width="50%">
72
+ </div>
73
+
74
+ <div align="center">
75
+ <font size="4">
76
+ <a href="https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/papers/media/idol_dancing.mp4">[Video]</a> <b>Multi-turn conversation</b>
77
+ </font>
78
+ </div>
79
+ <div align="center">
80
+ <img src="assert/multi_turn.png" width="50%">
81
+ </div>
82
+
83
+ <div align="center">
84
+ <font size="4">
85
+ <b>Image understanding</b>
86
+ </font>
87
+ </div>
88
+ <div align="center">
89
+ <img src="assert/image.png" width="100%">
90
+ </div>
91
+
92
+ # :running: Usage
93
+
94
+ - Prepare the envirment.
95
+ ```shell
96
+ pip install -r requirements.txt
97
+ ```
98
+
99
+ - Download [BLIP2](https://huggingface.co/docs/transformers/main/model_doc/blip-2) model:
100
+ - ViT: `wget https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/eva_vit_g.pth`
101
+ - QFormer: `wget https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth`
102
+ - Change the `vit_model_path` and `q_former_model_path` in [config.json](./configs/config.json).
103
+
104
+ - Download [StabelVicuna](https://huggingface.co/CarperAI/stable-vicuna-13b-delta) model:
105
+ - LLAMA: Download it from the [original repo](https://github.com/facebookresearch/llama) or [hugging face](https://huggingface.co/decapoda-research/llama-13b-hf).
106
+ - If you download LLAMA from the original repo, please process it via the following command:
107
+ ```shell
108
+ # convert_llama_weights_to_hf is copied from transformers
109
+ python src/transformers/models/llama/convert_llama_weights_to_hf.py \
110
+ --input_dir /path/to/downloaded/llama/weights \
111
+ --model_size 7B --output_dir /output/path
112
+ ```
113
+ - Download [StableVicuna-13b-deelta](https://huggingface.co/CarperAI/stable-vicuna-13b-delta) and process it:
114
+ ```shell
115
+ # fastchat v0.1.10
116
+ python3 apply_delta.py \
117
+ --base /path/to/model_weights/llama-13b \
118
+ --target stable-vicuna-13b \
119
+ --delta CarperAI/stable-vicuna-13b-delta
120
+ ```
121
+ - Change the `llama_model_path` in [config.json](./configs/config.json).
122
+
123
+ - Download [VideoChat](https://drive.google.com/file/d/1BqmWHWCZBPkhTNWDAq0IfGpbkKLz9C0V/view?usp=share_link) model:
124
+
125
+ - Change the `videochat_model_path` in [config.json](./configs/config.json).
126
+
127
+ - Running demo with Gradio:
128
+ ```shell
129
+ python demo.py
130
+ ```
131
+
132
+ - Another demo on Jupyter Notebook can found in [demo.ipynb](demo.ipynb)
133
+
134
+
135
+ # :page_facing_up: Citation
136
+
137
+ If you find this project useful in your research, please consider cite:
138
+ ```BibTeX
139
+ @article{2023videochat,
140
+ title={VideoChat: Chat-Centric Video Understanding},
141
+ author={KunChang Li, Yinan He, Yi Wang, Yizhuo Li, Wenhai Wang, Ping Luo, Yali Wang, Limin Wang, and Yu Qiao},
142
+ journal={arXiv preprint arXiv:2305.06355},
143
+ year={2023}
144
+ }
145
+ ```
146
+
147
+ # :thumbsup: Acknowledgement
148
+
149
+ Thanks to the open source of the following projects:
150
+
151
+ [InternVideo](https://github.com/OpenGVLab/InternVideo), [UniFormerV2](https://github.com/OpenGVLab/UniFormerV2), [MiniGPT-4](https://github.com/Vision-CAIR/MiniGPT-4), [LLaVA](https://github.com/haotian-liu/LLaVA), [BLIP2](https://huggingface.co/docs/transformers/main/model_doc/blip-2), [StableLM](https://github.com/Stability-AI/StableLM).
configs/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "vit_model": "eva_clip_g",
4
+ "vit_model_path": "model/eva_vit_g.pth",
5
+ "q_former_model_path": "model/blip2_pretrained_flant5xxl.pth",
6
+ "llama_model_path": "model/stable-vicuna-13b",
7
+ "videochat_model_path": "model/videochat.pth",
8
+ "img_size": 224,
9
+ "num_query_token": 32,
10
+ "drop_path_rate": 0.0,
11
+ "use_grad_checkpoint": false,
12
+ "vit_precision": "fp32",
13
+ "freeze_vit": true,
14
+ "freeze_mhra": false,
15
+ "freeze_qformer": true,
16
+ "low_resource": false,
17
+ "max_txt_len": 320,
18
+ "temporal_downsample": false,
19
+ "no_lmhra": true,
20
+ "double_lmhra": false,
21
+ "lmhra_reduction": 2.0,
22
+ "gmhra_layers": 8,
23
+ "gmhra_drop_path_rate": 0.0,
24
+ "gmhra_dropout": 0.5,
25
+ "extra_num_query_token": 64
26
+ },
27
+ "device": "cuda"
28
+ }
conversation.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+
3
+ import torch
4
+ from transformers import StoppingCriteria, StoppingCriteriaList
5
+
6
+ from enum import auto, Enum
7
+
8
+ import numpy as np
9
+ from decord import VideoReader, cpu
10
+ import torchvision.transforms as T
11
+ from models.video_transformers import (
12
+ GroupNormalize, GroupScale, GroupCenterCrop,
13
+ Stack, ToTorchFormatTensor
14
+ )
15
+ from torchvision.transforms.functional import InterpolationMode
16
+ from transformers import LlamaTokenizer, LlamaConfig
17
+
18
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
19
+
20
+
21
+ class SeparatorStyle(Enum):
22
+ """Different separator style."""
23
+ SINGLE = auto()
24
+ TWO = auto()
25
+
26
+
27
+ def get_prompt(conv):
28
+ ret = conv.system + conv.sep
29
+ for role, message in conv.messages:
30
+ if message:
31
+ ret += role + ": " + message + conv.sep
32
+ else:
33
+ ret += role + ":"
34
+ return ret
35
+
36
+
37
+ class StoppingCriteriaSub(StoppingCriteria):
38
+ def __init__(self, stops=[], encounters=1):
39
+ super().__init__()
40
+ self.stops = stops
41
+
42
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
43
+ for stop in self.stops:
44
+ if torch.all((stop == input_ids[0][-len(stop):])).item():
45
+ return True
46
+ return False
47
+
48
+
49
+ class Chat:
50
+ def __init__(self, model, device='cuda:0'):
51
+ self.device = device
52
+ self.model = model
53
+ stop_words_ids = [torch.tensor([835]).to(self.device),
54
+ torch.tensor([2277, 29937]).to(self.device)] # '###' can be encoded in two different ways.
55
+ self.stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)])
56
+
57
+ def ask(self,text,conv):
58
+ conv.messages.append([conv.roles[0], text + '\n'])
59
+ return conv
60
+
61
+ def answer(self, conv, img_list, max_new_tokens=200, num_beams=1, min_length=1, top_p=0.9,
62
+ repetition_penalty=1.0, length_penalty=1, temperature=1.0):
63
+ conv.messages.append([conv.roles[1], None])
64
+ embs = self.get_context_emb(conv, img_list)
65
+ outputs = self.model.llama_model.generate(
66
+ inputs_embeds=embs,
67
+ max_new_tokens=max_new_tokens,
68
+ stopping_criteria=self.stopping_criteria,
69
+ num_beams=num_beams,
70
+ do_sample=True,
71
+ min_length=min_length,
72
+ top_p=top_p,
73
+ repetition_penalty=repetition_penalty,
74
+ length_penalty=length_penalty,
75
+ temperature=temperature,
76
+ )
77
+ output_token = outputs[0]
78
+ if output_token[0] == 0: # the model might output a unknow token <unk> at the beginning. remove it
79
+ output_token = output_token[1:]
80
+ if output_token[0] == 1: # some users find that there is a start token <s> at the beginning. remove it
81
+ output_token = output_token[1:]
82
+ output_text = self.model.llama_tokenizer.decode(output_token, add_special_tokens=False)
83
+ output_text = output_text.split('###')[0] # remove the stop sign '###'
84
+ output_text = output_text.split('Assistant:')[-1].strip()
85
+ conv.messages[-1][1] = output_text
86
+ return output_text, output_token.cpu().numpy(), conv
87
+
88
+ def get_index(self, num_frames, num_segments):
89
+ seg_size = float(num_frames - 1) / num_segments
90
+ start = int(seg_size / 2)
91
+ offsets = np.array([
92
+ start + int(np.round(seg_size * idx)) for idx in range(num_segments)
93
+ ])
94
+ return offsets
95
+
96
+ def load_video(self, video_path, num_segments=8, return_msg=False):
97
+ vr = VideoReader(video_path, ctx=cpu(0))
98
+ num_frames = len(vr)
99
+ frame_indices = self.get_index(num_frames, num_segments)
100
+
101
+ duration = len(vr) // vr.get_avg_fps()
102
+ index = np.linspace(0, len(vr)-1, num=int(duration))
103
+ buffer = vr.get_batch(index).asnumpy()
104
+ # transform
105
+ input_mean = [0.48145466, 0.4578275, 0.40821073]
106
+ input_std = [0.26862954, 0.26130258, 0.27577711]
107
+
108
+ transform = T.Compose([
109
+ GroupScale(int(224), interpolation=InterpolationMode.BICUBIC),
110
+ GroupCenterCrop(224),
111
+ Stack(),
112
+ ToTorchFormatTensor(),
113
+ GroupNormalize(input_mean, input_std)
114
+ ])
115
+
116
+ images_group = list()
117
+ for frame in buffer:
118
+ img = Image.fromarray(frame)
119
+ images_group.append(img)
120
+ images_group = list()
121
+ for frame_index in frame_indices:
122
+ img = Image.fromarray(vr[frame_index].asnumpy())
123
+ images_group.append(img)
124
+ torch_imgs_224 = transform(images_group)
125
+ if return_msg:
126
+ fps = float(vr.get_avg_fps())
127
+ sec = ", ".join([str(round(f / fps, 1)) for f in frame_indices])
128
+ # " " should be added in the start and end
129
+ msg = f"The video contains {len(frame_indices)} frames sampled at {sec} seconds."
130
+ return torch_imgs_224, msg
131
+ else:
132
+ return torch_imgs_224
133
+
134
+ def upload_video(self, image, conv, img_list, num_segments):
135
+ if isinstance(image, str): # is a image path
136
+ vid_chat, msg = self.load_video(image, num_segments=num_segments, return_msg=True)
137
+ TC, H, W = vid_chat.shape
138
+ image = vid_chat.reshape(1, TC//3, 3, H, W).to(self.device)
139
+
140
+ else:
141
+ raise NotImplementedError
142
+ print("Input video shape:", vid_chat.shape)
143
+ image_emb, _ = self.model.encode_img(image)
144
+ img_list.append(image_emb)
145
+ conv.messages.append([
146
+ conv.roles[0],
147
+ f"<Video><VideoHere></Video> {msg}\n"
148
+ ])
149
+ msg = "Received."
150
+ # self.conv.append_message(self.conv.roles[1], msg)
151
+ return msg, img_list, conv
152
+
153
+ def upload_img(self, image, conv, img_list):
154
+ img = image#Image.open(image)#.convert('RGB')
155
+ transform = T.Compose(
156
+ [
157
+ T.Resize(
158
+ (224, 224), interpolation=InterpolationMode.BICUBIC
159
+ ),
160
+ T.ToTensor(),
161
+ T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
162
+ ]
163
+ )
164
+
165
+ img = transform(img).unsqueeze(0).unsqueeze(0).cuda()
166
+ image_emb, _ = self.model.encode_img(img)
167
+ img_list.append(image_emb)
168
+ conv.messages.append([
169
+ conv.roles[0],
170
+ f"<Image><ImageHere></Image>\n"
171
+ ])
172
+ msg = "Received."
173
+ # self.conv.append_message(self.conv.roles[1], msg)
174
+ return msg,img_list, conv
175
+
176
+ def get_context_emb(self, conv, img_list):
177
+ prompt = get_prompt(conv)
178
+ #print(prompt)
179
+ if '<VideoHere>' in prompt:
180
+ prompt_segs = prompt.split('<VideoHere>')
181
+ else:
182
+ prompt_segs = prompt.split('<ImageHere>')
183
+ assert len(prompt_segs) == len(img_list) + 1, "Unmatched numbers of visual placeholders and videos."
184
+ seg_tokens = [
185
+ self.model.llama_tokenizer(
186
+ seg, return_tensors="pt", add_special_tokens=i == 0).to(self.device).input_ids
187
+ # only add bos to the first seg
188
+ for i, seg in enumerate(prompt_segs)
189
+ ]
190
+ seg_embs = [self.model.llama_model.model.embed_tokens(seg_t) for seg_t in seg_tokens]
191
+ mixed_embs = [emb for pair in zip(seg_embs[:-1], img_list) for emb in pair] + [seg_embs[-1]]
192
+ mixed_embs = torch.cat(mixed_embs, dim=1)
193
+ return mixed_embs
demo.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from gradio.themes.utils import colors, fonts, sizes
4
+
5
+ from conversation import Chat
6
+
7
+ # videochat
8
+ from utils.config import Config
9
+ from utils.easydict import EasyDict
10
+ from models.videochat import VideoChat
11
+
12
+
13
+ # ========================================
14
+ # Model Initialization
15
+ # ========================================
16
+ def init_model():
17
+ print('Initializing VideoChat')
18
+ config_file = "configs/config.json"
19
+ cfg = Config.from_file(config_file)
20
+ model = VideoChat(config=cfg.model)
21
+ model = model.to(torch.device(cfg.device))
22
+ model = model.eval()
23
+ chat = Chat(model)
24
+ print('Initialization Finished')
25
+ return chat
26
+
27
+
28
+ # ========================================
29
+ # Gradio Setting
30
+ # ========================================
31
+ def gradio_reset(chat_state, img_list):
32
+ if chat_state is not None:
33
+ chat_state.messages = []
34
+ if img_list is not None:
35
+ img_list = []
36
+ return None, gr.update(value=None, interactive=True), gr.update(value=None, interactive=True), gr.update(placeholder='Please upload your video first', interactive=False),gr.update(value="Upload & Start Chat", interactive=True), chat_state, img_list
37
+
38
+
39
+ def upload_img(gr_img, gr_video, chat_state, num_segments):
40
+ # print(gr_img, gr_video)
41
+ chat_state = EasyDict({
42
+ "system": "",
43
+ "roles": ("Human", "Assistant"),
44
+ "messages": [],
45
+ "sep": "###"
46
+ })
47
+ img_list = []
48
+ if gr_img is None and gr_video is None:
49
+ return None, None, gr.update(interactive=True), chat_state, None
50
+ if gr_video:
51
+ llm_message, img_list, chat_state = chat.upload_video(gr_video, chat_state, img_list, num_segments)
52
+ return gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True, placeholder='Type and press Enter'), gr.update(value="Start Chatting", interactive=False), chat_state, img_list
53
+ if gr_img:
54
+ llm_message, img_list,chat_state = chat.upload_img(gr_img, chat_state, img_list)
55
+ return gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True, placeholder='Type and press Enter'), gr.update(value="Start Chatting", interactive=False), chat_state, img_list
56
+
57
+
58
+ def gradio_ask(user_message, chatbot, chat_state):
59
+ if len(user_message) == 0:
60
+ return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state
61
+ #print(chat_state)
62
+ chat_state = chat.ask(user_message, chat_state)
63
+ chatbot = chatbot + [[user_message, None]]
64
+ return '', chatbot, chat_state
65
+
66
+
67
+ def gradio_answer(gr_img, gr_video,chatbot, chat_state, img_list, num_beams, temperature):
68
+ llm_message,llm_message_token, chat_state = chat.answer(conv=chat_state, img_list=img_list, max_new_tokens=1000, num_beams=num_beams, temperature=temperature)
69
+ llm_message = llm_message.replace("<s>", "") # handle <s>
70
+ chatbot[-1][1] = llm_message
71
+ print(f"========{gr_img}##<BOS>##{gr_video}========")
72
+ print(chat_state,flush=True)
73
+ print(f"========{gr_img}##<END>##{gr_video}========")
74
+ # print(f"Answer: {llm_message}")
75
+ return chatbot, chat_state, img_list
76
+
77
+
78
+ class OpenGVLab(gr.themes.base.Base):
79
+ def __init__(
80
+ self,
81
+ *,
82
+ primary_hue=colors.blue,
83
+ secondary_hue=colors.sky,
84
+ neutral_hue=colors.gray,
85
+ spacing_size=sizes.spacing_md,
86
+ radius_size=sizes.radius_sm,
87
+ text_size=sizes.text_md,
88
+ font=(
89
+ fonts.GoogleFont("Noto Sans"),
90
+ "ui-sans-serif",
91
+ "sans-serif",
92
+ ),
93
+ font_mono=(
94
+ fonts.GoogleFont("IBM Plex Mono"),
95
+ "ui-monospace",
96
+ "monospace",
97
+ ),
98
+ ):
99
+ super().__init__(
100
+ primary_hue=primary_hue,
101
+ secondary_hue=secondary_hue,
102
+ neutral_hue=neutral_hue,
103
+ spacing_size=spacing_size,
104
+ radius_size=radius_size,
105
+ text_size=text_size,
106
+ font=font,
107
+ font_mono=font_mono,
108
+ )
109
+ super().set(
110
+ body_background_fill="*neutral_50",
111
+ )
112
+
113
+
114
+ gvlabtheme = OpenGVLab(primary_hue=colors.blue,
115
+ secondary_hue=colors.sky,
116
+ neutral_hue=colors.gray,
117
+ spacing_size=sizes.spacing_md,
118
+ radius_size=sizes.radius_sm,
119
+ text_size=sizes.text_md,
120
+ )
121
+
122
+ title = """<h1 align="center"><a href="https://github.com/OpenGVLab/Ask-Anything"><img src="https://i.328888.xyz/2023/05/11/iqrAkZ.md.png" alt="Ask-Anything" border="0" style="margin: 0 auto; height: 100px;" /></a> </h1>"""
123
+ description ="""
124
+ <p> VideoChat, an end-to-end chat-centric video understanding system powered by <a href='https://github.com/OpenGVLab/InternVideo'>InternVideo</a>. It integrates video foundation models and large language models via a learnable neural interface, excelling in spatiotemporal reasoning, event localization, and causal relationship inference.</p>
125
+ <div style='display:flex; gap: 0.25rem; '>
126
+ <a src="https://img.shields.io/badge/Github-Code-blue?logo=github" href="https://github.com/OpenGVLab/Ask-Anything"> <img src="https://img.shields.io/badge/Github-Code-blue?logo=github">
127
+ <a src="https://img.shields.io/badge/cs.CV-2305.06355-b31b1b?logo=arxiv&logoColor=red" href="https://arxiv.org/abs/2305.06355"> <img src="https://img.shields.io/badge/cs.CV-2305.06355-b31b1b?logo=arxiv&logoColor=red">
128
+ <a src="https://img.shields.io/badge/WeChat-Group-green?logo=wechat" href="https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/papers/media/wechat_group.jpg"> <img src="https://img.shields.io/badge/WeChat-Group-green?logo=wechat">
129
+ <a src="https://img.shields.io/discord/1099920215724277770?label=Discord&logo=discord" href="https://discord.gg/A2Ex6Pph6A"> <img src="https://img.shields.io/discord/1099920215724277770?label=Discord&logo=discord"> </div>
130
+ """
131
+
132
+
133
+ with gr.Blocks(title="InternVideo-VideoChat!",theme=gvlabtheme,css="#chatbot {overflow:auto; height:500px;} #InputVideo {overflow:visible; height:320px;} footer {visibility: none}") as demo:
134
+ gr.Markdown(title)
135
+ gr.Markdown(description)
136
+
137
+ with gr.Row():
138
+ with gr.Column(scale=0.5, visible=True) as video_upload:
139
+ with gr.Column(elem_id="image") as img_part:
140
+ with gr.Tab("Video", elem_id='video_tab'):
141
+ up_video = gr.Video(interactive=True, include_audio=True, elem_id="video_upload")#.style(height=320)
142
+ with gr.Tab("Image", elem_id='image_tab'):
143
+ up_image = gr.Image(type="pil", interactive=True, elem_id="image_upload")#.style(height=320)
144
+ upload_button = gr.Button(value="Upload & Start Chat", interactive=True, variant="primary")
145
+
146
+ num_beams = gr.Slider(
147
+ minimum=1,
148
+ maximum=10,
149
+ value=1,
150
+ step=1,
151
+ interactive=True,
152
+ label="beam search numbers",
153
+ )
154
+
155
+ temperature = gr.Slider(
156
+ minimum=0.1,
157
+ maximum=2.0,
158
+ value=1.0,
159
+ step=0.1,
160
+ interactive=True,
161
+ label="Temperature",
162
+ )
163
+
164
+ num_segments = gr.Slider(
165
+ minimum=8,
166
+ maximum=64,
167
+ value=8,
168
+ step=1,
169
+ interactive=True,
170
+ label="Video Segments",
171
+ )
172
+
173
+
174
+ with gr.Column(visible=True) as input_raws:
175
+ chat_state = gr.State(EasyDict({
176
+ "system": "",
177
+ "roles": ("Human", "Assistant"),
178
+ "messages": [],
179
+ "sep": "###"
180
+ }))
181
+ img_list = gr.State()
182
+ chatbot = gr.Chatbot(elem_id="chatbot",label='VideoChat')
183
+ with gr.Row():
184
+ with gr.Column(scale=0.7):
185
+ text_input = gr.Textbox(show_label=False, placeholder='Please upload your video first', interactive=False).style(container=False)
186
+ with gr.Column(scale=0.15, min_width=0):
187
+ run = gr.Button("πŸ’­Send")
188
+ with gr.Column(scale=0.15, min_width=0):
189
+ clear = gr.Button("πŸ”„Clear️")
190
+
191
+ chat = init_model()
192
+ upload_button.click(upload_img, [up_image, up_video, chat_state, num_segments], [up_image, up_video, text_input, upload_button, chat_state, img_list])
193
+
194
+ text_input.submit(gradio_ask, [text_input, chatbot, chat_state], [text_input, chatbot, chat_state]).then(
195
+ gradio_answer, [up_image, up_video, chatbot, chat_state, img_list, num_beams, temperature], [chatbot, chat_state, img_list]
196
+ )
197
+ run.click(gradio_ask, [text_input, chatbot, chat_state], [text_input, chatbot, chat_state]).then(
198
+ gradio_answer, [up_image, up_video,chatbot, chat_state, img_list, num_beams, temperature], [chatbot, chat_state, img_list]
199
+ )
200
+ run.click(lambda: "", None, text_input)
201
+ clear.click(gradio_reset, [chat_state, img_list], [chatbot, up_image, up_video, text_input, upload_button, chat_state, img_list], queue=False)
202
+
203
+ demo.launch(server_name="0.0.0.0", favicon_path='bot_avatar.jpg', enable_queue=True,ssl_keyfile="vchat_cert/privkey1.pem",ssl_certfile="vchat_cert/cert1.pem",ssl_verify=False)
models/Qformer.py ADDED
@@ -0,0 +1,1237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * Copyright (c) 2023, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ """
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple, Dict, Any
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from timm.models.layers import drop_path
25
+ from transformers.activations import ACT2FN
26
+ from transformers.file_utils import (
27
+ ModelOutput,
28
+ )
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import (
41
+ PreTrainedModel,
42
+ apply_chunking_to_forward,
43
+ find_pruneable_heads_and_indices,
44
+ prune_linear_layer,
45
+ )
46
+ from transformers.utils import logging
47
+ from transformers.models.bert.configuration_bert import BertConfig
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ class BertEmbeddings(nn.Module):
53
+ """Construct the embeddings from word and position embeddings."""
54
+
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.word_embeddings = nn.Embedding(
58
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
59
+ )
60
+ self.position_embeddings = nn.Embedding(
61
+ config.max_position_embeddings, config.hidden_size
62
+ )
63
+
64
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
65
+ # any TensorFlow checkpoint file
66
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
67
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
68
+
69
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
70
+ self.register_buffer(
71
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
72
+ )
73
+ self.position_embedding_type = getattr(
74
+ config, "position_embedding_type", "absolute"
75
+ )
76
+
77
+ self.config = config
78
+
79
+ def forward(
80
+ self,
81
+ input_ids=None,
82
+ position_ids=None,
83
+ query_embeds=None,
84
+ past_key_values_length=0,
85
+ ):
86
+ if input_ids is not None:
87
+ seq_length = input_ids.size()[1]
88
+ else:
89
+ seq_length = 0
90
+
91
+ if position_ids is None:
92
+ position_ids = self.position_ids[
93
+ :, past_key_values_length : seq_length + past_key_values_length
94
+ ].clone()
95
+
96
+ if input_ids is not None:
97
+ embeddings = self.word_embeddings(input_ids)
98
+ if self.position_embedding_type == "absolute":
99
+ position_embeddings = self.position_embeddings(position_ids)
100
+ embeddings = embeddings + position_embeddings
101
+
102
+ if query_embeds is not None:
103
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
104
+ else:
105
+ embeddings = query_embeds
106
+
107
+ embeddings = self.LayerNorm(embeddings)
108
+ embeddings = self.dropout(embeddings)
109
+ return embeddings
110
+
111
+
112
+ class BertSelfAttention(nn.Module):
113
+ def __init__(self, config, is_cross_attention):
114
+ super().__init__()
115
+ self.config = config
116
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
117
+ config, "embedding_size"
118
+ ):
119
+ raise ValueError(
120
+ "The hidden size (%d) is not a multiple of the number of attention "
121
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
122
+ )
123
+
124
+ self.num_attention_heads = config.num_attention_heads
125
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
126
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
127
+
128
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
129
+ if is_cross_attention:
130
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
131
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
132
+ else:
133
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
134
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
135
+
136
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
137
+ self.position_embedding_type = getattr(
138
+ config, "position_embedding_type", "absolute"
139
+ )
140
+ if (
141
+ self.position_embedding_type == "relative_key"
142
+ or self.position_embedding_type == "relative_key_query"
143
+ ):
144
+ self.max_position_embeddings = config.max_position_embeddings
145
+ self.distance_embedding = nn.Embedding(
146
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
147
+ )
148
+ self.save_attention = False
149
+
150
+ def save_attn_gradients(self, attn_gradients):
151
+ self.attn_gradients = attn_gradients
152
+
153
+ def get_attn_gradients(self):
154
+ return self.attn_gradients
155
+
156
+ def save_attention_map(self, attention_map):
157
+ self.attention_map = attention_map
158
+
159
+ def get_attention_map(self):
160
+ return self.attention_map
161
+
162
+ def transpose_for_scores(self, x):
163
+ new_x_shape = x.size()[:-1] + (
164
+ self.num_attention_heads,
165
+ self.attention_head_size,
166
+ )
167
+ x = x.view(*new_x_shape)
168
+ return x.permute(0, 2, 1, 3)
169
+
170
+ def forward(
171
+ self,
172
+ hidden_states,
173
+ attention_mask=None,
174
+ head_mask=None,
175
+ encoder_hidden_states=None,
176
+ encoder_attention_mask=None,
177
+ past_key_value=None,
178
+ output_attentions=False,
179
+ ):
180
+
181
+ # If this is instantiated as a cross-attention module, the keys
182
+ # and values come from an encoder; the attention mask needs to be
183
+ # such that the encoder's padding tokens are not attended to.
184
+ is_cross_attention = encoder_hidden_states is not None
185
+
186
+ if is_cross_attention:
187
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
188
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
189
+ attention_mask = encoder_attention_mask
190
+ elif past_key_value is not None:
191
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
192
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
193
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
194
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
195
+ else:
196
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
197
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
198
+
199
+ mixed_query_layer = self.query(hidden_states)
200
+
201
+ query_layer = self.transpose_for_scores(mixed_query_layer)
202
+
203
+ past_key_value = (key_layer, value_layer)
204
+
205
+ # Take the dot product between "query" and "key" to get the raw attention scores.
206
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
207
+
208
+ if (
209
+ self.position_embedding_type == "relative_key"
210
+ or self.position_embedding_type == "relative_key_query"
211
+ ):
212
+ seq_length = hidden_states.size()[1]
213
+ position_ids_l = torch.arange(
214
+ seq_length, dtype=torch.long, device=hidden_states.device
215
+ ).view(-1, 1)
216
+ position_ids_r = torch.arange(
217
+ seq_length, dtype=torch.long, device=hidden_states.device
218
+ ).view(1, -1)
219
+ distance = position_ids_l - position_ids_r
220
+ positional_embedding = self.distance_embedding(
221
+ distance + self.max_position_embeddings - 1
222
+ )
223
+ positional_embedding = positional_embedding.to(
224
+ dtype=query_layer.dtype
225
+ ) # fp16 compatibility
226
+
227
+ if self.position_embedding_type == "relative_key":
228
+ relative_position_scores = torch.einsum(
229
+ "bhld,lrd->bhlr", query_layer, positional_embedding
230
+ )
231
+ attention_scores = attention_scores + relative_position_scores
232
+ elif self.position_embedding_type == "relative_key_query":
233
+ relative_position_scores_query = torch.einsum(
234
+ "bhld,lrd->bhlr", query_layer, positional_embedding
235
+ )
236
+ relative_position_scores_key = torch.einsum(
237
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
238
+ )
239
+ attention_scores = (
240
+ attention_scores
241
+ + relative_position_scores_query
242
+ + relative_position_scores_key
243
+ )
244
+
245
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
246
+ if attention_mask is not None:
247
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
248
+ attention_scores = attention_scores + attention_mask
249
+
250
+ # Normalize the attention scores to probabilities.
251
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
252
+
253
+ if is_cross_attention and self.save_attention:
254
+ self.save_attention_map(attention_probs)
255
+ attention_probs.register_hook(self.save_attn_gradients)
256
+
257
+ # This is actually dropping out entire tokens to attend to, which might
258
+ # seem a bit unusual, but is taken from the original Transformer paper.
259
+ attention_probs_dropped = self.dropout(attention_probs)
260
+
261
+ # Mask heads if we want to
262
+ if head_mask is not None:
263
+ attention_probs_dropped = attention_probs_dropped * head_mask
264
+
265
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
266
+
267
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
268
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
269
+ context_layer = context_layer.view(*new_context_layer_shape)
270
+
271
+ outputs = (
272
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
273
+ )
274
+
275
+ outputs = outputs + (past_key_value,)
276
+ return outputs
277
+
278
+
279
+ class DropPath(nn.Module):
280
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
281
+ """
282
+ def __init__(self, drop_prob=None):
283
+ super(DropPath, self).__init__()
284
+ self.drop_prob = drop_prob
285
+
286
+ def forward(self, x):
287
+ return drop_path(x, self.drop_prob, self.training)
288
+
289
+ def extra_repr(self) -> str:
290
+ return 'p={}'.format(self.drop_prob)
291
+
292
+
293
+ class BertSelfOutput(nn.Module):
294
+ def __init__(self, config, drop_path=0.):
295
+ super().__init__()
296
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
297
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
298
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
299
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
300
+
301
+ def forward(self, hidden_states, input_tensor):
302
+ hidden_states = self.dense(hidden_states)
303
+ hidden_states = self.dropout(hidden_states)
304
+ hidden_states = self.drop_path(hidden_states)
305
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
306
+ return hidden_states
307
+
308
+
309
+ class BertAttention(nn.Module):
310
+ def __init__(self, config, is_cross_attention=False, drop_path=0.,):
311
+ super().__init__()
312
+ self.self = BertSelfAttention(config, is_cross_attention)
313
+ self.output = BertSelfOutput(config, drop_path=drop_path)
314
+ self.pruned_heads = set()
315
+
316
+ def prune_heads(self, heads):
317
+ if len(heads) == 0:
318
+ return
319
+ heads, index = find_pruneable_heads_and_indices(
320
+ heads,
321
+ self.self.num_attention_heads,
322
+ self.self.attention_head_size,
323
+ self.pruned_heads,
324
+ )
325
+
326
+ # Prune linear layers
327
+ self.self.query = prune_linear_layer(self.self.query, index)
328
+ self.self.key = prune_linear_layer(self.self.key, index)
329
+ self.self.value = prune_linear_layer(self.self.value, index)
330
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
331
+
332
+ # Update hyper params and store pruned heads
333
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
334
+ self.self.all_head_size = (
335
+ self.self.attention_head_size * self.self.num_attention_heads
336
+ )
337
+ self.pruned_heads = self.pruned_heads.union(heads)
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states,
342
+ attention_mask=None,
343
+ head_mask=None,
344
+ encoder_hidden_states=None,
345
+ encoder_attention_mask=None,
346
+ past_key_value=None,
347
+ output_attentions=False,
348
+ ):
349
+ self_outputs = self.self(
350
+ hidden_states,
351
+ attention_mask,
352
+ head_mask,
353
+ encoder_hidden_states,
354
+ encoder_attention_mask,
355
+ past_key_value,
356
+ output_attentions,
357
+ )
358
+ attention_output = self.output(self_outputs[0], hidden_states)
359
+
360
+ outputs = (attention_output,) + self_outputs[
361
+ 1:
362
+ ] # add attentions if we output them
363
+ return outputs
364
+
365
+
366
+ class BertIntermediate(nn.Module):
367
+ def __init__(self, config):
368
+ super().__init__()
369
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
370
+ if isinstance(config.hidden_act, str):
371
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
372
+ else:
373
+ self.intermediate_act_fn = config.hidden_act
374
+
375
+ def forward(self, hidden_states):
376
+ hidden_states = self.dense(hidden_states)
377
+ hidden_states = self.intermediate_act_fn(hidden_states)
378
+ return hidden_states
379
+
380
+
381
+ class BertOutput(nn.Module):
382
+ def __init__(self, config, drop_path=0.):
383
+ super().__init__()
384
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
385
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
386
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
387
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
388
+
389
+ def forward(self, hidden_states, input_tensor):
390
+ hidden_states = self.dense(hidden_states)
391
+ hidden_states = self.dropout(hidden_states)
392
+ hidden_states = self.drop_path(hidden_states)
393
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
394
+ return hidden_states
395
+
396
+
397
+ class BertLayer(nn.Module):
398
+ def __init__(self, config, layer_num):
399
+ super().__init__()
400
+ self.config = config
401
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
402
+ self.seq_len_dim = 1
403
+ drop_path = config.drop_path_list[layer_num]
404
+ self.attention = BertAttention(config, drop_path=drop_path)
405
+ self.layer_num = layer_num
406
+ if (
407
+ self.config.add_cross_attention
408
+ and layer_num % self.config.cross_attention_freq == 0
409
+ ):
410
+ self.crossattention = BertAttention(
411
+ config, is_cross_attention=self.config.add_cross_attention,
412
+ drop_path=drop_path
413
+ )
414
+ self.has_cross_attention = True
415
+ else:
416
+ self.has_cross_attention = False
417
+ self.intermediate = BertIntermediate(config)
418
+ self.output = BertOutput(config, drop_path=drop_path)
419
+
420
+ self.intermediate_query = BertIntermediate(config)
421
+ self.output_query = BertOutput(config, drop_path=drop_path)
422
+
423
+ def forward(
424
+ self,
425
+ hidden_states,
426
+ attention_mask=None,
427
+ head_mask=None,
428
+ encoder_hidden_states=None,
429
+ encoder_attention_mask=None,
430
+ past_key_value=None,
431
+ output_attentions=False,
432
+ query_length=0,
433
+ ):
434
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
435
+ self_attn_past_key_value = (
436
+ past_key_value[:2] if past_key_value is not None else None
437
+ )
438
+ self_attention_outputs = self.attention(
439
+ hidden_states,
440
+ attention_mask,
441
+ head_mask,
442
+ output_attentions=output_attentions,
443
+ past_key_value=self_attn_past_key_value,
444
+ )
445
+ attention_output = self_attention_outputs[0]
446
+ outputs = self_attention_outputs[1:-1]
447
+
448
+ present_key_value = self_attention_outputs[-1]
449
+
450
+ if query_length > 0:
451
+ query_attention_output = attention_output[:, :query_length, :]
452
+
453
+ if self.has_cross_attention:
454
+ assert (
455
+ encoder_hidden_states is not None
456
+ ), "encoder_hidden_states must be given for cross-attention layers"
457
+ cross_attention_outputs = self.crossattention(
458
+ query_attention_output,
459
+ attention_mask,
460
+ head_mask,
461
+ encoder_hidden_states,
462
+ encoder_attention_mask,
463
+ output_attentions=output_attentions,
464
+ )
465
+ query_attention_output = cross_attention_outputs[0]
466
+ outputs = (
467
+ outputs + cross_attention_outputs[1:-1]
468
+ ) # add cross attentions if we output attention weights
469
+
470
+ layer_output = apply_chunking_to_forward(
471
+ self.feed_forward_chunk_query,
472
+ self.chunk_size_feed_forward,
473
+ self.seq_len_dim,
474
+ query_attention_output,
475
+ )
476
+ if attention_output.shape[1] > query_length:
477
+ layer_output_text = apply_chunking_to_forward(
478
+ self.feed_forward_chunk,
479
+ self.chunk_size_feed_forward,
480
+ self.seq_len_dim,
481
+ attention_output[:, query_length:, :],
482
+ )
483
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
484
+ else:
485
+ layer_output = apply_chunking_to_forward(
486
+ self.feed_forward_chunk,
487
+ self.chunk_size_feed_forward,
488
+ self.seq_len_dim,
489
+ attention_output,
490
+ )
491
+ outputs = (layer_output,) + outputs
492
+
493
+ outputs = outputs + (present_key_value,)
494
+
495
+ return outputs
496
+
497
+ def feed_forward_chunk(self, attention_output):
498
+ intermediate_output = self.intermediate(attention_output)
499
+ layer_output = self.output(intermediate_output, attention_output)
500
+ return layer_output
501
+
502
+ def feed_forward_chunk_query(self, attention_output):
503
+ intermediate_output = self.intermediate_query(attention_output)
504
+ layer_output = self.output_query(intermediate_output, attention_output)
505
+ return layer_output
506
+
507
+
508
+ class BertEncoder(nn.Module):
509
+ def __init__(self, config):
510
+ super().__init__()
511
+ self.config = config
512
+ self.layer = nn.ModuleList(
513
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
514
+ )
515
+
516
+ def forward(
517
+ self,
518
+ hidden_states,
519
+ attention_mask=None,
520
+ head_mask=None,
521
+ encoder_hidden_states=None,
522
+ encoder_attention_mask=None,
523
+ past_key_values=None,
524
+ use_cache=None,
525
+ output_attentions=False,
526
+ output_hidden_states=False,
527
+ return_dict=True,
528
+ query_length=0,
529
+ ):
530
+ all_hidden_states = () if output_hidden_states else None
531
+ all_self_attentions = () if output_attentions else None
532
+ all_cross_attentions = (
533
+ () if output_attentions and self.config.add_cross_attention else None
534
+ )
535
+
536
+ next_decoder_cache = () if use_cache else None
537
+
538
+ for i in range(self.config.num_hidden_layers):
539
+ layer_module = self.layer[i]
540
+ if output_hidden_states:
541
+ all_hidden_states = all_hidden_states + (hidden_states,)
542
+
543
+ layer_head_mask = head_mask[i] if head_mask is not None else None
544
+ past_key_value = past_key_values[i] if past_key_values is not None else None
545
+
546
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
547
+
548
+ if use_cache:
549
+ logger.warn(
550
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
551
+ )
552
+ use_cache = False
553
+
554
+ def create_custom_forward(module):
555
+ def custom_forward(*inputs):
556
+ return module(
557
+ *inputs, past_key_value, output_attentions, query_length
558
+ )
559
+
560
+ return custom_forward
561
+
562
+ layer_outputs = torch.utils.checkpoint.checkpoint(
563
+ create_custom_forward(layer_module),
564
+ hidden_states,
565
+ attention_mask,
566
+ layer_head_mask,
567
+ encoder_hidden_states,
568
+ encoder_attention_mask,
569
+ )
570
+ else:
571
+ layer_outputs = layer_module(
572
+ hidden_states,
573
+ attention_mask,
574
+ layer_head_mask,
575
+ encoder_hidden_states,
576
+ encoder_attention_mask,
577
+ past_key_value,
578
+ output_attentions,
579
+ query_length,
580
+ )
581
+
582
+ hidden_states = layer_outputs[0]
583
+ if use_cache:
584
+ next_decoder_cache += (layer_outputs[-1],)
585
+ if output_attentions:
586
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
587
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
588
+
589
+ if output_hidden_states:
590
+ all_hidden_states = all_hidden_states + (hidden_states,)
591
+
592
+ if not return_dict:
593
+ return tuple(
594
+ v
595
+ for v in [
596
+ hidden_states,
597
+ next_decoder_cache,
598
+ all_hidden_states,
599
+ all_self_attentions,
600
+ all_cross_attentions,
601
+ ]
602
+ if v is not None
603
+ )
604
+ return BaseModelOutputWithPastAndCrossAttentions(
605
+ last_hidden_state=hidden_states,
606
+ past_key_values=next_decoder_cache,
607
+ hidden_states=all_hidden_states,
608
+ attentions=all_self_attentions,
609
+ cross_attentions=all_cross_attentions,
610
+ )
611
+
612
+
613
+ class BertPooler(nn.Module):
614
+ def __init__(self, config):
615
+ super().__init__()
616
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
617
+ self.activation = nn.Tanh()
618
+
619
+ def forward(self, hidden_states):
620
+ # We "pool" the model by simply taking the hidden state corresponding
621
+ # to the first token.
622
+ first_token_tensor = hidden_states[:, 0]
623
+ pooled_output = self.dense(first_token_tensor)
624
+ pooled_output = self.activation(pooled_output)
625
+ return pooled_output
626
+
627
+
628
+ class BertPredictionHeadTransform(nn.Module):
629
+ def __init__(self, config):
630
+ super().__init__()
631
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
632
+ if isinstance(config.hidden_act, str):
633
+ self.transform_act_fn = ACT2FN[config.hidden_act]
634
+ else:
635
+ self.transform_act_fn = config.hidden_act
636
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
637
+
638
+ def forward(self, hidden_states):
639
+ hidden_states = self.dense(hidden_states)
640
+ hidden_states = self.transform_act_fn(hidden_states)
641
+ hidden_states = self.LayerNorm(hidden_states)
642
+ return hidden_states
643
+
644
+
645
+ class BertLMPredictionHead(nn.Module):
646
+ def __init__(self, config):
647
+ super().__init__()
648
+ self.transform = BertPredictionHeadTransform(config)
649
+
650
+ # The output weights are the same as the input embeddings, but there is
651
+ # an output-only bias for each token.
652
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
653
+
654
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
655
+
656
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
657
+ self.decoder.bias = self.bias
658
+
659
+ def forward(self, hidden_states):
660
+ hidden_states = self.transform(hidden_states)
661
+ hidden_states = self.decoder(hidden_states)
662
+ return hidden_states
663
+
664
+
665
+ class BertOnlyMLMHead(nn.Module):
666
+ def __init__(self, config):
667
+ super().__init__()
668
+ self.predictions = BertLMPredictionHead(config)
669
+
670
+ def forward(self, sequence_output):
671
+ prediction_scores = self.predictions(sequence_output)
672
+ return prediction_scores
673
+
674
+
675
+ class BertPreTrainedModel(PreTrainedModel):
676
+ """
677
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
678
+ models.
679
+ """
680
+
681
+ config_class = BertConfig
682
+ base_model_prefix = "bert"
683
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
684
+
685
+ def _init_weights(self, module):
686
+ """Initialize the weights"""
687
+ if isinstance(module, (nn.Linear, nn.Embedding)):
688
+ # Slightly different from the TF version which uses truncated_normal for initialization
689
+ # cf https://github.com/pytorch/pytorch/pull/5617
690
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
691
+ elif isinstance(module, nn.LayerNorm):
692
+ module.bias.data.zero_()
693
+ module.weight.data.fill_(1.0)
694
+ if isinstance(module, nn.Linear) and module.bias is not None:
695
+ module.bias.data.zero_()
696
+
697
+
698
+ class BertModel(BertPreTrainedModel):
699
+ """
700
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
701
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
702
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
703
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
704
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
705
+ input to the forward pass.
706
+ """
707
+
708
+ def __init__(self, config, add_pooling_layer=False):
709
+ super().__init__(config)
710
+ self.config = config
711
+
712
+ self.embeddings = BertEmbeddings(config)
713
+
714
+ self.encoder = BertEncoder(config)
715
+
716
+ self.pooler = BertPooler(config) if add_pooling_layer else None
717
+
718
+ self.init_weights()
719
+
720
+ def get_input_embeddings(self):
721
+ return self.embeddings.word_embeddings
722
+
723
+ def set_input_embeddings(self, value):
724
+ self.embeddings.word_embeddings = value
725
+
726
+ def _prune_heads(self, heads_to_prune):
727
+ """
728
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
729
+ class PreTrainedModel
730
+ """
731
+ for layer, heads in heads_to_prune.items():
732
+ self.encoder.layer[layer].attention.prune_heads(heads)
733
+
734
+ def get_extended_attention_mask(
735
+ self,
736
+ attention_mask: Tensor,
737
+ input_shape: Tuple[int],
738
+ device: device,
739
+ is_decoder: bool,
740
+ has_query: bool = False,
741
+ ) -> Tensor:
742
+ """
743
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
744
+
745
+ Arguments:
746
+ attention_mask (:obj:`torch.Tensor`):
747
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
748
+ input_shape (:obj:`Tuple[int]`):
749
+ The shape of the input to the model.
750
+ device: (:obj:`torch.device`):
751
+ The device of the input to the model.
752
+
753
+ Returns:
754
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
755
+ """
756
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
757
+ # ourselves in which case we just need to make it broadcastable to all heads.
758
+ if attention_mask.dim() == 3:
759
+ extended_attention_mask = attention_mask[:, None, :, :]
760
+ elif attention_mask.dim() == 2:
761
+ # Provided a padding mask of dimensions [batch_size, seq_length]
762
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
763
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
764
+ if is_decoder:
765
+ batch_size, seq_length = input_shape
766
+
767
+ seq_ids = torch.arange(seq_length, device=device)
768
+ causal_mask = (
769
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
770
+ <= seq_ids[None, :, None]
771
+ )
772
+
773
+ # add a prefix ones mask to the causal mask
774
+ # causal and attention masks must have same type with pytorch version < 1.3
775
+ causal_mask = causal_mask.to(attention_mask.dtype)
776
+
777
+ if causal_mask.shape[1] < attention_mask.shape[1]:
778
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
779
+ if has_query: # UniLM style attention mask
780
+ causal_mask = torch.cat(
781
+ [
782
+ torch.zeros(
783
+ (batch_size, prefix_seq_len, seq_length),
784
+ device=device,
785
+ dtype=causal_mask.dtype,
786
+ ),
787
+ causal_mask,
788
+ ],
789
+ axis=1,
790
+ )
791
+ causal_mask = torch.cat(
792
+ [
793
+ torch.ones(
794
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
795
+ device=device,
796
+ dtype=causal_mask.dtype,
797
+ ),
798
+ causal_mask,
799
+ ],
800
+ axis=-1,
801
+ )
802
+ extended_attention_mask = (
803
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
804
+ )
805
+ else:
806
+ extended_attention_mask = attention_mask[:, None, None, :]
807
+ else:
808
+ raise ValueError(
809
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
810
+ input_shape, attention_mask.shape
811
+ )
812
+ )
813
+
814
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
815
+ # masked positions, this operation will create a tensor which is 0.0 for
816
+ # positions we want to attend and -10000.0 for masked positions.
817
+ # Since we are adding it to the raw scores before the softmax, this is
818
+ # effectively the same as removing these entirely.
819
+ extended_attention_mask = extended_attention_mask.to(
820
+ dtype=self.dtype
821
+ ) # fp16 compatibility
822
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
823
+ return extended_attention_mask
824
+
825
+ def forward(
826
+ self,
827
+ input_ids=None,
828
+ attention_mask=None,
829
+ position_ids=None,
830
+ head_mask=None,
831
+ query_embeds=None,
832
+ encoder_hidden_states=None,
833
+ encoder_attention_mask=None,
834
+ past_key_values=None,
835
+ use_cache=None,
836
+ output_attentions=None,
837
+ output_hidden_states=None,
838
+ return_dict=None,
839
+ is_decoder=False,
840
+ ):
841
+ r"""
842
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
843
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
844
+ the model is configured as a decoder.
845
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
846
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
847
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
848
+ - 1 for tokens that are **not masked**,
849
+ - 0 for tokens that are **masked**.
850
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
851
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
852
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
853
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
854
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
855
+ use_cache (:obj:`bool`, `optional`):
856
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
857
+ decoding (see :obj:`past_key_values`).
858
+ """
859
+ output_attentions = (
860
+ output_attentions
861
+ if output_attentions is not None
862
+ else self.config.output_attentions
863
+ )
864
+ output_hidden_states = (
865
+ output_hidden_states
866
+ if output_hidden_states is not None
867
+ else self.config.output_hidden_states
868
+ )
869
+ return_dict = (
870
+ return_dict if return_dict is not None else self.config.use_return_dict
871
+ )
872
+
873
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
874
+
875
+ if input_ids is None:
876
+ assert (
877
+ query_embeds is not None
878
+ ), "You have to specify query_embeds when input_ids is None"
879
+
880
+ # past_key_values_length
881
+ past_key_values_length = (
882
+ past_key_values[0][0].shape[2] - self.config.query_length
883
+ if past_key_values is not None
884
+ else 0
885
+ )
886
+
887
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
888
+
889
+ embedding_output = self.embeddings(
890
+ input_ids=input_ids,
891
+ position_ids=position_ids,
892
+ query_embeds=query_embeds,
893
+ past_key_values_length=past_key_values_length,
894
+ )
895
+
896
+ input_shape = embedding_output.size()[:-1]
897
+ batch_size, seq_length = input_shape
898
+ device = embedding_output.device
899
+
900
+ if attention_mask is None:
901
+ attention_mask = torch.ones(
902
+ ((batch_size, seq_length + past_key_values_length)), device=device
903
+ )
904
+
905
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
906
+ # ourselves in which case we just need to make it broadcastable to all heads.
907
+ if is_decoder:
908
+ extended_attention_mask = self.get_extended_attention_mask(
909
+ attention_mask,
910
+ input_ids.shape,
911
+ device,
912
+ is_decoder,
913
+ has_query=(query_embeds is not None),
914
+ )
915
+ else:
916
+ extended_attention_mask = self.get_extended_attention_mask(
917
+ attention_mask, input_shape, device, is_decoder
918
+ )
919
+
920
+ # If a 2D or 3D attention mask is provided for the cross-attention
921
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
922
+ if encoder_hidden_states is not None:
923
+ if type(encoder_hidden_states) == list:
924
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
925
+ 0
926
+ ].size()
927
+ else:
928
+ (
929
+ encoder_batch_size,
930
+ encoder_sequence_length,
931
+ _,
932
+ ) = encoder_hidden_states.size()
933
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
934
+
935
+ if type(encoder_attention_mask) == list:
936
+ encoder_extended_attention_mask = [
937
+ self.invert_attention_mask(mask) for mask in encoder_attention_mask
938
+ ]
939
+ elif encoder_attention_mask is None:
940
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
941
+ encoder_extended_attention_mask = self.invert_attention_mask(
942
+ encoder_attention_mask
943
+ )
944
+ else:
945
+ encoder_extended_attention_mask = self.invert_attention_mask(
946
+ encoder_attention_mask
947
+ )
948
+ else:
949
+ encoder_extended_attention_mask = None
950
+
951
+ # Prepare head mask if needed
952
+ # 1.0 in head_mask indicate we keep the head
953
+ # attention_probs has shape bsz x n_heads x N x N
954
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
955
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
956
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
957
+
958
+ encoder_outputs = self.encoder(
959
+ embedding_output,
960
+ attention_mask=extended_attention_mask,
961
+ head_mask=head_mask,
962
+ encoder_hidden_states=encoder_hidden_states,
963
+ encoder_attention_mask=encoder_extended_attention_mask,
964
+ past_key_values=past_key_values,
965
+ use_cache=use_cache,
966
+ output_attentions=output_attentions,
967
+ output_hidden_states=output_hidden_states,
968
+ return_dict=return_dict,
969
+ query_length=query_length,
970
+ )
971
+ sequence_output = encoder_outputs[0]
972
+ pooled_output = (
973
+ self.pooler(sequence_output) if self.pooler is not None else None
974
+ )
975
+
976
+ if not return_dict:
977
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
978
+
979
+ return BaseModelOutputWithPoolingAndCrossAttentions(
980
+ last_hidden_state=sequence_output,
981
+ pooler_output=pooled_output,
982
+ past_key_values=encoder_outputs.past_key_values,
983
+ hidden_states=encoder_outputs.hidden_states,
984
+ attentions=encoder_outputs.attentions,
985
+ cross_attentions=encoder_outputs.cross_attentions,
986
+ )
987
+
988
+
989
+ class BertLMHeadModel(BertPreTrainedModel):
990
+
991
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
992
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
993
+
994
+ def __init__(self, config):
995
+ super().__init__(config)
996
+
997
+ self.bert = BertModel(config, add_pooling_layer=False)
998
+ self.cls = BertOnlyMLMHead(config)
999
+
1000
+ self.init_weights()
1001
+
1002
+ def get_output_embeddings(self):
1003
+ return self.cls.predictions.decoder
1004
+
1005
+ def set_output_embeddings(self, new_embeddings):
1006
+ self.cls.predictions.decoder = new_embeddings
1007
+
1008
+ def forward(
1009
+ self,
1010
+ input_ids=None,
1011
+ attention_mask=None,
1012
+ position_ids=None,
1013
+ head_mask=None,
1014
+ query_embeds=None,
1015
+ encoder_hidden_states=None,
1016
+ encoder_attention_mask=None,
1017
+ labels=None,
1018
+ past_key_values=None,
1019
+ use_cache=True,
1020
+ output_attentions=None,
1021
+ output_hidden_states=None,
1022
+ return_dict=None,
1023
+ return_logits=False,
1024
+ is_decoder=True,
1025
+ reduction="mean",
1026
+ ):
1027
+ r"""
1028
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
1029
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1030
+ the model is configured as a decoder.
1031
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1032
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1033
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
1034
+ - 1 for tokens that are **not masked**,
1035
+ - 0 for tokens that are **masked**.
1036
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1037
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1038
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
1039
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
1040
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1041
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1042
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
1043
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
1044
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
1045
+ use_cache (:obj:`bool`, `optional`):
1046
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
1047
+ decoding (see :obj:`past_key_values`).
1048
+ Returns:
1049
+ Example::
1050
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
1051
+ >>> import torch
1052
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
1053
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
1054
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
1055
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1056
+ >>> outputs = model(**inputs)
1057
+ >>> prediction_logits = outputs.logits
1058
+ """
1059
+ return_dict = (
1060
+ return_dict if return_dict is not None else self.config.use_return_dict
1061
+ )
1062
+ if labels is not None:
1063
+ use_cache = False
1064
+ if past_key_values is not None:
1065
+ query_embeds = None
1066
+
1067
+ outputs = self.bert(
1068
+ input_ids,
1069
+ attention_mask=attention_mask,
1070
+ position_ids=position_ids,
1071
+ head_mask=head_mask,
1072
+ query_embeds=query_embeds,
1073
+ encoder_hidden_states=encoder_hidden_states,
1074
+ encoder_attention_mask=encoder_attention_mask,
1075
+ past_key_values=past_key_values,
1076
+ use_cache=use_cache,
1077
+ output_attentions=output_attentions,
1078
+ output_hidden_states=output_hidden_states,
1079
+ return_dict=return_dict,
1080
+ is_decoder=is_decoder,
1081
+ )
1082
+
1083
+ sequence_output = outputs[0]
1084
+ if query_embeds is not None:
1085
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1086
+
1087
+ prediction_scores = self.cls(sequence_output)
1088
+
1089
+ if return_logits:
1090
+ return prediction_scores[:, :-1, :].contiguous()
1091
+
1092
+ lm_loss = None
1093
+ if labels is not None:
1094
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1095
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1096
+ labels = labels[:, 1:].contiguous()
1097
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
1098
+ lm_loss = loss_fct(
1099
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
1100
+ labels.view(-1),
1101
+ )
1102
+ if reduction == "none":
1103
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
1104
+
1105
+ if not return_dict:
1106
+ output = (prediction_scores,) + outputs[2:]
1107
+ return ((lm_loss,) + output) if lm_loss is not None else output
1108
+
1109
+ return CausalLMOutputWithCrossAttentions(
1110
+ loss=lm_loss,
1111
+ logits=prediction_scores,
1112
+ past_key_values=outputs.past_key_values,
1113
+ hidden_states=outputs.hidden_states,
1114
+ attentions=outputs.attentions,
1115
+ cross_attentions=outputs.cross_attentions,
1116
+ )
1117
+
1118
+ def prepare_inputs_for_generation(
1119
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
1120
+ ):
1121
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1122
+ if attention_mask is None:
1123
+ attention_mask = input_ids.new_ones(input_ids.shape)
1124
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
1125
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
1126
+
1127
+ # cut decoder_input_ids if past is used
1128
+ if past is not None:
1129
+ input_ids = input_ids[:, -1:]
1130
+
1131
+ return {
1132
+ "input_ids": input_ids,
1133
+ "query_embeds": query_embeds,
1134
+ "attention_mask": attention_mask,
1135
+ "past_key_values": past,
1136
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1137
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1138
+ "is_decoder": True,
1139
+ }
1140
+
1141
+ def _reorder_cache(self, past, beam_idx):
1142
+ reordered_past = ()
1143
+ for layer_past in past:
1144
+ reordered_past += (
1145
+ tuple(
1146
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1147
+ ),
1148
+ )
1149
+ return reordered_past
1150
+
1151
+
1152
+ class BertForMaskedLM(BertPreTrainedModel):
1153
+
1154
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1155
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1156
+
1157
+ def __init__(self, config):
1158
+ super().__init__(config)
1159
+
1160
+ self.bert = BertModel(config, add_pooling_layer=False)
1161
+ self.cls = BertOnlyMLMHead(config)
1162
+
1163
+ self.init_weights()
1164
+
1165
+ def get_output_embeddings(self):
1166
+ return self.cls.predictions.decoder
1167
+
1168
+ def set_output_embeddings(self, new_embeddings):
1169
+ self.cls.predictions.decoder = new_embeddings
1170
+
1171
+ def forward(
1172
+ self,
1173
+ input_ids=None,
1174
+ attention_mask=None,
1175
+ position_ids=None,
1176
+ head_mask=None,
1177
+ query_embeds=None,
1178
+ encoder_hidden_states=None,
1179
+ encoder_attention_mask=None,
1180
+ labels=None,
1181
+ output_attentions=None,
1182
+ output_hidden_states=None,
1183
+ return_dict=None,
1184
+ return_logits=False,
1185
+ is_decoder=False,
1186
+ ):
1187
+ r"""
1188
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1189
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1190
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1191
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1192
+ """
1193
+
1194
+ return_dict = (
1195
+ return_dict if return_dict is not None else self.config.use_return_dict
1196
+ )
1197
+
1198
+ outputs = self.bert(
1199
+ input_ids,
1200
+ attention_mask=attention_mask,
1201
+ position_ids=position_ids,
1202
+ head_mask=head_mask,
1203
+ query_embeds=query_embeds,
1204
+ encoder_hidden_states=encoder_hidden_states,
1205
+ encoder_attention_mask=encoder_attention_mask,
1206
+ output_attentions=output_attentions,
1207
+ output_hidden_states=output_hidden_states,
1208
+ return_dict=return_dict,
1209
+ is_decoder=is_decoder,
1210
+ )
1211
+
1212
+ if query_embeds is not None:
1213
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1214
+ prediction_scores = self.cls(sequence_output)
1215
+
1216
+ if return_logits:
1217
+ return prediction_scores
1218
+
1219
+ masked_lm_loss = None
1220
+ if labels is not None:
1221
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1222
+ masked_lm_loss = loss_fct(
1223
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1224
+ )
1225
+
1226
+ if not return_dict:
1227
+ output = (prediction_scores,) + outputs[2:]
1228
+ return (
1229
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1230
+ )
1231
+
1232
+ return MaskedLMOutput(
1233
+ loss=masked_lm_loss,
1234
+ logits=prediction_scores,
1235
+ hidden_states=outputs.hidden_states,
1236
+ attentions=outputs.attentions,
1237
+ )
models/__init__.py ADDED
File without changes
models/__pycache__/Qformer.cpython-38.pyc ADDED
Binary file (32 kB). View file
 
models/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (147 Bytes). View file
 
models/__pycache__/blip2.cpython-38.pyc ADDED
Binary file (4.48 kB). View file
 
models/__pycache__/eva_vit.cpython-38.pyc ADDED
Binary file (19.9 kB). View file
 
models/__pycache__/modeling_llama.cpython-38.pyc ADDED
Binary file (25.1 kB). View file
 
models/__pycache__/video_transformers.cpython-38.pyc ADDED
Binary file (14.4 kB). View file
 
models/__pycache__/videochat.cpython-38.pyc ADDED
Binary file (4.85 kB). View file
 
models/blip2.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (c) 2023, salesforce.com, inc.
3
+ All rights reserved.
4
+ SPDX-License-Identifier: BSD-3-Clause
5
+ For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ """
7
+ import contextlib
8
+ import os
9
+ import logging
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+
14
+ from .Qformer import BertConfig, BertLMHeadModel
15
+ from .eva_vit import create_eva_vit_g
16
+ from transformers import BertTokenizer
17
+
18
+
19
+ class Blip2Base(nn.Module):
20
+ def __init__(self):
21
+ super().__init__()
22
+
23
+ @classmethod
24
+ def init_tokenizer(cls):
25
+ tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
26
+ tokenizer.add_special_tokens({"bos_token": "[DEC]"})
27
+ return tokenizer
28
+
29
+ @property
30
+ def device(self):
31
+ return list(self.parameters())[0].device
32
+
33
+ def maybe_autocast(self, dtype=torch.float16):
34
+ # if on cpu, don't use autocast
35
+ # if on gpu, use autocast with dtype if provided, otherwise use torch.float16
36
+ enable_autocast = self.device != torch.device("cpu")
37
+
38
+ if enable_autocast:
39
+ return torch.cuda.amp.autocast(dtype=dtype)
40
+ else:
41
+ return contextlib.nullcontext()
42
+
43
+ @classmethod
44
+ def init_Qformer(
45
+ cls,
46
+ num_query_token, vision_width,
47
+ qformer_hidden_dropout_prob=0.,
48
+ qformer_attention_probs_dropout_prob=0.,
49
+ qformer_drop_path_rate=0.,
50
+ ):
51
+ encoder_config = BertConfig.from_pretrained("bert-base-uncased")
52
+ encoder_config.encoder_width = vision_width
53
+ # insert cross-attention layer every other block
54
+ encoder_config.add_cross_attention = True
55
+ encoder_config.cross_attention_freq = 2
56
+ encoder_config.query_length = num_query_token
57
+ encoder_config.hidden_dropout_prob = qformer_hidden_dropout_prob
58
+ encoder_config.attention_probs_dropout_prob = qformer_attention_probs_dropout_prob
59
+ encoder_config.drop_path_list = [x.item() for x in torch.linspace(0, qformer_drop_path_rate, encoder_config.num_hidden_layers)]
60
+ print(f"Drop_path:{encoder_config.drop_path_list}")
61
+ print(encoder_config)
62
+ Qformer = BertLMHeadModel(config=encoder_config)
63
+ query_tokens = nn.Parameter(
64
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
65
+ )
66
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
67
+ return Qformer, query_tokens
68
+
69
+ @classmethod
70
+ def init_vision_encoder(
71
+ cls,
72
+ model_name, img_size, drop_path_rate,
73
+ use_grad_checkpoint, precision, vit_model_path,
74
+ temporal_downsample=True,
75
+ no_lmhra=False,
76
+ double_lmhra=False,
77
+ lmhra_reduction=2.0,
78
+ gmhra_layers=8,
79
+ gmhra_drop_path_rate=0.,
80
+ gmhra_dropout=0.5,
81
+ ):
82
+ assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of VideoChat"
83
+ visual_encoder = create_eva_vit_g(
84
+ img_size, drop_path_rate,
85
+ use_grad_checkpoint, precision, vit_model_path,
86
+ temporal_downsample=temporal_downsample,
87
+ no_lmhra=no_lmhra,
88
+ double_lmhra=double_lmhra,
89
+ lmhra_reduction=lmhra_reduction,
90
+ gmhra_layers=gmhra_layers,
91
+ gmhra_drop_path_rate=gmhra_drop_path_rate,
92
+ gmhra_dropout=gmhra_dropout,
93
+ )
94
+
95
+ ln_vision = LayerNorm(visual_encoder.num_features)
96
+ return visual_encoder, ln_vision
97
+
98
+ def load_from_pretrained(self, model_path):
99
+ if model_path is not None and os.path.isfile(model_path):
100
+ checkpoint = torch.load(model_path, map_location="cpu")
101
+ else:
102
+ raise RuntimeError("checkpoint url or path is invalid")
103
+
104
+ state_dict = checkpoint["model"]
105
+
106
+ msg = self.load_state_dict(state_dict, strict=False)
107
+
108
+ print(f"Load QFormer from {model_path}")
109
+ print(msg)
110
+
111
+ return msg
112
+
113
+
114
+ def disabled_train(self, mode=True):
115
+ """Overwrite model.train with this function to make sure train/eval mode
116
+ does not change anymore."""
117
+ return self
118
+
119
+
120
+ class LayerNorm(nn.LayerNorm):
121
+ """Subclass torch's LayerNorm to handle fp16."""
122
+
123
+ def forward(self, x: torch.Tensor):
124
+ orig_type = x.dtype
125
+ ret = super().forward(x.type(torch.float32))
126
+ return ret.type(orig_type)
models/eva_vit.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Based on EVA, BEIT, timm and DeiT code bases
2
+ # https://github.com/baaivision/EVA
3
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm
4
+ # https://github.com/microsoft/unilm/tree/master/beit
5
+ # https://github.com/facebookresearch/deit/
6
+ # https://github.com/facebookresearch/dino
7
+ # --------------------------------------------------------'
8
+ import os
9
+ import math
10
+ import logging
11
+ from functools import partial
12
+ from collections import OrderedDict
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import torch.utils.checkpoint as checkpoint
18
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
19
+
20
+
21
+ def _cfg(url='', **kwargs):
22
+ return {
23
+ 'url': url,
24
+ 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
25
+ 'crop_pct': .9, 'interpolation': 'bicubic',
26
+ 'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5),
27
+ **kwargs
28
+ }
29
+
30
+
31
+ class DropPath(nn.Module):
32
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
33
+ """
34
+ def __init__(self, drop_prob=None):
35
+ super(DropPath, self).__init__()
36
+ self.drop_prob = drop_prob
37
+
38
+ def forward(self, x):
39
+ return drop_path(x, self.drop_prob, self.training)
40
+
41
+ def extra_repr(self):
42
+ return 'p={}'.format(self.drop_prob)
43
+
44
+
45
+ class Mlp(nn.Module):
46
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
47
+ super().__init__()
48
+ out_features = out_features or in_features
49
+ hidden_features = hidden_features or in_features
50
+ self.fc1 = nn.Linear(in_features, hidden_features)
51
+ self.act = act_layer()
52
+ self.fc2 = nn.Linear(hidden_features, out_features)
53
+ self.drop = nn.Dropout(drop)
54
+
55
+ def forward(self, x):
56
+ x = self.fc1(x)
57
+ x = self.act(x)
58
+ # x = self.drop(x)
59
+ # commit this for the orignal BERT implement
60
+ x = self.fc2(x)
61
+ x = self.drop(x)
62
+ return x
63
+
64
+
65
+ class Local_MHRA(nn.Module):
66
+ def __init__(self, d_model, dw_reduction=1.5, pos_kernel_size=3):
67
+ super().__init__()
68
+
69
+ padding = pos_kernel_size // 2
70
+ re_d_model = int(d_model // dw_reduction)
71
+ self.pos_embed = nn.Sequential(
72
+ nn.BatchNorm3d(d_model),
73
+ nn.Conv3d(d_model, re_d_model, kernel_size=1, stride=1, padding=0),
74
+ nn.Conv3d(re_d_model, re_d_model, kernel_size=(pos_kernel_size, 1, 1), stride=(1, 1, 1), padding=(padding, 0, 0), groups=re_d_model),
75
+ nn.Conv3d(re_d_model, d_model, kernel_size=1, stride=1, padding=0),
76
+ )
77
+
78
+ # init zero
79
+ # print('Init zero for Conv in pos_emb')
80
+ nn.init.constant_(self.pos_embed[3].weight, 0)
81
+ nn.init.constant_(self.pos_embed[3].bias, 0)
82
+
83
+ def forward(self, x):
84
+ out = self.pos_embed(x)
85
+ return out
86
+
87
+
88
+ class Attention(nn.Module):
89
+ def __init__(
90
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
91
+ proj_drop=0., window_size=None, attn_head_dim=None):
92
+ super().__init__()
93
+ self.num_heads = num_heads
94
+ head_dim = dim // num_heads
95
+ if attn_head_dim is not None:
96
+ head_dim = attn_head_dim
97
+ all_head_dim = head_dim * self.num_heads
98
+ self.scale = qk_scale or head_dim ** -0.5
99
+
100
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
101
+ if qkv_bias:
102
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
103
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
104
+ else:
105
+ self.q_bias = None
106
+ self.v_bias = None
107
+
108
+ if window_size:
109
+ self.window_size = window_size
110
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
111
+ self.relative_position_bias_table = nn.Parameter(
112
+ torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
113
+ # cls to token & token 2 cls & cls to cls
114
+
115
+ # get pair-wise relative position index for each token inside the window
116
+ coords_h = torch.arange(window_size[0])
117
+ coords_w = torch.arange(window_size[1])
118
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
119
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
120
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
121
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
122
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
123
+ relative_coords[:, :, 1] += window_size[1] - 1
124
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
125
+ relative_position_index = \
126
+ torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype)
127
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
128
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
129
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
130
+ relative_position_index[0, 0] = self.num_relative_distance - 1
131
+
132
+ self.register_buffer("relative_position_index", relative_position_index)
133
+ else:
134
+ self.window_size = None
135
+ self.relative_position_bias_table = None
136
+ self.relative_position_index = None
137
+
138
+ self.attn_drop = nn.Dropout(attn_drop)
139
+ self.proj = nn.Linear(all_head_dim, dim)
140
+ self.proj_drop = nn.Dropout(proj_drop)
141
+
142
+ def forward(self, x, rel_pos_bias=None):
143
+ B, N, C = x.shape
144
+ qkv_bias = None
145
+ if self.q_bias is not None:
146
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
147
+ # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
148
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
149
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
150
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
151
+
152
+ q = q * self.scale
153
+ attn = (q @ k.transpose(-2, -1))
154
+
155
+ if self.relative_position_bias_table is not None:
156
+ relative_position_bias = \
157
+ self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
158
+ self.window_size[0] * self.window_size[1] + 1,
159
+ self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
160
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
161
+ attn = attn + relative_position_bias.unsqueeze(0)
162
+
163
+ if rel_pos_bias is not None:
164
+ attn = attn + rel_pos_bias
165
+
166
+ attn = attn.softmax(dim=-1)
167
+ attn = self.attn_drop(attn)
168
+
169
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
170
+ x = self.proj(x)
171
+ x = self.proj_drop(x)
172
+ return x
173
+
174
+
175
+ class Block(nn.Module):
176
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
177
+ drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
178
+ window_size=None, attn_head_dim=None,
179
+ no_lmhra=False, double_lmhra=True, lmhra_reduction=2.0,
180
+ ):
181
+ super().__init__()
182
+ self.no_lmhra = no_lmhra
183
+ self.double_lmhra = double_lmhra
184
+ if not no_lmhra:
185
+ self.lmhra1 = Local_MHRA(dim, dw_reduction=lmhra_reduction)
186
+ if double_lmhra:
187
+ self.lmhra2 = Local_MHRA(dim, dw_reduction=lmhra_reduction)
188
+
189
+ self.norm1 = norm_layer(dim)
190
+ self.attn = Attention(
191
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
192
+ attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim)
193
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
194
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
195
+ self.norm2 = norm_layer(dim)
196
+ mlp_hidden_dim = int(dim * mlp_ratio)
197
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
198
+
199
+ if init_values is not None and init_values > 0:
200
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
201
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
202
+ else:
203
+ self.gamma_1, self.gamma_2 = None, None
204
+
205
+ def forward(self, x, rel_pos_bias=None, T=8):
206
+ # Local MHRA
207
+ if not self.no_lmhra:
208
+ # x: BT, HW+1, C
209
+ tmp_x = x[:, 1:, :]
210
+ BT, N, C = tmp_x.shape
211
+ B = BT // T
212
+ H = W = int(N ** 0.5)
213
+ tmp_x = tmp_x.view(B, T, H, W, C).permute(0, 4, 1, 2, 3).contiguous()
214
+ tmp_x = tmp_x + self.drop_path(self.lmhra1(tmp_x))
215
+ tmp_x = tmp_x.view(B, C, T, N).permute(0, 2, 3, 1).contiguous().view(BT, N, C)
216
+ x = torch.cat([x[:, :1, :], tmp_x], dim=1)
217
+
218
+ # MHSA
219
+ if self.gamma_1 is None:
220
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias))
221
+ else:
222
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias))
223
+
224
+ # Local MHRA
225
+ if not self.no_lmhra and self.double_lmhra:
226
+ tmp_x = x[:, 1:, :]
227
+ tmp_x = tmp_x.view(B, T, H, W, C).permute(0, 4, 1, 2, 3).contiguous()
228
+ tmp_x = tmp_x + self.drop_path(self.lmhra2(tmp_x))
229
+ tmp_x = tmp_x.view(B, C, T, N).permute(0, 2, 3, 1).contiguous().view(BT, N, C)
230
+ x = torch.cat([x[:, :1, :], tmp_x], dim=1)
231
+
232
+ # MLP
233
+ if self.gamma_1 is None:
234
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
235
+ else:
236
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
237
+
238
+ return x
239
+
240
+
241
+ class PatchEmbed(nn.Module):
242
+ """ Image to Patch Embedding
243
+ """
244
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, temporal_downsample=False):
245
+ super().__init__()
246
+ img_size = to_2tuple(img_size)
247
+ patch_size = to_2tuple(patch_size)
248
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
249
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
250
+ self.img_size = img_size
251
+ self.patch_size = patch_size
252
+ self.num_patches = num_patches
253
+ if temporal_downsample:
254
+ self.proj = nn.Conv3d(
255
+ in_chans, embed_dim, kernel_size=(3, patch_size[0], patch_size[1]),
256
+ stride=(2, patch_size[0], patch_size[1]), padding=(1, 0, 0)
257
+ )
258
+ else:
259
+ self.proj = nn.Conv3d(
260
+ in_chans, embed_dim, kernel_size=(1, patch_size[0], patch_size[1]),
261
+ stride=(1, patch_size[0], patch_size[1]), padding=(0, 0, 0)
262
+ )
263
+
264
+ def forward(self, x, **kwargs):
265
+ B, C, T, H, W = x.shape
266
+ # FIXME look at relaxing size constraints
267
+ assert H == self.img_size[0] and W == self.img_size[1], \
268
+ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
269
+ x = self.proj(x)
270
+ return x
271
+
272
+
273
+ class RelativePositionBias(nn.Module):
274
+ def __init__(self, window_size, num_heads):
275
+ super().__init__()
276
+ self.window_size = window_size
277
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
278
+ self.relative_position_bias_table = nn.Parameter(
279
+ torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
280
+ # cls to token & token 2 cls & cls to cls
281
+
282
+ # get pair-wise relative position index for each token inside the window
283
+ coords_h = torch.arange(window_size[0])
284
+ coords_w = torch.arange(window_size[1])
285
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
286
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
287
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
288
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
289
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
290
+ relative_coords[:, :, 1] += window_size[1] - 1
291
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
292
+ relative_position_index = \
293
+ torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
294
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
295
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
296
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
297
+ relative_position_index[0, 0] = self.num_relative_distance - 1
298
+
299
+ self.register_buffer("relative_position_index", relative_position_index)
300
+
301
+ # trunc_normal_(self.relative_position_bias_table, std=.02)
302
+
303
+ def forward(self):
304
+ relative_position_bias = \
305
+ self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
306
+ self.window_size[0] * self.window_size[1] + 1,
307
+ self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
308
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
309
+
310
+
311
+ class Global_MHRA(nn.Module):
312
+ def __init__(
313
+ self, d_model, n_head, attn_mask=None,
314
+ mlp_factor=4.0, drop_path=0., dropout=0.,
315
+ ):
316
+ super().__init__()
317
+ print(f'Drop path rate: {drop_path}')
318
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
319
+
320
+ self.dpe = nn.Conv3d(d_model, d_model, kernel_size=3, stride=1, padding=1, bias=True, groups=d_model)
321
+ nn.init.constant_(self.dpe.bias, 0.)
322
+
323
+ self.attn = nn.MultiheadAttention(d_model, n_head)
324
+ self.ln_1 = nn.LayerNorm(d_model)
325
+ d_mlp = round(mlp_factor * d_model)
326
+ self.mlp = nn.Sequential(OrderedDict([
327
+ ("c_fc", nn.Linear(d_model, d_mlp)),
328
+ ("gelu", nn.GELU()),
329
+ ("dropout", nn.Dropout(dropout)),
330
+ ("c_proj", nn.Linear(d_mlp, d_model))
331
+ ]))
332
+ self.ln_2 = nn.LayerNorm(d_model)
333
+ self.ln_3 = nn.LayerNorm(d_model)
334
+ self.attn_mask = attn_mask
335
+
336
+ # zero init
337
+ nn.init.xavier_uniform_(self.attn.in_proj_weight)
338
+ nn.init.constant_(self.attn.out_proj.weight, 0.)
339
+ nn.init.constant_(self.attn.out_proj.bias, 0.)
340
+ nn.init.xavier_uniform_(self.mlp[0].weight)
341
+ nn.init.constant_(self.mlp[-1].weight, 0.)
342
+ nn.init.constant_(self.mlp[-1].bias, 0.)
343
+
344
+ def attention(self, x, y, T):
345
+ # x: 1, B, C
346
+ # y: BT, HW+1, C
347
+ BT, N, C = y.shape
348
+ B = BT // T
349
+ H = W = int(N ** 0.5)
350
+ y = y.view(B, T, N, C)
351
+ _, tmp_feats = y[:, :, :1], y[:, :, 1:]
352
+ tmp_feats = tmp_feats.view(B, T, H, W, C).permute(0, 4, 1, 2, 3).contiguous()
353
+ tmp_feats = self.dpe(tmp_feats.clone()).view(B, C, T, N - 1).permute(0, 2, 3, 1).contiguous()
354
+ y[:, :, 1:] = y[:, :, 1:] + tmp_feats
355
+ y = y.permute(1, 2, 0, 3).flatten(0, 1) # T(HW+1), B, C
356
+
357
+ d_model = self.ln_1.weight.size(0)
358
+ q = (x @ self.attn.in_proj_weight[:d_model].T) + self.attn.in_proj_bias[:d_model]
359
+
360
+ k = (y @ self.attn.in_proj_weight[d_model:-d_model].T) + self.attn.in_proj_bias[d_model:-d_model]
361
+ v = (y @ self.attn.in_proj_weight[-d_model:].T) + self.attn.in_proj_bias[-d_model:]
362
+ Tx, Ty, N = q.size(0), k.size(0), q.size(1)
363
+ q = q.view(Tx, N, self.attn.num_heads, self.attn.head_dim).permute(1, 2, 0, 3)
364
+ k = k.view(Ty, N, self.attn.num_heads, self.attn.head_dim).permute(1, 2, 0, 3)
365
+ v = v.view(Ty, N, self.attn.num_heads, self.attn.head_dim).permute(1, 2, 0, 3)
366
+ aff = (q @ k.transpose(-2, -1) / (self.attn.head_dim ** 0.5))
367
+
368
+ aff = aff.softmax(dim=-1)
369
+ out = aff @ v
370
+ out = out.permute(2, 0, 1, 3).flatten(2)
371
+ out = self.attn.out_proj(out)
372
+ return out
373
+
374
+ def forward(self, x, y, T):
375
+ x = x + self.drop_path(self.attention(self.ln_1(x), self.ln_3(y), T=T))
376
+ x = x + self.drop_path(self.mlp(self.ln_2(x)))
377
+ return x
378
+
379
+
380
+ class VisionTransformer(nn.Module):
381
+ """ Vision Transformer with support for patch or hybrid CNN input stage
382
+ """
383
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
384
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
385
+ drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None,
386
+ use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False,
387
+ use_mean_pooling=True, init_scale=0.001, use_checkpoint=False,
388
+ temporal_downsample=True,
389
+ no_lmhra=False, double_lmhra=True, lmhra_reduction=1.5,
390
+ gmhra_layers=4, gmhra_drop_path_rate=0., gmhra_dropout=0.5,
391
+ ):
392
+ super().__init__()
393
+ self.image_size = img_size
394
+ self.num_classes = num_classes
395
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
396
+
397
+ print(f"Temporal downsample: {temporal_downsample}")
398
+ self.patch_embed = PatchEmbed(
399
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
400
+ temporal_downsample=temporal_downsample,
401
+ )
402
+ num_patches = self.patch_embed.num_patches
403
+
404
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
405
+ if use_abs_pos_emb:
406
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
407
+ else:
408
+ self.pos_embed = None
409
+ self.pos_drop = nn.Dropout(p=drop_rate)
410
+
411
+ if use_shared_rel_pos_bias:
412
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
413
+ else:
414
+ self.rel_pos_bias = None
415
+ self.use_checkpoint = use_checkpoint
416
+
417
+ print(f'No L_MHRA: {no_lmhra}')
418
+ print(f'Double L_MHRA: {double_lmhra}')
419
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
420
+ self.use_rel_pos_bias = use_rel_pos_bias
421
+ self.blocks = nn.ModuleList([
422
+ Block(
423
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
424
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
425
+ init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
426
+ no_lmhra=no_lmhra, double_lmhra=double_lmhra, lmhra_reduction=lmhra_reduction,
427
+ )
428
+ for i in range(depth)])
429
+
430
+ # global MHRA
431
+ self.gmhra_layers = gmhra_layers
432
+ self.gmhra_layer_idx = [(depth - 1 - idx) for idx in range(gmhra_layers)]
433
+ print(f"GMHRA index: {self.gmhra_layer_idx}")
434
+ print(f"GMHRA dropout: {gmhra_dropout}")
435
+ if gmhra_layers > 0:
436
+ self.gmhra_cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
437
+ gmhra_dpr = [x.item() for x in torch.linspace(0, gmhra_drop_path_rate, gmhra_layers)]
438
+ self.gmhra = nn.ModuleList([
439
+ Global_MHRA(
440
+ embed_dim, num_heads, mlp_factor=mlp_ratio,
441
+ drop_path=gmhra_dpr[i], dropout=gmhra_dropout,
442
+ ) for i in range(gmhra_layers)
443
+ ])
444
+
445
+ if self.pos_embed is not None:
446
+ trunc_normal_(self.pos_embed, std=.02)
447
+ trunc_normal_(self.cls_token, std=.02)
448
+ self.fix_init_weight()
449
+
450
+ def fix_init_weight(self):
451
+ def rescale(param, layer_id):
452
+ param.div_(math.sqrt(2.0 * layer_id))
453
+
454
+ for layer_id, layer in enumerate(self.blocks):
455
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
456
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
457
+
458
+ def forward_features(self, x):
459
+ x = self.patch_embed(x)
460
+ B, C, T, H, W = x.shape
461
+ x = x.permute(0, 2, 3, 4, 1).reshape(B * T, H * W, C)
462
+
463
+ cls_tokens = self.cls_token.expand(B * T, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
464
+ x = torch.cat((cls_tokens, x), dim=1)
465
+ if self.pos_embed is not None:
466
+ x = x + self.pos_embed
467
+ x = self.pos_drop(x)
468
+
469
+ # the input of global MHRA should be (THW+1)xBx1
470
+ if self.gmhra_layers > 0:
471
+ gmhra_cls_token = self.gmhra_cls_token.repeat(1, B, 1)
472
+
473
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
474
+ j = -1
475
+ for idx, blk in enumerate(self.blocks):
476
+ if self.use_checkpoint:
477
+ x = checkpoint.checkpoint(blk, x, rel_pos_bias, T=T)
478
+ else:
479
+ x = blk(x, rel_pos_bias, T=T)
480
+ if idx in self.gmhra_layer_idx:
481
+ j += 1
482
+ tmp_x = x.clone()
483
+ gmhra_cls_token = self.gmhra[j](gmhra_cls_token, tmp_x, T=T)
484
+ z = torch.cat([x.view(B, -1, C), gmhra_cls_token.permute(1, 0, 2)], dim=1)
485
+ return z
486
+
487
+ def forward(self, x):
488
+ x = self.forward_features(x)
489
+ return x
490
+
491
+
492
+ def interpolate_pos_embed(model, checkpoint_model):
493
+ if 'pos_embed' in checkpoint_model:
494
+ pos_embed_checkpoint = checkpoint_model['pos_embed'].float()
495
+ embedding_size = pos_embed_checkpoint.shape[-1]
496
+ num_patches = model.patch_embed.num_patches
497
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches
498
+ # height (== width) for the checkpoint position embedding
499
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
500
+ # height (== width) for the new position embedding
501
+ new_size = int(num_patches ** 0.5)
502
+ # class_token and dist_token are kept unchanged
503
+ if orig_size != new_size:
504
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
505
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
506
+ # only the position tokens are interpolated
507
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
508
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
509
+ pos_tokens = torch.nn.functional.interpolate(
510
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
511
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
512
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
513
+ checkpoint_model['pos_embed'] = new_pos_embed
514
+
515
+
516
+ def convert_weights_to_fp16(model: nn.Module):
517
+ """Convert applicable model parameters to fp16"""
518
+ def _convert_weights_to_fp16(l):
519
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
520
+ l.weight.data = l.weight.data.half()
521
+ if l.bias is not None:
522
+ l.bias.data = l.bias.data.half()
523
+ if isinstance(l, (nn.MultiheadAttention, Attention)):
524
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
525
+ tensor = getattr(l, attr)
526
+ if tensor is not None:
527
+ tensor.data = tensor.data.half()
528
+ model.apply(_convert_weights_to_fp16)
529
+
530
+
531
+ def inflate_weight(weight_2d, time_dim, center=True):
532
+ print(f'Init center: {center}')
533
+ if center:
534
+ weight_3d = torch.zeros(*weight_2d.shape)
535
+ weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
536
+ middle_idx = time_dim // 2
537
+ weight_3d[:, :, middle_idx, :, :] = weight_2d
538
+ else:
539
+ weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
540
+ weight_3d = weight_3d / time_dim
541
+ return weight_3d
542
+
543
+
544
+ def load_state_dict(model, state_dict, strict=True):
545
+ state_dict_3d = model.state_dict()
546
+ for k in state_dict.keys():
547
+ if k in state_dict_3d.keys() and state_dict[k].shape != state_dict_3d[k].shape:
548
+ if len(state_dict_3d[k].shape) <= 2:
549
+ print(f'Ignore: {k}')
550
+ continue
551
+ print(f'Inflate: {k}, {state_dict[k].shape} => {state_dict_3d[k].shape}')
552
+ time_dim = state_dict_3d[k].shape[2]
553
+ state_dict[k] = inflate_weight(state_dict[k], time_dim)
554
+ msg = model.load_state_dict(state_dict, strict=strict)
555
+ return msg
556
+
557
+
558
+ def create_eva_vit_g(
559
+ img_size=224, drop_path_rate=0.4, use_checkpoint=False,
560
+ precision="fp16", vit_model_path=None,
561
+ # UniFormerV2
562
+ temporal_downsample=True,
563
+ no_lmhra=False,
564
+ double_lmhra=False,
565
+ lmhra_reduction=2.0,
566
+ gmhra_layers=8,
567
+ gmhra_drop_path_rate=0.,
568
+ gmhra_dropout=0.5,
569
+ ):
570
+ model = VisionTransformer(
571
+ img_size=img_size,
572
+ patch_size=14,
573
+ use_mean_pooling=False,
574
+ embed_dim=1408,
575
+ depth=39,
576
+ num_heads=1408//88,
577
+ mlp_ratio=4.3637,
578
+ qkv_bias=True,
579
+ drop_path_rate=drop_path_rate,
580
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
581
+ use_checkpoint=use_checkpoint,
582
+ temporal_downsample=temporal_downsample,
583
+ no_lmhra=no_lmhra,
584
+ double_lmhra=double_lmhra,
585
+ lmhra_reduction=lmhra_reduction,
586
+ gmhra_layers=gmhra_layers,
587
+ gmhra_drop_path_rate=gmhra_drop_path_rate,
588
+ gmhra_dropout=gmhra_dropout,
589
+ )
590
+ if vit_model_path is not None and os.path.isfile(vit_model_path):
591
+ state_dict = torch.load(vit_model_path, map_location="cpu")
592
+ print(f"Load ViT model from: {vit_model_path}")
593
+ interpolate_pos_embed(model, state_dict)
594
+ msg = load_state_dict(model, state_dict, strict=False)
595
+ print(msg)
596
+
597
+ if precision == "fp16":
598
+ # model.to("cuda")
599
+ convert_weights_to_fp16(model)
600
+ return model
601
+
602
+
603
+ if __name__ == '__main__':
604
+ import time
605
+ from fvcore.nn import FlopCountAnalysis
606
+ from fvcore.nn import flop_count_table
607
+ import numpy as np
608
+
609
+ seed = 4217
610
+ np.random.seed(seed)
611
+ torch.manual_seed(seed)
612
+ torch.cuda.manual_seed(seed)
613
+ torch.cuda.manual_seed_all(seed)
614
+ num_frames = 8
615
+
616
+ model = create_eva_vit_g(
617
+ img_size=224, drop_path_rate=0.4, use_checkpoint=False,
618
+ precision="fp16", vit_model_path=None,
619
+ temporal_downsample=True,
620
+ no_lmhra=False,
621
+ double_lmhra=False,
622
+ lmhra_reduction=2.0,
623
+ gmhra_layers=12,
624
+ gmhra_drop_path_rate=0.,
625
+ gmhra_dropout=0.5,
626
+ )
627
+ video = torch.rand(1, 3, num_frames, 224, 224)
628
+ flops = FlopCountAnalysis(model, video)
629
+ s = time.time()
630
+ print(flop_count_table(flops, max_depth=1))
631
+ print(time.time()-s)
models/modeling_llama.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This script is based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
2
+
3
+ """ PyTorch LLaMA model."""
4
+ import math
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ import torch
8
+ import torch.utils.checkpoint
9
+ from torch import nn
10
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
11
+
12
+ from transformers.activations import ACT2FN
13
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
16
+ from transformers.models.llama.configuration_llama import LlamaConfig
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+ _CONFIG_FOR_DOC = "LlamaConfig"
22
+
23
+
24
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
25
+ def _make_causal_mask(
26
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
27
+ ):
28
+ """
29
+ Make causal mask used for bi-directional self-attention.
30
+ """
31
+ bsz, tgt_len = input_ids_shape
32
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
33
+ mask_cond = torch.arange(mask.size(-1), device=device)
34
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
35
+ mask = mask.to(dtype)
36
+
37
+ if past_key_values_length > 0:
38
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
39
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
40
+
41
+
42
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
43
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
44
+ """
45
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
46
+ """
47
+ bsz, src_len = mask.size()
48
+ tgt_len = tgt_len if tgt_len is not None else src_len
49
+
50
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
51
+
52
+ inverted_mask = 1.0 - expanded_mask
53
+
54
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
55
+
56
+
57
+ class LlamaRMSNorm(nn.Module):
58
+ def __init__(self, hidden_size, eps=1e-6):
59
+ """
60
+ LlamaRMSNorm is equivalent to T5LayerNorm
61
+ """
62
+ super().__init__()
63
+ self.weight = nn.Parameter(torch.ones(hidden_size))
64
+ self.variance_epsilon = eps
65
+
66
+ def forward(self, hidden_states):
67
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
68
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
69
+
70
+ # convert into half-precision if necessary
71
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
72
+ hidden_states = hidden_states.to(self.weight.dtype)
73
+
74
+ return self.weight * hidden_states
75
+
76
+
77
+ class LlamaRotaryEmbedding(torch.nn.Module):
78
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
79
+ super().__init__()
80
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
81
+ self.register_buffer("inv_freq", inv_freq)
82
+
83
+ # Build here to make `torch.jit.trace` work.
84
+ self.max_seq_len_cached = max_position_embeddings
85
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
86
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
87
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
88
+ emb = torch.cat((freqs, freqs), dim=-1)
89
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
90
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
91
+
92
+ def forward(self, x, seq_len=None):
93
+ # x: [bs, num_attention_heads, seq_len, head_size]
94
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
95
+ if seq_len > self.max_seq_len_cached:
96
+ self.max_seq_len_cached = seq_len
97
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
98
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
99
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
100
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
101
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
102
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
103
+ return (
104
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
105
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
106
+ )
107
+
108
+
109
+ def rotate_half(x):
110
+ """Rotates half the hidden dims of the input."""
111
+ x1 = x[..., : x.shape[-1] // 2]
112
+ x2 = x[..., x.shape[-1] // 2 :]
113
+ return torch.cat((-x2, x1), dim=-1)
114
+
115
+
116
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
117
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
118
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
119
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
120
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
121
+ q_embed = (q * cos) + (rotate_half(q) * sin)
122
+ k_embed = (k * cos) + (rotate_half(k) * sin)
123
+ return q_embed, k_embed
124
+
125
+
126
+ class LlamaMLP(nn.Module):
127
+ def __init__(
128
+ self,
129
+ hidden_size: int,
130
+ intermediate_size: int,
131
+ hidden_act: str,
132
+ ):
133
+ super().__init__()
134
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
135
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
136
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
137
+ self.act_fn = ACT2FN[hidden_act]
138
+
139
+ def forward(self, x):
140
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
141
+
142
+
143
+ class LlamaAttention(nn.Module):
144
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
145
+
146
+ def __init__(self, config: LlamaConfig):
147
+ super().__init__()
148
+ self.config = config
149
+ self.hidden_size = config.hidden_size
150
+ self.num_heads = config.num_attention_heads
151
+ self.head_dim = self.hidden_size // self.num_heads
152
+ self.max_position_embeddings = config.max_position_embeddings
153
+
154
+ if (self.head_dim * self.num_heads) != self.hidden_size:
155
+ raise ValueError(
156
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
157
+ f" and `num_heads`: {self.num_heads})."
158
+ )
159
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
160
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
161
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
162
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
163
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
164
+
165
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
166
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
167
+
168
+ def forward(
169
+ self,
170
+ hidden_states: torch.Tensor,
171
+ attention_mask: Optional[torch.Tensor] = None,
172
+ position_ids: Optional[torch.LongTensor] = None,
173
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
174
+ output_attentions: bool = False,
175
+ use_cache: bool = False,
176
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
177
+ bsz, q_len, _ = hidden_states.size()
178
+
179
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
180
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
181
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
182
+
183
+ kv_seq_len = key_states.shape[-2]
184
+ if past_key_value is not None:
185
+ kv_seq_len += past_key_value[0].shape[-2]
186
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
187
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
188
+ # [bsz, nh, t, hd]
189
+
190
+ if past_key_value is not None:
191
+ # reuse k, v, self_attention
192
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
193
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
194
+
195
+ past_key_value = (key_states, value_states) if use_cache else None
196
+
197
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
198
+
199
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
200
+ raise ValueError(
201
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
202
+ f" {attn_weights.size()}"
203
+ )
204
+
205
+ if attention_mask is not None:
206
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
207
+ raise ValueError(
208
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
209
+ )
210
+ attn_weights = attn_weights + attention_mask
211
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
212
+
213
+ # upcast attention to fp32
214
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
215
+ attn_output = torch.matmul(attn_weights, value_states)
216
+
217
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
218
+ raise ValueError(
219
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
220
+ f" {attn_output.size()}"
221
+ )
222
+
223
+ attn_output = attn_output.transpose(1, 2)
224
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
225
+
226
+ attn_output = self.o_proj(attn_output)
227
+
228
+ if not output_attentions:
229
+ attn_weights = None
230
+
231
+ return attn_output, attn_weights, past_key_value
232
+
233
+
234
+ class LlamaDecoderLayer(nn.Module):
235
+ def __init__(self, config: LlamaConfig):
236
+ super().__init__()
237
+ self.hidden_size = config.hidden_size
238
+ self.self_attn = LlamaAttention(config=config)
239
+ self.mlp = LlamaMLP(
240
+ hidden_size=self.hidden_size,
241
+ intermediate_size=config.intermediate_size,
242
+ hidden_act=config.hidden_act,
243
+ )
244
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
245
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
246
+
247
+ def forward(
248
+ self,
249
+ hidden_states: torch.Tensor,
250
+ attention_mask: Optional[torch.Tensor] = None,
251
+ position_ids: Optional[torch.LongTensor] = None,
252
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
253
+ output_attentions: Optional[bool] = False,
254
+ use_cache: Optional[bool] = False,
255
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
256
+ """
257
+ Args:
258
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
259
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
260
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
261
+ output_attentions (`bool`, *optional*):
262
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
263
+ returned tensors for more detail.
264
+ use_cache (`bool`, *optional*):
265
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
266
+ (see `past_key_values`).
267
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
268
+ """
269
+
270
+ residual = hidden_states
271
+
272
+ hidden_states = self.input_layernorm(hidden_states)
273
+
274
+ # Self Attention
275
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
276
+ hidden_states=hidden_states,
277
+ attention_mask=attention_mask,
278
+ position_ids=position_ids,
279
+ past_key_value=past_key_value,
280
+ output_attentions=output_attentions,
281
+ use_cache=use_cache,
282
+ )
283
+ hidden_states = residual + hidden_states
284
+
285
+ # Fully Connected
286
+ residual = hidden_states
287
+ hidden_states = self.post_attention_layernorm(hidden_states)
288
+ hidden_states = self.mlp(hidden_states)
289
+ hidden_states = residual + hidden_states
290
+
291
+ outputs = (hidden_states,)
292
+
293
+ if output_attentions:
294
+ outputs += (self_attn_weights,)
295
+
296
+ if use_cache:
297
+ outputs += (present_key_value,)
298
+
299
+ return outputs
300
+
301
+
302
+ LLAMA_START_DOCSTRING = r"""
303
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
304
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
305
+ etc.)
306
+
307
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
308
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
309
+ and behavior.
310
+
311
+ Parameters:
312
+ config ([`LlamaConfig`]):
313
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
314
+ load the weights associated with the model, only the configuration. Check out the
315
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
316
+ """
317
+
318
+
319
+ @add_start_docstrings(
320
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
321
+ LLAMA_START_DOCSTRING,
322
+ )
323
+ class LlamaPreTrainedModel(PreTrainedModel):
324
+ config_class = LlamaConfig
325
+ base_model_prefix = "model"
326
+ supports_gradient_checkpointing = True
327
+ _no_split_modules = ["LlamaDecoderLayer"]
328
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
329
+
330
+ def _init_weights(self, module):
331
+ std = self.config.initializer_range
332
+ if isinstance(module, nn.Linear):
333
+ module.weight.data.normal_(mean=0.0, std=std)
334
+ if module.bias is not None:
335
+ module.bias.data.zero_()
336
+ elif isinstance(module, nn.Embedding):
337
+ module.weight.data.normal_(mean=0.0, std=std)
338
+ if module.padding_idx is not None:
339
+ module.weight.data[module.padding_idx].zero_()
340
+
341
+ def _set_gradient_checkpointing(self, module, value=False):
342
+ if isinstance(module, LlamaModel):
343
+ module.gradient_checkpointing = value
344
+
345
+
346
+ LLAMA_INPUTS_DOCSTRING = r"""
347
+ Args:
348
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
349
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
350
+ it.
351
+
352
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
353
+ [`PreTrainedTokenizer.__call__`] for details.
354
+
355
+ [What are input IDs?](../glossary#input-ids)
356
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
357
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
358
+
359
+ - 1 for tokens that are **not masked**,
360
+ - 0 for tokens that are **masked**.
361
+
362
+ [What are attention masks?](../glossary#attention-mask)
363
+
364
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
365
+ [`PreTrainedTokenizer.__call__`] for details.
366
+
367
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
368
+ `past_key_values`).
369
+
370
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
371
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
372
+ information on the default strategy.
373
+
374
+ - 1 indicates the head is **not masked**,
375
+ - 0 indicates the head is **masked**.
376
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
377
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
378
+ config.n_positions - 1]`.
379
+
380
+ [What are position IDs?](../glossary#position-ids)
381
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
382
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
383
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
384
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
385
+
386
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
387
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
388
+
389
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
390
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
391
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
392
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
393
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
394
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
395
+ model's internal embedding lookup matrix.
396
+ use_cache (`bool`, *optional*):
397
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
398
+ `past_key_values`).
399
+ output_attentions (`bool`, *optional*):
400
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
401
+ tensors for more detail.
402
+ output_hidden_states (`bool`, *optional*):
403
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
404
+ more detail.
405
+ return_dict (`bool`, *optional*):
406
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
407
+ """
408
+
409
+
410
+ @add_start_docstrings(
411
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
412
+ LLAMA_START_DOCSTRING,
413
+ )
414
+ class LlamaModel(LlamaPreTrainedModel):
415
+ """
416
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
417
+
418
+ Args:
419
+ config: LlamaConfig
420
+ """
421
+
422
+ def __init__(self, config: LlamaConfig):
423
+ super().__init__(config)
424
+ self.padding_idx = config.pad_token_id
425
+ self.vocab_size = config.vocab_size
426
+
427
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
428
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
429
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
430
+
431
+ self.gradient_checkpointing = False
432
+ # Initialize weights and apply final processing
433
+ self.post_init()
434
+
435
+ def get_input_embeddings(self):
436
+ return self.embed_tokens
437
+
438
+ def set_input_embeddings(self, value):
439
+ self.embed_tokens = value
440
+
441
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
442
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
443
+ # create causal mask
444
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
445
+ combined_attention_mask = None
446
+ if input_shape[-1] > 1:
447
+ combined_attention_mask = _make_causal_mask(
448
+ input_shape,
449
+ inputs_embeds.dtype,
450
+ device=inputs_embeds.device,
451
+ past_key_values_length=past_key_values_length,
452
+ )
453
+
454
+ if attention_mask is not None:
455
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
456
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
457
+ inputs_embeds.device
458
+ )
459
+ combined_attention_mask = (
460
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
461
+ )
462
+
463
+ return combined_attention_mask
464
+
465
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
466
+ def forward(
467
+ self,
468
+ input_ids: torch.LongTensor = None,
469
+ attention_mask: Optional[torch.Tensor] = None,
470
+ position_ids: Optional[torch.LongTensor] = None,
471
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
472
+ inputs_embeds: Optional[torch.FloatTensor] = None,
473
+ query_embeds: Optional[torch.FloatTensor] = None,
474
+ use_cache: Optional[bool] = None,
475
+ output_attentions: Optional[bool] = None,
476
+ output_hidden_states: Optional[bool] = None,
477
+ return_dict: Optional[bool] = None,
478
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
479
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
480
+ output_hidden_states = (
481
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
482
+ )
483
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
484
+
485
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
486
+
487
+ # retrieve input_ids and inputs_embeds
488
+ if input_ids is not None and inputs_embeds is not None:
489
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
490
+ elif input_ids is not None:
491
+ batch_size, seq_length = input_ids.shape
492
+ elif inputs_embeds is not None:
493
+ batch_size, seq_length, _ = inputs_embeds.shape
494
+ else:
495
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
496
+
497
+ if inputs_embeds is None:
498
+ inputs_embeds = self.embed_tokens(input_ids)
499
+ if query_embeds is not None:
500
+ inputs_embeds = torch.cat([query_embeds, inputs_embeds], dim=1)
501
+ batch_size, seq_length, _ = inputs_embeds.shape
502
+
503
+ seq_length_with_past = seq_length
504
+ past_key_values_length = 0
505
+
506
+ if past_key_values is not None:
507
+ past_key_values_length = past_key_values[0][0].shape[2]
508
+ seq_length_with_past = seq_length_with_past + past_key_values_length
509
+
510
+ if position_ids is None:
511
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
512
+ position_ids = torch.arange(
513
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
514
+ )
515
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
516
+ else:
517
+ position_ids = position_ids.view(-1, seq_length).long()
518
+
519
+ # embed positions
520
+ if attention_mask is None:
521
+ attention_mask = torch.ones(
522
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
523
+ )
524
+ attention_mask = self._prepare_decoder_attention_mask(
525
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
526
+ )
527
+
528
+ hidden_states = inputs_embeds
529
+
530
+ if self.gradient_checkpointing and self.training:
531
+ if use_cache:
532
+ logger.warning_once(
533
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
534
+ )
535
+ use_cache = False
536
+
537
+ # decoder layers
538
+ all_hidden_states = () if output_hidden_states else None
539
+ all_self_attns = () if output_attentions else None
540
+ next_decoder_cache = () if use_cache else None
541
+
542
+ for idx, decoder_layer in enumerate(self.layers):
543
+ if output_hidden_states:
544
+ all_hidden_states += (hidden_states,)
545
+
546
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
547
+
548
+ if self.gradient_checkpointing and self.training:
549
+
550
+ def create_custom_forward(module):
551
+ def custom_forward(*inputs):
552
+ # None for past_key_value
553
+ return module(*inputs, output_attentions, None)
554
+
555
+ return custom_forward
556
+
557
+ layer_outputs = torch.utils.checkpoint.checkpoint(
558
+ create_custom_forward(decoder_layer),
559
+ hidden_states,
560
+ attention_mask,
561
+ position_ids,
562
+ None,
563
+ )
564
+ else:
565
+ layer_outputs = decoder_layer(
566
+ hidden_states,
567
+ attention_mask=attention_mask,
568
+ position_ids=position_ids,
569
+ past_key_value=past_key_value,
570
+ output_attentions=output_attentions,
571
+ use_cache=use_cache,
572
+ )
573
+
574
+ hidden_states = layer_outputs[0]
575
+
576
+ if use_cache:
577
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
578
+
579
+ if output_attentions:
580
+ all_self_attns += (layer_outputs[1],)
581
+
582
+ hidden_states = self.norm(hidden_states)
583
+
584
+ # add hidden states from the last decoder layer
585
+ if output_hidden_states:
586
+ all_hidden_states += (hidden_states,)
587
+
588
+ next_cache = next_decoder_cache if use_cache else None
589
+ if not return_dict:
590
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
591
+ return BaseModelOutputWithPast(
592
+ last_hidden_state=hidden_states,
593
+ past_key_values=next_cache,
594
+ hidden_states=all_hidden_states,
595
+ attentions=all_self_attns,
596
+ )
597
+
598
+
599
+ class LlamaForCausalLM(LlamaPreTrainedModel):
600
+ def __init__(self, config):
601
+ super().__init__(config)
602
+ self.model = LlamaModel(config)
603
+
604
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
605
+
606
+ # Initialize weights and apply final processing
607
+ self.post_init()
608
+
609
+ def get_input_embeddings(self):
610
+ return self.model.embed_tokens
611
+
612
+ def set_input_embeddings(self, value):
613
+ self.model.embed_tokens = value
614
+
615
+ def get_output_embeddings(self):
616
+ return self.lm_head
617
+
618
+ def set_output_embeddings(self, new_embeddings):
619
+ self.lm_head = new_embeddings
620
+
621
+ def set_decoder(self, decoder):
622
+ self.model = decoder
623
+
624
+ def get_decoder(self):
625
+ return self.model
626
+
627
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
628
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
629
+ def forward(
630
+ self,
631
+ input_ids: torch.LongTensor = None,
632
+ attention_mask: Optional[torch.Tensor] = None,
633
+ position_ids: Optional[torch.LongTensor] = None,
634
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
635
+ inputs_embeds: Optional[torch.FloatTensor] = None,
636
+ query_embeds: Optional[torch.FloatTensor] = None,
637
+ labels: Optional[torch.LongTensor] = None,
638
+ use_cache: Optional[bool] = None,
639
+ output_attentions: Optional[bool] = None,
640
+ output_hidden_states: Optional[bool] = None,
641
+ return_dict: Optional[bool] = None,
642
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
643
+ r"""
644
+ Args:
645
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
646
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
647
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
648
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
649
+
650
+ Returns:
651
+
652
+ Example:
653
+
654
+ ```python
655
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
656
+
657
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
658
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
659
+
660
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
661
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
662
+
663
+ >>> # Generate
664
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
665
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
666
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
667
+ ```"""
668
+
669
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
670
+ output_hidden_states = (
671
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
672
+ )
673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
674
+
675
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
676
+ outputs = self.model(
677
+ input_ids=input_ids,
678
+ attention_mask=attention_mask,
679
+ position_ids=position_ids,
680
+ past_key_values=past_key_values,
681
+ inputs_embeds=inputs_embeds,
682
+ query_embeds=query_embeds,
683
+ use_cache=use_cache,
684
+ output_attentions=output_attentions,
685
+ output_hidden_states=output_hidden_states,
686
+ return_dict=return_dict,
687
+ )
688
+
689
+ hidden_states = outputs[0]
690
+ logits = self.lm_head(hidden_states)
691
+
692
+ loss = None
693
+ if labels is not None:
694
+ # Shift so that tokens < n predict n
695
+ shift_logits = logits[..., :-1, :].contiguous()
696
+ shift_labels = labels[..., 1:].contiguous()
697
+ # Flatten the tokens
698
+ loss_fct = CrossEntropyLoss()
699
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
700
+ shift_labels = shift_labels.view(-1)
701
+ # Enable model parallelism
702
+ shift_labels = shift_labels.to(shift_logits.device)
703
+ loss = loss_fct(shift_logits, shift_labels)
704
+
705
+ if not return_dict:
706
+ output = (logits,) + outputs[1:]
707
+ return (loss,) + output if loss is not None else output
708
+
709
+ return CausalLMOutputWithPast(
710
+ loss=loss,
711
+ logits=logits,
712
+ past_key_values=outputs.past_key_values,
713
+ hidden_states=outputs.hidden_states,
714
+ attentions=outputs.attentions,
715
+ )
716
+
717
+ def prepare_inputs_for_generation(
718
+ self, input_ids, query_embeds=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
719
+ ):
720
+ if past_key_values:
721
+ input_ids = input_ids[:, -1:]
722
+
723
+ position_ids = kwargs.get("position_ids", None)
724
+ if attention_mask is not None and position_ids is None:
725
+ # create position_ids on the fly for batch generation
726
+ position_ids = attention_mask.long().cumsum(-1) - 1
727
+ position_ids.masked_fill_(attention_mask == 0, 1)
728
+ if past_key_values:
729
+ position_ids = position_ids[:, -1].unsqueeze(-1)
730
+ query_embeds = None
731
+
732
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
733
+ if inputs_embeds is not None and past_key_values is None:
734
+ model_inputs = {"inputs_embeds": inputs_embeds}
735
+ else:
736
+ model_inputs = {"input_ids": input_ids}
737
+
738
+ model_inputs.update(
739
+ {
740
+ "position_ids": position_ids,
741
+ "query_embeds": query_embeds,
742
+ "past_key_values": past_key_values,
743
+ "use_cache": kwargs.get("use_cache"),
744
+ "attention_mask": attention_mask,
745
+ }
746
+ )
747
+ return model_inputs
748
+
749
+ @staticmethod
750
+ def _reorder_cache(past_key_values, beam_idx):
751
+ reordered_past = ()
752
+ for layer_past in past_key_values:
753
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
754
+ return reordered_past
755
+
models/video_transformers.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torchvision
2
+ import random
3
+ from PIL import Image, ImageOps
4
+ import numpy as np
5
+ import numbers
6
+ import math
7
+ import torch
8
+
9
+
10
+ class GroupRandomCrop(object):
11
+ def __init__(self, size):
12
+ if isinstance(size, numbers.Number):
13
+ self.size = (int(size), int(size))
14
+ else:
15
+ self.size = size
16
+
17
+ def __call__(self, img_group):
18
+
19
+ w, h = img_group[0].size
20
+ th, tw = self.size
21
+
22
+ out_images = list()
23
+
24
+ x1 = random.randint(0, w - tw)
25
+ y1 = random.randint(0, h - th)
26
+
27
+ for img in img_group:
28
+ assert(img.size[0] == w and img.size[1] == h)
29
+ if w == tw and h == th:
30
+ out_images.append(img)
31
+ else:
32
+ out_images.append(img.crop((x1, y1, x1 + tw, y1 + th)))
33
+
34
+ return out_images
35
+
36
+
37
+ class MultiGroupRandomCrop(object):
38
+ def __init__(self, size, groups=1):
39
+ if isinstance(size, numbers.Number):
40
+ self.size = (int(size), int(size))
41
+ else:
42
+ self.size = size
43
+ self.groups = groups
44
+
45
+ def __call__(self, img_group):
46
+
47
+ w, h = img_group[0].size
48
+ th, tw = self.size
49
+
50
+ out_images = list()
51
+
52
+ for i in range(self.groups):
53
+ x1 = random.randint(0, w - tw)
54
+ y1 = random.randint(0, h - th)
55
+
56
+ for img in img_group:
57
+ assert(img.size[0] == w and img.size[1] == h)
58
+ if w == tw and h == th:
59
+ out_images.append(img)
60
+ else:
61
+ out_images.append(img.crop((x1, y1, x1 + tw, y1 + th)))
62
+
63
+ return out_images
64
+
65
+
66
+ class GroupCenterCrop(object):
67
+ def __init__(self, size):
68
+ self.worker = torchvision.transforms.CenterCrop(size)
69
+
70
+ def __call__(self, img_group):
71
+ return [self.worker(img) for img in img_group]
72
+
73
+
74
+ class GroupRandomHorizontalFlip(object):
75
+ """Randomly horizontally flips the given PIL.Image with a probability of 0.5
76
+ """
77
+
78
+ def __init__(self, is_flow=False):
79
+ self.is_flow = is_flow
80
+
81
+ def __call__(self, img_group, is_flow=False):
82
+ v = random.random()
83
+ if v < 0.5:
84
+ ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group]
85
+ if self.is_flow:
86
+ for i in range(0, len(ret), 2):
87
+ # invert flow pixel values when flipping
88
+ ret[i] = ImageOps.invert(ret[i])
89
+ return ret
90
+ else:
91
+ return img_group
92
+
93
+
94
+ class GroupNormalize(object):
95
+ def __init__(self, mean, std):
96
+ self.mean = mean
97
+ self.std = std
98
+
99
+ def __call__(self, tensor):
100
+ rep_mean = self.mean * (tensor.size()[0] // len(self.mean))
101
+ rep_std = self.std * (tensor.size()[0] // len(self.std))
102
+
103
+ # TODO: make efficient
104
+ for t, m, s in zip(tensor, rep_mean, rep_std):
105
+ t.sub_(m).div_(s)
106
+
107
+ return tensor
108
+
109
+
110
+ class GroupScale(object):
111
+ """ Rescales the input PIL.Image to the given 'size'.
112
+ 'size' will be the size of the smaller edge.
113
+ For example, if height > width, then image will be
114
+ rescaled to (size * height / width, size)
115
+ size: size of the smaller edge
116
+ interpolation: Default: PIL.Image.BILINEAR
117
+ """
118
+
119
+ def __init__(self, size, interpolation=Image.BILINEAR):
120
+ self.worker = torchvision.transforms.Resize(size, interpolation)
121
+
122
+ def __call__(self, img_group):
123
+ return [self.worker(img) for img in img_group]
124
+
125
+
126
+ class GroupOverSample(object):
127
+ def __init__(self, crop_size, scale_size=None, flip=True):
128
+ self.crop_size = crop_size if not isinstance(
129
+ crop_size, int) else (crop_size, crop_size)
130
+
131
+ if scale_size is not None:
132
+ self.scale_worker = GroupScale(scale_size)
133
+ else:
134
+ self.scale_worker = None
135
+ self.flip = flip
136
+
137
+ def __call__(self, img_group):
138
+
139
+ if self.scale_worker is not None:
140
+ img_group = self.scale_worker(img_group)
141
+
142
+ image_w, image_h = img_group[0].size
143
+ crop_w, crop_h = self.crop_size
144
+
145
+ offsets = GroupMultiScaleCrop.fill_fix_offset(
146
+ False, image_w, image_h, crop_w, crop_h)
147
+ oversample_group = list()
148
+ for o_w, o_h in offsets:
149
+ normal_group = list()
150
+ flip_group = list()
151
+ for i, img in enumerate(img_group):
152
+ crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h))
153
+ normal_group.append(crop)
154
+ flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)
155
+
156
+ if img.mode == 'L' and i % 2 == 0:
157
+ flip_group.append(ImageOps.invert(flip_crop))
158
+ else:
159
+ flip_group.append(flip_crop)
160
+
161
+ oversample_group.extend(normal_group)
162
+ if self.flip:
163
+ oversample_group.extend(flip_group)
164
+ return oversample_group
165
+
166
+
167
+ class GroupFullResSample(object):
168
+ def __init__(self, crop_size, scale_size=None, flip=True):
169
+ self.crop_size = crop_size if not isinstance(
170
+ crop_size, int) else (crop_size, crop_size)
171
+
172
+ if scale_size is not None:
173
+ self.scale_worker = GroupScale(scale_size)
174
+ else:
175
+ self.scale_worker = None
176
+ self.flip = flip
177
+
178
+ def __call__(self, img_group):
179
+
180
+ if self.scale_worker is not None:
181
+ img_group = self.scale_worker(img_group)
182
+
183
+ image_w, image_h = img_group[0].size
184
+ crop_w, crop_h = self.crop_size
185
+
186
+ w_step = (image_w - crop_w) // 4
187
+ h_step = (image_h - crop_h) // 4
188
+
189
+ offsets = list()
190
+ offsets.append((0 * w_step, 2 * h_step)) # left
191
+ offsets.append((4 * w_step, 2 * h_step)) # right
192
+ offsets.append((2 * w_step, 2 * h_step)) # center
193
+
194
+ oversample_group = list()
195
+ for o_w, o_h in offsets:
196
+ normal_group = list()
197
+ flip_group = list()
198
+ for i, img in enumerate(img_group):
199
+ crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h))
200
+ normal_group.append(crop)
201
+ if self.flip:
202
+ flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)
203
+
204
+ if img.mode == 'L' and i % 2 == 0:
205
+ flip_group.append(ImageOps.invert(flip_crop))
206
+ else:
207
+ flip_group.append(flip_crop)
208
+
209
+ oversample_group.extend(normal_group)
210
+ oversample_group.extend(flip_group)
211
+ return oversample_group
212
+
213
+
214
+ class GroupMultiScaleCrop(object):
215
+
216
+ def __init__(self, input_size, scales=None, max_distort=1,
217
+ fix_crop=True, more_fix_crop=True):
218
+ self.scales = scales if scales is not None else [1, .875, .75, .66]
219
+ self.max_distort = max_distort
220
+ self.fix_crop = fix_crop
221
+ self.more_fix_crop = more_fix_crop
222
+ self.input_size = input_size if not isinstance(input_size, int) else [
223
+ input_size, input_size]
224
+ self.interpolation = Image.BILINEAR
225
+
226
+ def __call__(self, img_group):
227
+
228
+ im_size = img_group[0].size
229
+
230
+ crop_w, crop_h, offset_w, offset_h = self._sample_crop_size(im_size)
231
+ crop_img_group = [
232
+ img.crop(
233
+ (offset_w,
234
+ offset_h,
235
+ offset_w +
236
+ crop_w,
237
+ offset_h +
238
+ crop_h)) for img in img_group]
239
+ ret_img_group = [img.resize((self.input_size[0], self.input_size[1]), self.interpolation)
240
+ for img in crop_img_group]
241
+ return ret_img_group
242
+
243
+ def _sample_crop_size(self, im_size):
244
+ image_w, image_h = im_size[0], im_size[1]
245
+
246
+ # find a crop size
247
+ base_size = min(image_w, image_h)
248
+ crop_sizes = [int(base_size * x) for x in self.scales]
249
+ crop_h = [
250
+ self.input_size[1] if abs(
251
+ x - self.input_size[1]) < 3 else x for x in crop_sizes]
252
+ crop_w = [
253
+ self.input_size[0] if abs(
254
+ x - self.input_size[0]) < 3 else x for x in crop_sizes]
255
+
256
+ pairs = []
257
+ for i, h in enumerate(crop_h):
258
+ for j, w in enumerate(crop_w):
259
+ if abs(i - j) <= self.max_distort:
260
+ pairs.append((w, h))
261
+
262
+ crop_pair = random.choice(pairs)
263
+ if not self.fix_crop:
264
+ w_offset = random.randint(0, image_w - crop_pair[0])
265
+ h_offset = random.randint(0, image_h - crop_pair[1])
266
+ else:
267
+ w_offset, h_offset = self._sample_fix_offset(
268
+ image_w, image_h, crop_pair[0], crop_pair[1])
269
+
270
+ return crop_pair[0], crop_pair[1], w_offset, h_offset
271
+
272
+ def _sample_fix_offset(self, image_w, image_h, crop_w, crop_h):
273
+ offsets = self.fill_fix_offset(
274
+ self.more_fix_crop, image_w, image_h, crop_w, crop_h)
275
+ return random.choice(offsets)
276
+
277
+ @staticmethod
278
+ def fill_fix_offset(more_fix_crop, image_w, image_h, crop_w, crop_h):
279
+ w_step = (image_w - crop_w) // 4
280
+ h_step = (image_h - crop_h) // 4
281
+
282
+ ret = list()
283
+ ret.append((0, 0)) # upper left
284
+ ret.append((4 * w_step, 0)) # upper right
285
+ ret.append((0, 4 * h_step)) # lower left
286
+ ret.append((4 * w_step, 4 * h_step)) # lower right
287
+ ret.append((2 * w_step, 2 * h_step)) # center
288
+
289
+ if more_fix_crop:
290
+ ret.append((0, 2 * h_step)) # center left
291
+ ret.append((4 * w_step, 2 * h_step)) # center right
292
+ ret.append((2 * w_step, 4 * h_step)) # lower center
293
+ ret.append((2 * w_step, 0 * h_step)) # upper center
294
+
295
+ ret.append((1 * w_step, 1 * h_step)) # upper left quarter
296
+ ret.append((3 * w_step, 1 * h_step)) # upper right quarter
297
+ ret.append((1 * w_step, 3 * h_step)) # lower left quarter
298
+ ret.append((3 * w_step, 3 * h_step)) # lower righ quarter
299
+
300
+ return ret
301
+
302
+
303
+ class GroupRandomSizedCrop(object):
304
+ """Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size
305
+ and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio
306
+ This is popularly used to train the Inception networks
307
+ size: size of the smaller edge
308
+ interpolation: Default: PIL.Image.BILINEAR
309
+ """
310
+
311
+ def __init__(self, size, interpolation=Image.BILINEAR):
312
+ self.size = size
313
+ self.interpolation = interpolation
314
+
315
+ def __call__(self, img_group):
316
+ for attempt in range(10):
317
+ area = img_group[0].size[0] * img_group[0].size[1]
318
+ target_area = random.uniform(0.08, 1.0) * area
319
+ aspect_ratio = random.uniform(3. / 4, 4. / 3)
320
+
321
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
322
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
323
+
324
+ if random.random() < 0.5:
325
+ w, h = h, w
326
+
327
+ if w <= img_group[0].size[0] and h <= img_group[0].size[1]:
328
+ x1 = random.randint(0, img_group[0].size[0] - w)
329
+ y1 = random.randint(0, img_group[0].size[1] - h)
330
+ found = True
331
+ break
332
+ else:
333
+ found = False
334
+ x1 = 0
335
+ y1 = 0
336
+
337
+ if found:
338
+ out_group = list()
339
+ for img in img_group:
340
+ img = img.crop((x1, y1, x1 + w, y1 + h))
341
+ assert(img.size == (w, h))
342
+ out_group.append(
343
+ img.resize(
344
+ (self.size, self.size), self.interpolation))
345
+ return out_group
346
+ else:
347
+ # Fallback
348
+ scale = GroupScale(self.size, interpolation=self.interpolation)
349
+ crop = GroupRandomCrop(self.size)
350
+ return crop(scale(img_group))
351
+
352
+
353
+ class ConvertDataFormat(object):
354
+ def __init__(self, model_type):
355
+ self.model_type = model_type
356
+
357
+ def __call__(self, images):
358
+ if self.model_type == '2D':
359
+ return images
360
+ tc, h, w = images.size()
361
+ t = tc // 3
362
+ images = images.view(t, 3, h, w)
363
+ images = images.permute(1, 0, 2, 3)
364
+ return images
365
+
366
+
367
+ class Stack(object):
368
+
369
+ def __init__(self, roll=False):
370
+ self.roll = roll
371
+
372
+ def __call__(self, img_group):
373
+ if img_group[0].mode == 'L':
374
+ return np.concatenate([np.expand_dims(x, 2)
375
+ for x in img_group], axis=2)
376
+ elif img_group[0].mode == 'RGB':
377
+ if self.roll:
378
+ return np.concatenate([np.array(x)[:, :, ::-1]
379
+ for x in img_group], axis=2)
380
+ else:
381
+ #print(np.concatenate(img_group, axis=2).shape)
382
+ # print(img_group[0].shape)
383
+ return np.concatenate(img_group, axis=2)
384
+
385
+
386
+ class ToTorchFormatTensor(object):
387
+ """ Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255]
388
+ to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] """
389
+
390
+ def __init__(self, div=True):
391
+ self.div = div
392
+
393
+ def __call__(self, pic):
394
+ if isinstance(pic, np.ndarray):
395
+ # handle numpy array
396
+ img = torch.from_numpy(pic).permute(2, 0, 1).contiguous()
397
+ else:
398
+ # handle PIL Image
399
+ img = torch.ByteTensor(
400
+ torch.ByteStorage.from_buffer(
401
+ pic.tobytes()))
402
+ img = img.view(pic.size[1], pic.size[0], len(pic.mode))
403
+ # put it from HWC to CHW format
404
+ # yikes, this transpose takes 80% of the loading time/CPU
405
+ img = img.transpose(0, 1).transpose(0, 2).contiguous()
406
+ return img.float().div(255) if self.div else img.float()
407
+
408
+
409
+ class IdentityTransform(object):
410
+
411
+ def __call__(self, data):
412
+ return data
413
+
414
+
415
+ if __name__ == "__main__":
416
+ trans = torchvision.transforms.Compose([
417
+ GroupScale(256),
418
+ GroupRandomCrop(224),
419
+ Stack(),
420
+ ToTorchFormatTensor(),
421
+ GroupNormalize(
422
+ mean=[.485, .456, .406],
423
+ std=[.229, .224, .225]
424
+ )]
425
+ )
426
+
427
+ im = Image.open('../tensorflow-model-zoo.torch/lena_299.png')
428
+
429
+ color_group = [im] * 3
430
+ rst = trans(color_group)
431
+
432
+ gray_group = [im.convert('L')] * 9
433
+ gray_rst = trans(gray_group)
434
+
435
+ trans2 = torchvision.transforms.Compose([
436
+ GroupRandomSizedCrop(256),
437
+ Stack(),
438
+ ToTorchFormatTensor(),
439
+ GroupNormalize(
440
+ mean=[.485, .456, .406],
441
+ std=[.229, .224, .225])
442
+ ])
443
+ print(trans2(color_group))
models/videochat.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import logging
3
+
4
+ import torch
5
+ from torch.cuda.amp import autocast as autocast
6
+ import torch.nn as nn
7
+
8
+ from .blip2 import Blip2Base, disabled_train
9
+ from .modeling_llama import LlamaForCausalLM
10
+ from transformers import LlamaTokenizer, LlamaConfig
11
+
12
+
13
+ class VideoChat(Blip2Base):
14
+ """
15
+ VideoChat model.
16
+ """
17
+ def __init__(self, config):
18
+ super().__init__()
19
+
20
+ vit_model = config.get("vit_model", "eva_clip_g")
21
+ vit_model_path = config.get("vit_model_path", None)
22
+ q_former_model_path = config.get("q_former_model_path", None)
23
+ llama_model_path = config.get("llama_model_path")
24
+ videochat_model_path = config.get("videochat_model_path", "")
25
+ img_size = config.get("img_size")
26
+
27
+ drop_path_rate = config.get("drop_path_rate", 0)
28
+ use_grad_checkpoint = config.get("use_grad_checkpoint", False)
29
+ vit_precision = config.get("vit_precision", "fp16")
30
+ freeze_vit = config.get("freeze_vit", True)
31
+ freeze_qformer = config.get("freeze_qformer", True)
32
+ low_resource = config.get("low_resource", False) # use 8 bit and put vit in cpu
33
+ max_txt_len = config.get("max_txt_len", 32)
34
+
35
+ # uniformerv2
36
+ freeze_mhra = config.get("freeze_mhra", False)
37
+ temporal_downsample = config.get("temporal_downsample", True)
38
+ no_lmhra = config.get("no_lmhra", False)
39
+ double_lmhra = config.get("double_lmhra", False)
40
+ lmhra_reduction = config.get("lmhra_reduction", 2.0)
41
+ gmhra_layers = config.get("gmhra_layers", 8)
42
+ gmhra_drop_path_rate = config.get("gmhra_drop_path_rate", 0.)
43
+ gmhra_dropout = config.get("gmhra_dropout", 0.5)
44
+ # qformer
45
+ num_query_token = config.get("num_query_token")
46
+ extra_num_query_token = config.get("extra_num_query_token", 64)
47
+
48
+ self.tokenizer = self.init_tokenizer()
49
+ self.low_resource = low_resource
50
+
51
+ self.vit_precision = vit_precision
52
+ print(f'Loading VIT. Use fp16: {vit_precision}')
53
+ self.visual_encoder, self.ln_vision = self.init_vision_encoder(
54
+ vit_model, img_size, drop_path_rate,
55
+ use_grad_checkpoint, vit_precision, vit_model_path,
56
+ temporal_downsample=temporal_downsample,
57
+ no_lmhra=no_lmhra,
58
+ double_lmhra=double_lmhra,
59
+ lmhra_reduction=lmhra_reduction,
60
+ gmhra_layers=gmhra_layers,
61
+ gmhra_drop_path_rate=gmhra_drop_path_rate,
62
+ gmhra_dropout=gmhra_dropout,
63
+ )
64
+ if freeze_vit:
65
+ print("freeze vision encoder")
66
+ if not freeze_mhra:
67
+ open_list = []
68
+ for name, param in self.visual_encoder.named_parameters():
69
+ if 'mhra' not in name:
70
+ param.requires_grad = False
71
+ else:
72
+ open_list.append(name)
73
+ print(f"open module: {open_list}")
74
+ print("open ln_vision")
75
+ else:
76
+ for name, param in self.visual_encoder.named_parameters():
77
+ param.requires_grad = False
78
+ self.visual_encoder = self.visual_encoder.eval()
79
+ self.visual_encoder.train = disabled_train
80
+ for name, param in self.ln_vision.named_parameters():
81
+ param.requires_grad = False
82
+ self.ln_vision = self.ln_vision.eval()
83
+ self.ln_vision.train = disabled_train
84
+ print('Loading VIT Done')
85
+
86
+ print('Loading Q-Former')
87
+ self.Qformer, self.query_tokens = self.init_Qformer(
88
+ num_query_token, self.visual_encoder.num_features,
89
+ )
90
+ self.Qformer.cls = None
91
+ self.Qformer.bert.embeddings.word_embeddings = None
92
+ self.Qformer.bert.embeddings.position_embeddings = None
93
+ for layer in self.Qformer.bert.encoder.layer:
94
+ layer.output = None
95
+ layer.intermediate = None
96
+ self.load_from_pretrained(model_path=q_former_model_path)
97
+ print(f"Add extra {extra_num_query_token} tokens in QFormer")
98
+ self.extra_query_tokens = nn.Parameter(
99
+ torch.zeros(1, extra_num_query_token, self.query_tokens.shape[-1])
100
+ )
101
+
102
+ if freeze_qformer:
103
+ print("freeze Qformer")
104
+ for name, param in self.Qformer.named_parameters():
105
+ param.requires_grad = False
106
+ self.Qformer = self.Qformer.eval()
107
+ self.Qformer.train = disabled_train
108
+ self.query_tokens.requires_grad = False
109
+ print('Loading Q-Former Done')
110
+
111
+ print('Loading LLAMA')
112
+ self.llama_tokenizer = LlamaTokenizer.from_pretrained(llama_model_path, use_fast=False)
113
+ self.llama_tokenizer.pad_token = self.llama_tokenizer.eos_token
114
+
115
+ if self.low_resource:
116
+ self.llama_model = LlamaForCausalLM.from_pretrained(
117
+ llama_model_path,
118
+ torch_dtype=torch.float16,
119
+ load_in_8bit=True,
120
+ device_map="auto"
121
+ )
122
+ else:
123
+ self.llama_model = LlamaForCausalLM.from_pretrained(
124
+ llama_model_path,
125
+ torch_dtype=torch.float16,
126
+ )
127
+
128
+ print("freeze LLAMA")
129
+ for name, param in self.llama_model.named_parameters():
130
+ param.requires_grad = False
131
+ print('Loading LLAMA Done')
132
+
133
+ self.llama_proj = nn.Linear(
134
+ self.Qformer.config.hidden_size, self.llama_model.config.hidden_size
135
+ )
136
+ self.max_txt_len = max_txt_len
137
+
138
+ # load weights of VideoChat
139
+ if videochat_model_path:
140
+ print(f"Load VideoChat from: {videochat_model_path}")
141
+ ckpt = torch.load(videochat_model_path, map_location="cpu")
142
+ msg = self.load_state_dict(ckpt['model'], strict=False)
143
+ print(msg)
144
+
145
+ def vit_to_cpu(self):
146
+ self.ln_vision.to("cpu")
147
+ self.ln_vision.float()
148
+ self.visual_encoder.to("cpu")
149
+ self.visual_encoder.float()
150
+
151
+ def encode_img(self, image):
152
+ device = image.device
153
+ if self.low_resource:
154
+ self.vit_to_cpu()
155
+ image = image.to("cpu")
156
+
157
+ with self.maybe_autocast():
158
+ T = image.shape[1]
159
+ # use_image = True if T == 1 else False
160
+ image = image.permute(0, 2, 1, 3, 4) # [B,T,C,H,W] -> [B,C,T,H,W]
161
+
162
+ image_embeds = self.ln_vision(self.visual_encoder(image)).to(device)
163
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device)
164
+
165
+ query_tokens = torch.cat([self.query_tokens, self.extra_query_tokens], dim=1)
166
+ query_tokens = query_tokens.expand(image_embeds.shape[0], -1, -1)
167
+ query_output = self.Qformer.bert(
168
+ query_embeds=query_tokens,
169
+ encoder_hidden_states=image_embeds,
170
+ encoder_attention_mask=image_atts,
171
+ return_dict=True,
172
+ )
173
+
174
+ inputs_llama = self.llama_proj(query_output.last_hidden_state)
175
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(image.device)
176
+ return inputs_llama, atts_llama
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ decord==0.6.0
2
+ fvcore==0.1.5.post20221221
3
+ gradio==3.29.0
4
+ numpy==1.24.3
5
+ Pillow==9.5.0
6
+ PyYAML==6.0
7
+ timm==0.6.13
8
+ torch==1.12.1
9
+ torchvision==0.13.1
10
+ transformers==4.28.1
11
+ sentencepiece==0.1.99
utils/__pycache__/config.cpython-38.pyc ADDED
Binary file (6.82 kB). View file
 
utils/__pycache__/easydict.cpython-38.pyc ADDED
Binary file (3.61 kB). View file
 
utils/config.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import ast
5
+ import json
6
+ import os
7
+ import os.path as osp
8
+ import re
9
+ import shutil
10
+ import sys
11
+ import tempfile
12
+ from copy import deepcopy
13
+ from importlib import import_module
14
+
15
+ import yaml
16
+
17
+ from .easydict import EasyDict
18
+
19
+ __all__ = ["Config", "pretty_text"]
20
+
21
+
22
+ BASE_KEY = "_base_"
23
+ # BASE_CONFIG = {"OUTPUT_DIR": "./workspace", "SESSION": "base", "LOG_FILE": "log.txt"}
24
+ BASE_CONFIG = {}
25
+
26
+ cfg = None
27
+
28
+
29
+ class Config(object):
30
+ """config"""
31
+
32
+ @classmethod
33
+ def pretty_text(cls, cfg: dict, indent=2) -> str:
34
+ """format dict to a string
35
+
36
+ Args:
37
+ cfg (EasyDict): the params.
38
+
39
+ Returns: The string to display.
40
+
41
+ """
42
+ msg = "{\n"
43
+ for i, (k, v) in enumerate(cfg.items()):
44
+ if isinstance(v, dict):
45
+ v = cls.pretty_text(v, indent + 4)
46
+ spaces = " " * indent
47
+ msg += spaces + "{}: {}".format(k, v)
48
+ if i == len(cfg) - 1:
49
+ msg += " }"
50
+ else:
51
+ msg += "\n"
52
+ return msg
53
+
54
+ @classmethod
55
+ def dump(cls, cfg, savepath=None):
56
+ """dump cfg to `json` file.
57
+
58
+ Args:
59
+ cfg (dict): The dict to dump.
60
+ savepath (str): The filepath to save the dumped dict.
61
+
62
+ Returns: TODO
63
+
64
+ """
65
+ if savepath is None:
66
+ savepath = osp.join(cfg.WORKSPACE, "config.json")
67
+ json.dump(cfg, open(savepath, "w"), indent=2)
68
+
69
+ @classmethod
70
+ def get_config(cls, default_config: dict = None):
71
+ """get a `Config` instance.
72
+
73
+ Args:
74
+ default_config (dict): The default config. `default_config` will be overrided
75
+ by config file `--cfg`, `--cfg` will be overrided by commandline args.
76
+
77
+ Returns: an EasyDict.
78
+ """
79
+ global cfg
80
+ if cfg is not None:
81
+ return cfg
82
+
83
+ # define arg parser.
84
+ parser = argparse.ArgumentParser()
85
+ # parser.add_argument("--cfg", help="load configs from yaml file", default="", type=str)
86
+ parser.add_argument(
87
+ "config_file", help="the configuration file to load. support: .yaml, .json, .py"
88
+ )
89
+ parser.add_argument(
90
+ "opts",
91
+ default=None,
92
+ nargs="*",
93
+ help="overrided configs. List. Format: 'key1 name1 key2 name2'",
94
+ )
95
+ args = parser.parse_args()
96
+
97
+ cfg = EasyDict(BASE_CONFIG)
98
+ if osp.isfile(args.config_file):
99
+ cfg_from_file = cls.from_file(args.config_file)
100
+ cfg = merge_a_into_b(cfg_from_file, cfg)
101
+ cfg = cls.merge_list(cfg, args.opts)
102
+ cfg = eval_dict_leaf(cfg)
103
+
104
+ # update some keys to make them show at the last
105
+ for k in BASE_CONFIG:
106
+ cfg[k] = cfg.pop(k)
107
+ return cfg
108
+
109
+ @classmethod
110
+ def from_file(cls, filepath: str) -> EasyDict:
111
+ """Build config from file. Supported filetypes: `.py`,`.yaml`,`.json`.
112
+
113
+ Args:
114
+ filepath (str): The config file path.
115
+
116
+ Returns: TODO
117
+
118
+ """
119
+ filepath = osp.abspath(osp.expanduser(filepath))
120
+ if not osp.isfile(filepath):
121
+ raise IOError(f"File does not exist: {filepath}")
122
+ if filepath.endswith(".py"):
123
+ with tempfile.TemporaryDirectory() as temp_config_dir:
124
+
125
+ shutil.copytree(osp.dirname(filepath), osp.join(temp_config_dir, "tmp_config"))
126
+ sys.path.insert(0, temp_config_dir)
127
+ mod = import_module("tmp_config." + osp.splitext(osp.basename(filepath))[0])
128
+ # mod = import_module(temp_module_name)
129
+ sys.path.pop(0)
130
+ cfg_dict = {
131
+ name: value
132
+ for name, value in mod.__dict__.items()
133
+ if not name.startswith("__")
134
+ }
135
+ for k in list(sys.modules.keys()):
136
+ if "tmp_config" in k:
137
+ del sys.modules[k]
138
+ elif filepath.endswith((".yml", ".yaml")):
139
+ cfg_dict = yaml.load(open(filepath, "r"), Loader=yaml.Loader)
140
+ elif filepath.endswith(".json"):
141
+ cfg_dict = json.load(open(filepath, "r"))
142
+ else:
143
+ raise IOError("Only py/yml/yaml/json type are supported now!")
144
+
145
+ cfg_text = filepath + "\n"
146
+ with open(filepath, "r") as f:
147
+ cfg_text += f.read()
148
+
149
+ if BASE_KEY in cfg_dict: # load configs in `BASE_KEY`
150
+ cfg_dir = osp.dirname(filepath)
151
+ base_filename = cfg_dict.pop(BASE_KEY)
152
+ base_filename = (
153
+ base_filename if isinstance(base_filename, list) else [base_filename]
154
+ )
155
+
156
+ cfg_dict_list = list()
157
+ for f in base_filename:
158
+ _cfg_dict = Config.from_file(osp.join(cfg_dir, f))
159
+ cfg_dict_list.append(_cfg_dict)
160
+
161
+ base_cfg_dict = dict()
162
+ for c in cfg_dict_list:
163
+ if len(base_cfg_dict.keys() & c.keys()) > 0:
164
+ raise KeyError("Duplicate key is not allowed among bases")
165
+ base_cfg_dict.update(c)
166
+
167
+ cfg_dict = merge_a_into_b(cfg_dict, base_cfg_dict)
168
+
169
+ return EasyDict(cfg_dict)
170
+
171
+ @classmethod
172
+ def merge_list(cls, cfg, opts: list):
173
+ """merge commandline opts.
174
+
175
+ Args:
176
+ cfg: (dict): The config to be merged.
177
+ opts (list): The list to merge. Format: [key1, name1, key2, name2,...].
178
+ The keys can be nested. For example, ["a.b", v] will be considered
179
+ as `dict(a=dict(b=v))`.
180
+
181
+ Returns: dict.
182
+
183
+ """
184
+ assert len(opts) % 2 == 0, f"length of opts must be even. Got: {opts}"
185
+ for i in range(0, len(opts), 2):
186
+ full_k, v = opts[i], opts[i + 1]
187
+ keys = full_k.split(".")
188
+ sub_d = cfg
189
+ for i, k in enumerate(keys):
190
+ if not hasattr(sub_d, k):
191
+ raise ValueError(f"The key {k} not exist in the config. Full key:{full_k}")
192
+ if i != len(keys) - 1:
193
+ sub_d = sub_d[k]
194
+ else:
195
+ sub_d[k] = v
196
+ return cfg
197
+
198
+
199
+ def merge_a_into_b(a, b, inplace=False):
200
+ """The values in a will override values in b.
201
+
202
+ Args:
203
+ a (dict): source dict.
204
+ b (dict): target dict.
205
+
206
+ Returns: dict. recursively merge dict a into dict b.
207
+
208
+ """
209
+ if not inplace:
210
+ b = deepcopy(b)
211
+ for key in a:
212
+ if key in b:
213
+ if isinstance(a[key], dict) and isinstance(b[key], dict):
214
+ b[key] = merge_a_into_b(a[key], b[key], inplace=True)
215
+ else:
216
+ b[key] = a[key]
217
+ else:
218
+ b[key] = a[key]
219
+ return b
220
+
221
+
222
+ def eval_dict_leaf(d, orig_dict=None):
223
+ """eval values of dict leaf.
224
+
225
+ Args:
226
+ d (dict): The dict to eval.
227
+
228
+ Returns: dict.
229
+
230
+ """
231
+ if orig_dict is None:
232
+ orig_dict = d
233
+ for k, v in d.items():
234
+ if not isinstance(v, dict):
235
+ d[k] = eval_string(v, orig_dict)
236
+ else:
237
+ eval_dict_leaf(v, orig_dict)
238
+ return d
239
+
240
+
241
+ def eval_string(string, d):
242
+ """automatically evaluate string to corresponding types.
243
+
244
+ For example:
245
+ not a string -> return the original input
246
+ '0' -> 0
247
+ '0.2' -> 0.2
248
+ '[0, 1, 2]' -> [0,1,2]
249
+ 'eval(1+2)' -> 3
250
+ 'eval(range(5))' -> [0,1,2,3,4]
251
+ '${a}' -> d.a
252
+
253
+
254
+
255
+ Args:
256
+ string (str): The value to evaluate.
257
+ d (dict): The
258
+
259
+ Returns: the corresponding type
260
+
261
+ """
262
+ if not isinstance(string, str):
263
+ return string
264
+ # if len(string) > 1 and string[0] == "[" and string[-1] == "]":
265
+ # return eval(string)
266
+ if string[0:5] == "eval(":
267
+ return eval(string[5:-1])
268
+
269
+ s0 = string
270
+ s1 = re.sub(r"\${(.*)}", r"d.\1", s0)
271
+ if s1 != s0:
272
+ while s1 != s0:
273
+ s0 = s1
274
+ s1 = re.sub(r"\${(.*)}", r"d.\1", s0)
275
+ return eval(s1)
276
+
277
+ try:
278
+ v = ast.literal_eval(string)
279
+ except:
280
+ v = string
281
+ return v
utils/easydict.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class EasyDict(dict):
2
+ """
3
+ Get attributes
4
+
5
+ >>> d = EasyDict({'foo':3})
6
+ >>> d['foo']
7
+ 3
8
+ >>> d.foo
9
+ 3
10
+ >>> d.bar
11
+ Traceback (most recent call last):
12
+ ...
13
+ AttributeError: 'EasyDict' object has no attribute 'bar'
14
+
15
+ Works recursively
16
+
17
+ >>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y':2}})
18
+ >>> isinstance(d.bar, dict)
19
+ True
20
+ >>> d.bar.x
21
+ 1
22
+
23
+ Bullet-proof
24
+
25
+ >>> EasyDict({})
26
+ {}
27
+ >>> EasyDict(d={})
28
+ {}
29
+ >>> EasyDict(None)
30
+ {}
31
+ >>> d = {'a': 1}
32
+ >>> EasyDict(**d)
33
+ {'a': 1}
34
+
35
+ Set attributes
36
+
37
+ >>> d = EasyDict()
38
+ >>> d.foo = 3
39
+ >>> d.foo
40
+ 3
41
+ >>> d.bar = {'prop': 'value'}
42
+ >>> d.bar.prop
43
+ 'value'
44
+ >>> d
45
+ {'foo': 3, 'bar': {'prop': 'value'}}
46
+ >>> d.bar.prop = 'newer'
47
+ >>> d.bar.prop
48
+ 'newer'
49
+
50
+
51
+ Values extraction
52
+
53
+ >>> d = EasyDict({'foo':0, 'bar':[{'x':1, 'y':2}, {'x':3, 'y':4}]})
54
+ >>> isinstance(d.bar, list)
55
+ True
56
+ >>> from operator import attrgetter
57
+ >>> map(attrgetter('x'), d.bar)
58
+ [1, 3]
59
+ >>> map(attrgetter('y'), d.bar)
60
+ [2, 4]
61
+ >>> d = EasyDict()
62
+ >>> d.keys()
63
+ []
64
+ >>> d = EasyDict(foo=3, bar=dict(x=1, y=2))
65
+ >>> d.foo
66
+ 3
67
+ >>> d.bar.x
68
+ 1
69
+
70
+ Still like a dict though
71
+
72
+ >>> o = EasyDict({'clean':True})
73
+ >>> o.items()
74
+ [('clean', True)]
75
+
76
+ And like a class
77
+
78
+ >>> class Flower(EasyDict):
79
+ ... power = 1
80
+ ...
81
+ >>> f = Flower()
82
+ >>> f.power
83
+ 1
84
+ >>> f = Flower({'height': 12})
85
+ >>> f.height
86
+ 12
87
+ >>> f['power']
88
+ 1
89
+ >>> sorted(f.keys())
90
+ ['height', 'power']
91
+
92
+ update and pop items
93
+ >>> d = EasyDict(a=1, b='2')
94
+ >>> e = EasyDict(c=3.0, a=9.0)
95
+ >>> d.update(e)
96
+ >>> d.c
97
+ 3.0
98
+ >>> d['c']
99
+ 3.0
100
+ >>> d.get('c')
101
+ 3.0
102
+ >>> d.update(a=4, b=4)
103
+ >>> d.b
104
+ 4
105
+ >>> d.pop('a')
106
+ 4
107
+ >>> d.a
108
+ Traceback (most recent call last):
109
+ ...
110
+ AttributeError: 'EasyDict' object has no attribute 'a'
111
+ """
112
+
113
+ def __init__(self, d=None, **kwargs):
114
+ if d is None:
115
+ d = {}
116
+ if kwargs:
117
+ d.update(**kwargs)
118
+ for k, v in d.items():
119
+ setattr(self, k, v)
120
+ # Class attributes
121
+ for k in self.__class__.__dict__.keys():
122
+ if not (k.startswith("__") and k.endswith("__")) and not k in ("update", "pop"):
123
+ setattr(self, k, getattr(self, k))
124
+
125
+ def __setattr__(self, name, value):
126
+ if isinstance(value, (list, tuple)):
127
+ value = [self.__class__(x) if isinstance(x, dict) else x for x in value]
128
+ elif isinstance(value, dict) and not isinstance(value, self.__class__):
129
+ value = self.__class__(value)
130
+ super(EasyDict, self).__setattr__(name, value)
131
+ super(EasyDict, self).__setitem__(name, value)
132
+
133
+ __setitem__ = __setattr__
134
+
135
+ def update(self, e=None, **f):
136
+ d = e or dict()
137
+ d.update(f)
138
+ for k in d:
139
+ setattr(self, k, d[k])
140
+
141
+ def pop(self, k, d=None):
142
+ if hasattr(self, k):
143
+ delattr(self, k)
144
+ return super(EasyDict, self).pop(k, d)
145
+
146
+
147
+ if __name__ == "__main__":
148
+ import doctest
149
+