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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<p align="center" width="100%">
|
2 |
+
<img src="assets/banner.png" width="100%" height="80%">
|
3 |
+
</p>
|
4 |
+
|
5 |
+
[![arXiv](https://img.shields.io/badge/arxiv-2406.xxxxx-b31b1b?style=plastic&color=b31b1b&link=https%3A%2F%2Farxiv.org%2Fabs%2F2406.xxxxx)](https://arxiv.org/abs/2406.xxxxx)
|
6 |
+
[![website](https://img.shields.io/badge/Project-Website-purple)](https://kxgong.github.io/meta_transformer/)
|
7 |
+
[![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/papers/2307.10802)
|
8 |
+
<a href="https://twitter.com/_akhaliq/status/1682248055637041152"><img src="https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social"></a>
|
9 |
+
<a href="https://www.youtube.com/watch?v=V8L8xbsTyls&ab_channel=CSBoard"><img src="https://img.icons8.com/color/48/000000/youtube-play.png" width="28" height="23"></a>
|
10 |
+
<a href="#LICENSE--citation">
|
11 |
+
<img alt="License: Apache2.0" src="https://img.shields.io/badge/LICENSE-Apache%202.0-blue.svg"/>
|
12 |
+
</a>
|
13 |
+
|
14 |
+
### Quick Use
|
15 |
+
|
16 |
+
```python
|
17 |
+
import os
|
18 |
+
import torch
|
19 |
+
import json
|
20 |
+
import argparse
|
21 |
+
from tqdm import tqdm
|
22 |
+
from collections import defaultdict
|
23 |
+
import torch.nn.functional as F
|
24 |
+
from time import time
|
25 |
+
from easydict import EasyDict as edict
|
26 |
+
|
27 |
+
from model.mico import *
|
28 |
+
|
29 |
+
|
30 |
+
def load_from_pretrained_dir(pretrain_dir, video_resolution=224, return_modal="full"):
|
31 |
+
|
32 |
+
checkpoint_dir = os.path.join(pretrain_dir,'ckpt')
|
33 |
+
file_cfg = edict(json.load(open(os.path.join(pretrain_dir,'log','hps.json'))))
|
34 |
+
model_cfg = file_cfg.model_cfg
|
35 |
+
checkpoint_ls = [ i for i in os.listdir(checkpoint_dir) if i.startswith('model_step')]
|
36 |
+
checkpoint_ls = [int(i.split('_')[2].split('.')[0]) for i in checkpoint_ls]
|
37 |
+
checkpoint_ls.sort()
|
38 |
+
step = checkpoint_ls[-1]
|
39 |
+
|
40 |
+
checkpoint_name = 'model_step_'+str(step)+'.pt'
|
41 |
+
ckpt_file = os.path.join(checkpoint_dir, checkpoint_name)
|
42 |
+
checkpoint = torch.load(ckpt_file, map_location = 'cpu')
|
43 |
+
print(f'load_from_pretrained: {ckpt_file}')
|
44 |
+
|
45 |
+
new_ckpt = {}
|
46 |
+
for k,v in checkpoint.items():
|
47 |
+
if 'video' in k:
|
48 |
+
new_ckpt[k.replace('video','vision')]=v
|
49 |
+
elif 'evaclip_model' in k:
|
50 |
+
new_ckpt[k.replace('evaclip_model','vision_encoder')]=v
|
51 |
+
elif 'clip_model' in k:
|
52 |
+
new_ckpt[k.replace('clip_model','vision_encoder')]=v
|
53 |
+
else:
|
54 |
+
new_ckpt[k] = v.float()
|
55 |
+
|
56 |
+
checkpoint = new_ckpt
|
57 |
+
|
58 |
+
if model_cfg.frame_embedding_type == 'adaptive':
|
59 |
+
|
60 |
+
if 'vision_frame_embedding' in checkpoint:
|
61 |
+
pretrain_embed = checkpoint['vision_frame_embedding']
|
62 |
+
if pretrain_embed.shape[1]!=model_cfg.max_vision_sample_num:
|
63 |
+
pretrain_embed = F.interpolate(pretrain_embed.permute(0,2,1),model_cfg.max_vision_sample_num,mode='nearest').permute(0,2,1)
|
64 |
+
checkpoint['vision_frame_embedding'] = pretrain_embed
|
65 |
+
else:
|
66 |
+
pretrain_embed = checkpoint['vision_perceiver.vision_frame_embedding']
|
67 |
+
if pretrain_embed.shape[1]!=model_cfg.max_vision_sample_num:
|
68 |
+
pretrain_embed = F.interpolate(pretrain_embed.permute(0,2,1),model_cfg.max_vision_sample_num,mode='nearest').permute(0,2,1)
|
69 |
+
checkpoint['vision_perceiver.vision_frame_embedding'] = pretrain_embed
|
70 |
+
|
71 |
+
if 'audio_frame_embedding' in checkpoint:
|
72 |
+
pretrain_embed_a = checkpoint['audio_frame_embedding']
|
73 |
+
if pretrain_embed_a.shape[1]!=model_cfg.max_audio_sample_num:
|
74 |
+
pretrain_embed_a = F.interpolate(pretrain_embed_a.permute(0,2,1),model_cfg.max_audio_sample_num,mode='nearest').permute(0,2,1)
|
75 |
+
checkpoint['audio_frame_embedding'] = pretrain_embed_a
|
76 |
+
|
77 |
+
if model_cfg.vision_encoder_type.startswith('clip'):
|
78 |
+
vision_width = checkpoint["vision_encoder.visual.positional_embedding"].shape[1]
|
79 |
+
vision_layers = len([k for k in checkpoint.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
80 |
+
vision_patch_size = checkpoint["vision_encoder.visual.conv1.weight"].shape[-1]
|
81 |
+
|
82 |
+
grid_size = round((checkpoint["vision_encoder.visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
83 |
+
|
84 |
+
src = checkpoint["vision_encoder.visual.positional_embedding"]
|
85 |
+
src_cls = src[0:1]
|
86 |
+
src_oth = src[1:]
|
87 |
+
new_grid_size = model_cfg.vision_resolution // vision_patch_size
|
88 |
+
if new_grid_size!=grid_size:
|
89 |
+
src_oth = F.interpolate(src_oth.reshape(grid_size,grid_size,vision_width).permute(2,0,1).unsqueeze(0),(new_grid_size,new_grid_size),mode='bilinear')
|
90 |
+
src_oth = src_oth[0].permute(1,2,0).reshape(-1,src.shape[-1])
|
91 |
+
tgt = torch.cat((src_cls,src_oth),dim=0)
|
92 |
+
checkpoint["vision_encoder.visual.positional_embedding"] = tgt
|
93 |
+
|
94 |
+
elif model_cfg.vision_encoder_type.startswith('evaclip'):
|
95 |
+
|
96 |
+
vision_width = checkpoint["vision_encoder.visual.pos_embed"].shape[2]
|
97 |
+
vision_layers = len([k for k in checkpoint.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
98 |
+
|
99 |
+
vision_patch_size = checkpoint["vision_encoder.visual.patch_embed.proj.weight"].shape[-1]
|
100 |
+
|
101 |
+
grid_size = round((checkpoint["vision_encoder.visual.pos_embed"].shape[1] - 1) ** 0.5)
|
102 |
+
|
103 |
+
src = checkpoint["vision_encoder.visual.pos_embed"][0]
|
104 |
+
src_cls = src[0:1]
|
105 |
+
src_oth = src[1:]
|
106 |
+
new_grid_size = model_cfg.vision_resolution // vision_patch_size
|
107 |
+
if new_grid_size!=grid_size:
|
108 |
+
src_oth = F.interpolate(src_oth.reshape(grid_size,grid_size,vision_width).permute(2,0,1).unsqueeze(0),(new_grid_size,new_grid_size),mode='bilinear')
|
109 |
+
src_oth = src_oth[0].permute(1,2,0).reshape(-1,src.shape[-1])
|
110 |
+
tgt = torch.cat((src_cls,src_oth),dim=0)
|
111 |
+
checkpoint["vision_encoder.visual.pos_embed"] = tgt.unsqueeze(0)
|
112 |
+
else:
|
113 |
+
pass
|
114 |
+
|
115 |
+
if return_modal=="full":
|
116 |
+
new_ckpt = checkpoint
|
117 |
+
elif return_modal=="uni":
|
118 |
+
new_ckpt = defaultdict()
|
119 |
+
for k in checkpoint.keys():
|
120 |
+
if "video_encoder" in k:
|
121 |
+
new_k = ".".join(k.split(".")[1:])
|
122 |
+
new_ckpt[new_k] = checkpoint[k]
|
123 |
+
elif return_modal=="text":
|
124 |
+
new_ckpt = defaultdict()
|
125 |
+
for k in checkpoint.keys():
|
126 |
+
if "multimodal_encoder" in k:
|
127 |
+
new_k = ".".join(k.split(".")[1:])
|
128 |
+
new_ckpt[new_k] = checkpoint[k]
|
129 |
+
else:
|
130 |
+
pass
|
131 |
+
|
132 |
+
return new_ckpt, model_cfg
|
133 |
+
|
134 |
+
|
135 |
+
if __name__ == "__main__":
|
136 |
+
# import ipdb
|
137 |
+
# ipdb.set_trace()
|
138 |
+
device = "cuda"
|
139 |
+
from model.imageprocessor import ImageProcessor
|
140 |
+
pretrain_path = 'MiCo-g' # please check your
|
141 |
+
checkpoint, opts = load_from_pretrained_dir("MiCo-g", video_resolution=224, return_modal="full")
|
142 |
+
model = MiCo.from_pretrained(opts,checkpoint).to(device)
|
143 |
+
image_file = "example/test.jpeg"
|
144 |
+
proc = ImageProcessor(image_resolution=224, image_encoder_type="swin", training=True)
|
145 |
+
image_input = proc(image_file).to(device)
|
146 |
+
image_input = image_input.unsqueeze(1) # image as a 1 frame video
|
147 |
+
|
148 |
+
video_output = model.forward_vision_encoder(image_input)
|
149 |
+
video_output_pooled = model.pool_vision_for_contra(video_output)
|
150 |
+
feat_v = model.contra_head_v(video_output_pooled)
|
151 |
+
feat_v = F.normalize(feat_v,dim=-1)
|
152 |
+
|
153 |
+
texts = ["a man is skiing in a snowy day.", "it's a hot day"]
|
154 |
+
caption_tokens = model.multimodal_encoder.tokenizer(texts,
|
155 |
+
padding="max_length",
|
156 |
+
truncation=True,
|
157 |
+
max_length=30,
|
158 |
+
return_tensors="pt")
|
159 |
+
caption_tokens = caption_tokens.to(torch.device('cuda'))
|
160 |
+
input_ids = caption_tokens.input_ids
|
161 |
+
attention_mask = caption_tokens.attention_mask
|
162 |
+
caption_output = model.forward_multimodal_encoder(input_ids, attention_mask).sequence_output
|
163 |
+
caption_output_pooled = model.pool_text_for_contra(caption_output)
|
164 |
+
feat_t = model.contra_head_t(caption_output_pooled)
|
165 |
+
feat_t = F.normalize(feat_t,dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
sim_t2v = torch.matmul(feat_t, feat_v.permute(1,0))
|
169 |
+
print(sim_t2v)
|
170 |
+
|
171 |
+
video_input = model.get_multimodal_forward_input_vision(video_output)
|
172 |
+
slice_output = model.forward_multimodal_encoder(input_ids, attention_mask, video_input).sequence_output
|
173 |
+
slice_scores = F.softmax(model.itm_head(slice_output[:,0]),dim=1)[:,1]
|
174 |
+
print(slice_scores)
|
175 |
+
|
176 |
+
|
177 |
+
video_input = model.get_multimodal_forward_input_vision(video_output)
|
178 |
+
init_input_ids = torch.ones(video_input.size(0), 1).long().cuda().fill_(model.multimodal_encoder.tokenizer.bos_token_id)
|
179 |
+
init_attention_mask = init_input_ids.new_ones(video_input.size(0), 1, 1)
|
180 |
+
outputs = model.multimodal_encoder.generate(input_ids=init_input_ids,
|
181 |
+
attention_mask=init_attention_mask,
|
182 |
+
encoder_hidden_states=video_input,
|
183 |
+
max_new_tokens=model.max_caption_len,
|
184 |
+
num_beams=model.beam_size,
|
185 |
+
eos_token_id=model.multimodal_encoder.tokenizer.sep_token_id,
|
186 |
+
pad_token_id=model.multimodal_encoder.tokenizer.pad_token_id,
|
187 |
+
length_penalty=0.6)
|
188 |
+
outputs_newgen = outputs[:,1:]
|
189 |
+
captions = model.multimodal_encoder.tokenizer.batch_decode(outputs_newgen, skip_special_tokens=True)
|
190 |
+
print(captions)
|
191 |
+
```
|
192 |
+
|
193 |
+
### ✨ Inspiration of Multimodal Context: Multimedia Brain Cognition
|
194 |
+
|
195 |
+
<p align="center" width="100%">
|
196 |
+
<img src="assets/brain.png" width="100%" height="60%">
|
197 |
+
</p>
|
198 |
+
|
199 |
+
***How the human brain performs coherent multimodal cognition?***
|
200 |
+
|
201 |
+
As outlined in Richard Mayer's Cognitive Theory of Multimedia Learning,our brain processes multimedia signals through two distinct channels—auditory and visual—in sensory memory, as depicted in Figure(a). The sensory memory integrates these signals with prior knowledge through words, transforming new multimedia information into long-term memory. Notably, **1**) multimedia signals in the brain share channels, and **2**) words function as the reasoning interface in our brain.
|
202 |
+
|
203 |
+
Inspired by these insights, we categorize diverse modalities into two types: ``knowledge modality`` and ``interface modality``. *Knowledge modalities*, primarily derived from raw sensors, contribute knowledge in diverse formats. For example, images and depth maps offer visual knowledge, while audio and video provide auditory and spatiotemporal knowledge. The language modality, developed by humans, is inherently more abstract and naturally functions as the *interface modality*, facilitating learning, reasoning, and the coordination of knowledge. To this end, we design an omni-modal learning architecture, illustrated in Figure (b), with two distinct branches: one for knowledge modalities and one for the interface modality, *i.e.* natural language. The knowledge and interface modalities are aligned through a novel generative reasoning method.
|
204 |
+
|
205 |
+
### 🚀 MiCo, An omni-modal and scalable pretraining paradigm
|
206 |
+
|
207 |
+
<p align="center" width="100%">
|
208 |
+
<img src="assets/omnimodal_pretraining.png" width="100%" height="60%">
|
209 |
+
</p>
|
210 |
+
|
211 |
+
We propose collecting large-scale omni-modal paired data, including text,
|
212 |
+
image, video, depth, and normal maps, to learn universal representations.
|
213 |
+
|
214 |
+
<p align="center" width="100%">
|
215 |
+
<img src="assets/paradigm.png" width="100%" height="60%">
|
216 |
+
</p>
|
217 |
+
|
218 |
+
**🚀 Evolution of Pretraining Paradigms**. Masked modeling (a) has shown great success in single modality, general-purpose understanding. Contrastive learning (b) distinguishes transferable features with modality tuples (such as text-image, text-video, text-audio, etc).
|
219 |
+
|
220 |
+
*🚀🚀🚀 We aim to achieve general-purpose omni-modal understanding and learn transferable, universal representations in (c).*
|
221 |
+
|
222 |
+
### 🌟🌟🌟 The Multimodal Scaling Laws with MiCo: Modalities Help Modalies!
|
223 |
+
|
224 |
+
<p align="center" width="100%">
|
225 |
+
<img src="assets/scaling_laws.png" width="100%" height="60%">
|
226 |
+
</p>
|
227 |
+
|
228 |
+
### 🔓 Pretrained Omni-Modal Models
|
229 |
+
<!-- <details> -->
|
230 |
+
**We will continue to update this model zoo including all scales of ViTs and highly-efficient ConvNets with the MiCo pretraining paradigm**
|
231 |
+
|
232 |
+
<summary> Current Checkpoints </summary>
|
233 |
+
<br>
|
234 |
+
<div>
|
235 |
+
|
236 |
+
| Model | Pretraining | Scale | Modality | #Param | Google Drive | Hugging Face
|
237 |
+
| :------------: | :----------: | :----------------------: | :----: | :---------------------------------------------------------------------------------------------------: |:----: | :----: |
|
238 |
+
| MiCo | 300k steps | ViT-g | Omni-modal | 1.3B | [ckpt](https://drive.google.com/drive/folders/1AIQjV1KU8K4OXiO-4gFirxkoxt3twWIq?usp=sharing) | [ckpt](https://huggingface.co/Yiyuan/MiCo-ViT-g-14-omnimodal-300k-b64K)
|
239 |
+
|
240 |
+
|
241 |
+
</div>
|
242 |
+
|
243 |
+
### 🔓 Omni-Modal Dataset Collection
|
244 |
+
|
245 |
+
We provdie a detailed [doc](data/README.md) for preparing the omni-modal dataset step-by-step
|
246 |
+
|
247 |
+
### ⚡ Quick Start
|
248 |
+
|
249 |
+
1. Download MiCo weights
|
250 |
+
```bash
|
251 |
+
pip install gdown
|
252 |
+
gdown 1AIQjV1KU8K4OXiO-4gFirxkoxt3twWIq --folder
|
253 |
+
python inference_demo.py
|
254 |
+
```
|
255 |
+
# Citation
|
256 |
+
If the code and paper help your research, please kindly cite:
|
257 |
+
```
|
258 |
+
@article{zhang2024explore,
|
259 |
+
title={Explore the Limits of Omni-modal Pretraining at Scale},
|
260 |
+
author={Zhang, Yiyuan and Li, Handong and Liu, Jing and Yue, Xiangyu},
|
261 |
+
journal={arXiv preprint arXiv:2406.xxxxx},
|
262 |
+
year={2024}
|
263 |
+
}
|
264 |
+
```
|
265 |
+
# License
|
266 |
+
This project is released under the [Apache 2.0 license](LICENSE).
|
267 |
+
# Acknowledgement
|
268 |
+
We appreciate [Dr. Xiaohan Ding](https://dingxiaohan.xyz/) for the valuable discussion and suggestions.This code is developed based [Meta-Transformer](https://github.com/invictus717/MetaTransformer), [VAST](https://github.com/TXH-mercury/VAST), [DPT](https://github.com/EPFL-VILAB/omnidata), and [GeoWizard](https://github.com/fuxiao0719/GeoWizard).
|