FantasticGu commited on
Commit
a73717c
1 Parent(s): 7fbdd01

initial commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +0 -13
  2. app.py +248 -0
  3. ckpt/train_supervised/pytorch_model.pt +3 -0
  4. ffffff.png +0 -0
  5. header.py +35 -0
  6. model/AnomalyGPT_models.py +73 -0
  7. model/ImageBind/CODE_OF_CONDUCT.md +80 -0
  8. model/ImageBind/CONTRIBUTING.md +31 -0
  9. model/ImageBind/LICENSE +437 -0
  10. model/ImageBind/README.md +155 -0
  11. model/ImageBind/__init__.py +2 -0
  12. model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz +3 -0
  13. model/ImageBind/data.py +399 -0
  14. model/ImageBind/model_card.md +94 -0
  15. model/ImageBind/models/__init__.py +0 -0
  16. model/ImageBind/models/__pycache__/__init__.cpython-38.pyc +0 -0
  17. model/ImageBind/models/__pycache__/helpers.cpython-38.pyc +0 -0
  18. model/ImageBind/models/__pycache__/imagebind_model.cpython-38.pyc +0 -0
  19. model/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-38.pyc +0 -0
  20. model/ImageBind/models/__pycache__/transformer.cpython-38.pyc +0 -0
  21. model/ImageBind/models/helpers.py +139 -0
  22. model/ImageBind/models/imagebind_model.py +527 -0
  23. model/ImageBind/models/multimodal_preprocessors.py +685 -0
  24. model/ImageBind/models/transformer.py +287 -0
  25. model/ImageBind/requirements.txt +10 -0
  26. model/__init__.py +11 -0
  27. model/agent.py +81 -0
  28. model/modeling_llama.py +755 -0
  29. model/openllama.py +729 -0
  30. pretrained_ckpt/imagebind_ckpt/imagebind_huge.pth +3 -0
  31. pretrained_ckpt/pandagpt_ckpt/13b/empty.txt +1 -0
  32. pretrained_ckpt/pandagpt_ckpt/7b/empty.txt +1 -0
  33. pretrained_ckpt/pandagpt_ckpt/7b/pytorch_model.pt +3 -0
  34. pretrained_ckpt/vicuna_ckpt/13b_v0/empty.txt +1 -0
  35. pretrained_ckpt/vicuna_ckpt/7b_v0/config.json +23 -0
  36. pretrained_ckpt/vicuna_ckpt/7b_v0/generation_config.json +7 -0
  37. pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model-00001-of-00002.bin +3 -0
  38. pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model-00002-of-00002.bin +3 -0
  39. pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model.bin.index.json +330 -0
  40. pretrained_ckpt/vicuna_ckpt/7b_v0/special_tokens_map.json +23 -0
  41. pretrained_ckpt/vicuna_ckpt/7b_v0/tokenizer.model +3 -0
  42. pretrained_ckpt/vicuna_ckpt/7b_v0/tokenizer_config.json +33 -0
  43. requirements.txt +25 -0
  44. utils/__init__.py +0 -0
  45. utils/__pycache__/__init__.cpython-38.pyc +0 -0
  46. utils/__pycache__/loss.cpython-38.pyc +0 -0
  47. utils/build.py +17 -0
  48. utils/config.py +63 -0
  49. utils/data_transform.py +339 -0
  50. utils/io.py +42 -0
README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: AnomalyGPT
3
- emoji: 📉
4
- colorFrom: red
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.41.2
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import mdtex2html
3
+ from model.openllama import OpenLLAMAPEFTModel
4
+ import torch
5
+ from io import BytesIO
6
+ from PIL import Image as PILImage
7
+ import cv2
8
+ import numpy as np
9
+ from matplotlib import pyplot as plt
10
+ from torchvision import transforms
11
+
12
+ # init the model
13
+ args = {
14
+ 'model': 'openllama_peft',
15
+ 'imagebind_ckpt_path': './pretrained_ckpt/imagebind_ckpt/imagebind_huge.pth',
16
+ 'vicuna_ckpt_path': './pretrained_ckpt/vicuna_ckpt/7b_v0',
17
+ 'anomalygpt_ckpt_path': './ckpt/train_cn/pytorch_model.pt',
18
+ 'delta_ckpt_path': './pretrained_ckpt/pandagpt_ckpt/7b/pytorch_model.pt',
19
+ 'stage': 2,
20
+ 'max_tgt_len': 128,
21
+ 'lora_r': 32,
22
+ 'lora_alpha': 32,
23
+ 'lora_dropout': 0.1,
24
+ 'layers': [7,15,23,31]
25
+ }
26
+
27
+ model = OpenLLAMAPEFTModel(**args)
28
+ delta_ckpt = torch.load(args['delta_ckpt_path'], map_location=torch.device('cpu'))
29
+ model.load_state_dict(delta_ckpt, strict=False)
30
+ delta_ckpt = torch.load(args['anomalygpt_ckpt_path'], map_location=torch.device('cpu'))
31
+ model.load_state_dict(delta_ckpt, strict=False)
32
+ model = model.eval()
33
+
34
+
35
+ output = None
36
+
37
+ """Override Chatbot.postprocess"""
38
+ def postprocess(self, y):
39
+ if y is None:
40
+ return []
41
+ for i, (message, response) in enumerate(y):
42
+ y[i] = (
43
+ None if message is None else mdtex2html.convert((message)),
44
+ None if response is None else mdtex2html.convert(response),
45
+ )
46
+ return y
47
+
48
+
49
+ gr.Chatbot.postprocess = postprocess
50
+
51
+
52
+ def parse_text(text):
53
+ """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
54
+ lines = text.split("\n")
55
+ lines = [line for line in lines if line != ""]
56
+ count = 0
57
+ for i, line in enumerate(lines):
58
+ if "```" in line:
59
+ count += 1
60
+ items = line.split('`')
61
+ if count % 2 == 1:
62
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
63
+ else:
64
+ lines[i] = f'<br></code></pre>'
65
+ else:
66
+ if i > 0:
67
+ if count % 2 == 1:
68
+ line = line.replace("`", "\`")
69
+ line = line.replace("<", "&lt;")
70
+ line = line.replace(">", "&gt;")
71
+ line = line.replace(" ", "&nbsp;")
72
+ line = line.replace("*", "&ast;")
73
+ line = line.replace("_", "&lowbar;")
74
+ line = line.replace("-", "&#45;")
75
+ line = line.replace(".", "&#46;")
76
+ line = line.replace("!", "&#33;")
77
+ line = line.replace("(", "&#40;")
78
+ line = line.replace(")", "&#41;")
79
+ line = line.replace("$", "&#36;")
80
+ lines[i] = "<br>"+line
81
+ text = "".join(lines)
82
+ return text
83
+
84
+
85
+ def predict(
86
+ input,
87
+ image_path,
88
+ normal_img_path,
89
+ chatbot,
90
+ max_length,
91
+ top_p,
92
+ temperature,
93
+ history,
94
+ modality_cache,
95
+ ):
96
+
97
+ if image_path is None and normal_img_path is None:
98
+ return [(input, "There is no input data provided! Please upload your data and start the conversation.")]
99
+ else:
100
+ print(f'[!] image path: {image_path}\n[!] normal image path: {normal_img_path}\n')
101
+
102
+ # prepare the prompt
103
+ prompt_text = ''
104
+ for idx, (q, a) in enumerate(history):
105
+ if idx == 0:
106
+ prompt_text += f'{q}\n### Assistant: {a}\n###'
107
+ else:
108
+ prompt_text += f' Human: {q}\n### Assistant: {a}\n###'
109
+ if len(history) == 0:
110
+ prompt_text += f'{input}'
111
+ else:
112
+ prompt_text += f' Human: {input}'
113
+
114
+ response, pixel_output = model.generate({
115
+ 'prompt': prompt_text,
116
+ 'image_paths': [image_path] if image_path else [],
117
+ 'normal_img_paths': [normal_img_path] if normal_img_path else [],
118
+ 'audio_paths': [],
119
+ 'video_paths': [],
120
+ 'thermal_paths': [],
121
+ 'top_p': top_p,
122
+ 'temperature': temperature,
123
+ 'max_tgt_len': max_length,
124
+ 'modality_embeds': modality_cache
125
+ },web_demo=True)
126
+ chatbot.append((parse_text(input), parse_text(response)))
127
+ history.append((input, response))
128
+
129
+
130
+ plt.imshow(pixel_output.reshape(224,224).detach().cpu(), cmap='binary_r')
131
+ plt.axis('off')
132
+ plt.savefig('output.png',bbox_inches='tight',pad_inches = 0)
133
+
134
+ target_size = 224
135
+ original_width, original_height = PILImage.open(image_path).size
136
+ if original_width > original_height:
137
+ new_width = target_size
138
+ new_height = int(target_size * (original_height / original_width))
139
+ else:
140
+ new_height = target_size
141
+ new_width = int(target_size * (original_width / original_height))
142
+
143
+ new_image = PILImage.new('L', (target_size, target_size), 255) # 'L' mode for grayscale
144
+
145
+ paste_x = (target_size - new_width) // 2
146
+ paste_y = (target_size - new_height) // 2
147
+
148
+ pixel_output = PILImage.open('output.png').resize((new_width, new_height), PILImage.LANCZOS)
149
+
150
+ new_image.paste(pixel_output, (paste_x, paste_y))
151
+
152
+ new_image.save('output.png')
153
+
154
+ image = cv2.imread('output.png', cv2.IMREAD_GRAYSCALE)
155
+ kernel = np.ones((3, 3), np.uint8)
156
+ eroded_image = cv2.erode(image, kernel, iterations=1)
157
+ cv2.imwrite('output.png', eroded_image)
158
+
159
+ global output
160
+ output = PILImage.open('output.png').convert('L')
161
+
162
+
163
+ return chatbot, history, modality_cache
164
+
165
+
166
+ def get_image():
167
+ global output
168
+ return output if output else "ffffff.png"
169
+
170
+
171
+ def reset_user_input():
172
+ return gr.update(value='')
173
+
174
+ def reset_dialog():
175
+ return [], []
176
+
177
+ def reset_state():
178
+ global output
179
+ output = None
180
+ return None, None, [], [], []
181
+
182
+
183
+
184
+ with gr.Blocks() as demo:
185
+ gr.HTML("""<h1 align="center">Demo of AnomalyGPT</h1>""")
186
+
187
+ with gr.Row():
188
+ with gr.Column(scale=1):
189
+ with gr.Row(scale=3):
190
+ image_path = gr.Image(type="filepath", label="Query Image", value=None)
191
+ with gr.Row(scale=3):
192
+ normal_img_path = gr.Image(type="filepath", label="Normal Image", value=None)
193
+ with gr.Row():
194
+ max_length = gr.Slider(0, 512, value=512, step=1.0, label="Maximum length", interactive=True)
195
+ with gr.Row():
196
+ top_p = gr.Slider(0, 1, value=0.01, step=0.01, label="Top P", interactive=True)
197
+ with gr.Row():
198
+ temperature = gr.Slider(0, 1, value=1.0, step=0.01, label="Temperature", interactive=True)
199
+
200
+
201
+ with gr.Column(scale=3):
202
+ with gr.Row():
203
+ with gr.Column(scale=6):
204
+ chatbot = gr.Chatbot().style(height=415)
205
+ with gr.Column(scale=4):
206
+ # gr.Image(output)
207
+ image_output = gr.Image(value=get_image, label="Localization Output", every=1.0, shape=[224,224])
208
+ with gr.Row():
209
+ user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(container=False)
210
+ with gr.Row():
211
+ with gr.Column(scale=2):
212
+ submitBtn = gr.Button("Submit", variant="primary")
213
+ with gr.Column(scale=1):
214
+ emptyBtn = gr.Button("Clear History")
215
+
216
+ history = gr.State([])
217
+ modality_cache = gr.State([])
218
+
219
+ submitBtn.click(
220
+ predict, [
221
+ user_input,
222
+ image_path,
223
+ normal_img_path,
224
+ chatbot,
225
+ max_length,
226
+ top_p,
227
+ temperature,
228
+ history,
229
+ modality_cache,
230
+ ], [
231
+ chatbot,
232
+ history,
233
+ modality_cache
234
+ ],
235
+ show_progress=True
236
+ )
237
+
238
+ submitBtn.click(reset_user_input, [], [user_input])
239
+ emptyBtn.click(reset_state, outputs=[
240
+ image_path,
241
+ normal_img_path,
242
+ chatbot,
243
+ history,
244
+ modality_cache
245
+ ], show_progress=True)
246
+
247
+
248
+ demo.queue().launch(server_port=24008)
ckpt/train_supervised/pytorch_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe107480518bd77d5f02fb95ce759e010d4236bee23da74c9a1f056dc1f316de
3
+ size 225330109
ffffff.png ADDED
header.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import datetime
3
+ import types
4
+ import deepspeed
5
+ from transformers.deepspeed import HfDeepSpeedConfig
6
+ import transformers
7
+ import numpy as np
8
+ from collections import OrderedDict
9
+ from torch.utils.data import Dataset, DataLoader
10
+ from torch.nn.utils import clip_grad_norm_
11
+ from torch.cuda.amp import autocast, GradScaler
12
+ from torch.nn import DataParallel
13
+ from torch.optim import lr_scheduler
14
+ import torch.optim as optim
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ from tqdm import tqdm
18
+ import os
19
+ import re
20
+ import math
21
+ import random
22
+ import json
23
+ import time
24
+ import logging
25
+ from copy import deepcopy
26
+ import ipdb
27
+ import argparse
28
+ import data
29
+ from transformers import LlamaTokenizer, LlamaForCausalLM, LlamaConfig
30
+ from torch.nn.utils.rnn import pad_sequence
31
+ from peft import LoraConfig, TaskType, get_peft_model
32
+
33
+ logging.getLogger("transformers").setLevel(logging.WARNING)
34
+ logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)
35
+ os.environ['TOKENIZERS_PARALLELISM'] = 'false'
model/AnomalyGPT_models.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import numpy as np
4
+ # from datas.dataset_3d import *
5
+ from torch.nn import functional as F
6
+
7
+
8
+ class Normalize(nn.Module):
9
+ def __init__(self, dim: int) -> None:
10
+ super().__init__()
11
+ self.dim = dim
12
+
13
+ def forward(self, x):
14
+ return torch.nn.functional.normalize(x, dim=self.dim, p=2)
15
+
16
+
17
+ class LinearLayer(nn.Module):
18
+ def __init__(self, dim_in, dim_out, k):
19
+ super(LinearLayer, self).__init__()
20
+ self.fc = nn.ModuleList([nn.Linear(dim_in, dim_out) for i in range(k)])
21
+
22
+ def forward(self, tokens):
23
+ for i in range(len(tokens)):
24
+ if len(tokens[i].shape) == 3:
25
+ tokens[i] = tokens[i].transpose(0,1)
26
+ tokens[i] = self.fc[i](tokens[i][:, 1:, :])
27
+ else:
28
+ B, C, H, W = tokens[i].shape
29
+ tokens[i] = self.fc[i](tokens[i].view(B, C, -1).permute(0, 2, 1).contiguous())
30
+ return tokens
31
+
32
+ class PromptLearner(nn.Module):
33
+ def __init__(self, dim_in, dim_out) -> None:
34
+ super().__init__()
35
+ self.meta_net = nn.Sequential(
36
+ nn.Conv2d(dim_in, dim_in * 4, kernel_size=3, padding=1),
37
+ # nn.BatchNorm2d(dim_in * 4),
38
+ nn.ReLU(inplace=True),
39
+ nn.MaxPool2d(2), # 112 * 112
40
+
41
+ nn.Conv2d(dim_in * 4, dim_in * 16, kernel_size=3, padding=1),
42
+ # nn.BatchNorm2d(dim_in * 16),
43
+ nn.ReLU(inplace=True),
44
+ nn.MaxPool2d(2), # 56 * 56
45
+
46
+ nn.Conv2d(dim_in * 16, dim_in * 64, kernel_size=3, padding=1),
47
+ # nn.BatchNorm2d(dim_in * 64),
48
+ nn.ReLU(inplace=True),
49
+ nn.MaxPool2d(2), # 28 * 28
50
+
51
+ nn.Conv2d(dim_in * 64, dim_in * 256, kernel_size=3, padding=1),
52
+ # nn.BatchNorm2d(dim_in * 256),
53
+ nn.ReLU(inplace=True),
54
+ nn.MaxPool2d(2), # 14 * 14
55
+
56
+ nn.Conv2d(dim_in * 256, dim_in * 1024, kernel_size=3, padding=1),
57
+ # nn.BatchNorm2d(dim_in * 1024),
58
+ nn.ReLU(inplace=True),
59
+ nn.MaxPool2d(2), # 7 * 7
60
+
61
+ nn.Conv2d(dim_in * 1024, dim_out, kernel_size=5, padding=0),
62
+ # nn.BatchNorm2d(dim_out),
63
+ # nn.ReLU(inplace=True),
64
+ )
65
+ self.base_prompts = nn.Parameter(torch.randn((9, dim_out)),requires_grad=True)
66
+
67
+ def forward(self, input):
68
+ B,C,H,W = input.shape
69
+ img_prompts = self.meta_net(input)
70
+ # print(input.shape, img_prompts.shape)
71
+ img_prompts = img_prompts.reshape(B,4096,9).transpose(-2,-1)
72
+ output = torch.cat([self.base_prompts.expand(B,-1,-1), img_prompts], dim=1)
73
+ return output
model/ImageBind/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@fb.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
model/ImageBind/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ImageBind
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Meta's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to Omnivore, you agree that your contributions will be licensed
31
+ under the [LICENSE](LICENSE) file in the root directory of this source tree.
model/ImageBind/LICENSE ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial-ShareAlike 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58
+ Public License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial-ShareAlike 4.0 International Public License
63
+ ("Public License"). To the extent this Public License may be
64
+ interpreted as a contract, You are granted the Licensed Rights in
65
+ consideration of Your acceptance of these terms and conditions, and the
66
+ Licensor grants You such rights in consideration of benefits the
67
+ Licensor receives from making the Licensed Material available under
68
+ these terms and conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. BY-NC-SA Compatible License means a license listed at
88
+ creativecommons.org/compatiblelicenses, approved by Creative
89
+ Commons as essentially the equivalent of this Public License.
90
+
91
+ d. Copyright and Similar Rights means copyright and/or similar rights
92
+ closely related to copyright including, without limitation,
93
+ performance, broadcast, sound recording, and Sui Generis Database
94
+ Rights, without regard to how the rights are labeled or
95
+ categorized. For purposes of this Public License, the rights
96
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
97
+ Rights.
98
+
99
+ e. Effective Technological Measures means those measures that, in the
100
+ absence of proper authority, may not be circumvented under laws
101
+ fulfilling obligations under Article 11 of the WIPO Copyright
102
+ Treaty adopted on December 20, 1996, and/or similar international
103
+ agreements.
104
+
105
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
106
+ any other exception or limitation to Copyright and Similar Rights
107
+ that applies to Your use of the Licensed Material.
108
+
109
+ g. License Elements means the license attributes listed in the name
110
+ of a Creative Commons Public License. The License Elements of this
111
+ Public License are Attribution, NonCommercial, and ShareAlike.
112
+
113
+ h. Licensed Material means the artistic or literary work, database,
114
+ or other material to which the Licensor applied this Public
115
+ License.
116
+
117
+ i. Licensed Rights means the rights granted to You subject to the
118
+ terms and conditions of this Public License, which are limited to
119
+ all Copyright and Similar Rights that apply to Your use of the
120
+ Licensed Material and that the Licensor has authority to license.
121
+
122
+ j. Licensor means the individual(s) or entity(ies) granting rights
123
+ under this Public License.
124
+
125
+ k. NonCommercial means not primarily intended for or directed towards
126
+ commercial advantage or monetary compensation. For purposes of
127
+ this Public License, the exchange of the Licensed Material for
128
+ other material subject to Copyright and Similar Rights by digital
129
+ file-sharing or similar means is NonCommercial provided there is
130
+ no payment of monetary compensation in connection with the
131
+ exchange.
132
+
133
+ l. Share means to provide material to the public by any means or
134
+ process that requires permission under the Licensed Rights, such
135
+ as reproduction, public display, public performance, distribution,
136
+ dissemination, communication, or importation, and to make material
137
+ available to the public including in ways that members of the
138
+ public may access the material from a place and at a time
139
+ individually chosen by them.
140
+
141
+ m. Sui Generis Database Rights means rights other than copyright
142
+ resulting from Directive 96/9/EC of the European Parliament and of
143
+ the Council of 11 March 1996 on the legal protection of databases,
144
+ as amended and/or succeeded, as well as other essentially
145
+ equivalent rights anywhere in the world.
146
+
147
+ n. You means the individual or entity exercising the Licensed Rights
148
+ under this Public License. Your has a corresponding meaning.
149
+
150
+
151
+ Section 2 -- Scope.
152
+
153
+ a. License grant.
154
+
155
+ 1. Subject to the terms and conditions of this Public License,
156
+ the Licensor hereby grants You a worldwide, royalty-free,
157
+ non-sublicensable, non-exclusive, irrevocable license to
158
+ exercise the Licensed Rights in the Licensed Material to:
159
+
160
+ a. reproduce and Share the Licensed Material, in whole or
161
+ in part, for NonCommercial purposes only; and
162
+
163
+ b. produce, reproduce, and Share Adapted Material for
164
+ NonCommercial purposes only.
165
+
166
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
167
+ Exceptions and Limitations apply to Your use, this Public
168
+ License does not apply, and You do not need to comply with
169
+ its terms and conditions.
170
+
171
+ 3. Term. The term of this Public License is specified in Section
172
+ 6(a).
173
+
174
+ 4. Media and formats; technical modifications allowed. The
175
+ Licensor authorizes You to exercise the Licensed Rights in
176
+ all media and formats whether now known or hereafter created,
177
+ and to make technical modifications necessary to do so. The
178
+ Licensor waives and/or agrees not to assert any right or
179
+ authority to forbid You from making technical modifications
180
+ necessary to exercise the Licensed Rights, including
181
+ technical modifications necessary to circumvent Effective
182
+ Technological Measures. For purposes of this Public License,
183
+ simply making modifications authorized by this Section 2(a)
184
+ (4) never produces Adapted Material.
185
+
186
+ 5. Downstream recipients.
187
+
188
+ a. Offer from the Licensor -- Licensed Material. Every
189
+ recipient of the Licensed Material automatically
190
+ receives an offer from the Licensor to exercise the
191
+ Licensed Rights under the terms and conditions of this
192
+ Public License.
193
+
194
+ b. Additional offer from the Licensor -- Adapted Material.
195
+ Every recipient of Adapted Material from You
196
+ automatically receives an offer from the Licensor to
197
+ exercise the Licensed Rights in the Adapted Material
198
+ under the conditions of the Adapter's License You apply.
199
+
200
+ c. No downstream restrictions. You may not offer or impose
201
+ any additional or different terms or conditions on, or
202
+ apply any Effective Technological Measures to, the
203
+ Licensed Material if doing so restricts exercise of the
204
+ Licensed Rights by any recipient of the Licensed
205
+ Material.
206
+
207
+ 6. No endorsement. Nothing in this Public License constitutes or
208
+ may be construed as permission to assert or imply that You
209
+ are, or that Your use of the Licensed Material is, connected
210
+ with, or sponsored, endorsed, or granted official status by,
211
+ the Licensor or others designated to receive attribution as
212
+ provided in Section 3(a)(1)(A)(i).
213
+
214
+ b. Other rights.
215
+
216
+ 1. Moral rights, such as the right of integrity, are not
217
+ licensed under this Public License, nor are publicity,
218
+ privacy, and/or other similar personality rights; however, to
219
+ the extent possible, the Licensor waives and/or agrees not to
220
+ assert any such rights held by the Licensor to the limited
221
+ extent necessary to allow You to exercise the Licensed
222
+ Rights, but not otherwise.
223
+
224
+ 2. Patent and trademark rights are not licensed under this
225
+ Public License.
226
+
227
+ 3. To the extent possible, the Licensor waives any right to
228
+ collect royalties from You for the exercise of the Licensed
229
+ Rights, whether directly or through a collecting society
230
+ under any voluntary or waivable statutory or compulsory
231
+ licensing scheme. In all other cases the Licensor expressly
232
+ reserves any right to collect such royalties, including when
233
+ the Licensed Material is used other than for NonCommercial
234
+ purposes.
235
+
236
+
237
+ Section 3 -- License Conditions.
238
+
239
+ Your exercise of the Licensed Rights is expressly made subject to the
240
+ following conditions.
241
+
242
+ a. Attribution.
243
+
244
+ 1. If You Share the Licensed Material (including in modified
245
+ form), You must:
246
+
247
+ a. retain the following if it is supplied by the Licensor
248
+ with the Licensed Material:
249
+
250
+ i. identification of the creator(s) of the Licensed
251
+ Material and any others designated to receive
252
+ attribution, in any reasonable manner requested by
253
+ the Licensor (including by pseudonym if
254
+ designated);
255
+
256
+ ii. a copyright notice;
257
+
258
+ iii. a notice that refers to this Public License;
259
+
260
+ iv. a notice that refers to the disclaimer of
261
+ warranties;
262
+
263
+ v. a URI or hyperlink to the Licensed Material to the
264
+ extent reasonably practicable;
265
+
266
+ b. indicate if You modified the Licensed Material and
267
+ retain an indication of any previous modifications; and
268
+
269
+ c. indicate the Licensed Material is licensed under this
270
+ Public License, and include the text of, or the URI or
271
+ hyperlink to, this Public License.
272
+
273
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
274
+ reasonable manner based on the medium, means, and context in
275
+ which You Share the Licensed Material. For example, it may be
276
+ reasonable to satisfy the conditions by providing a URI or
277
+ hyperlink to a resource that includes the required
278
+ information.
279
+ 3. If requested by the Licensor, You must remove any of the
280
+ information required by Section 3(a)(1)(A) to the extent
281
+ reasonably practicable.
282
+
283
+ b. ShareAlike.
284
+
285
+ In addition to the conditions in Section 3(a), if You Share
286
+ Adapted Material You produce, the following conditions also apply.
287
+
288
+ 1. The Adapter's License You apply must be a Creative Commons
289
+ license with the same License Elements, this version or
290
+ later, or a BY-NC-SA Compatible License.
291
+
292
+ 2. You must include the text of, or the URI or hyperlink to, the
293
+ Adapter's License You apply. You may satisfy this condition
294
+ in any reasonable manner based on the medium, means, and
295
+ context in which You Share Adapted Material.
296
+
297
+ 3. You may not offer or impose any additional or different terms
298
+ or conditions on, or apply any Effective Technological
299
+ Measures to, Adapted Material that restrict exercise of the
300
+ rights granted under the Adapter's License You apply.
301
+
302
+
303
+ Section 4 -- Sui Generis Database Rights.
304
+
305
+ Where the Licensed Rights include Sui Generis Database Rights that
306
+ apply to Your use of the Licensed Material:
307
+
308
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309
+ to extract, reuse, reproduce, and Share all or a substantial
310
+ portion of the contents of the database for NonCommercial purposes
311
+ only;
312
+
313
+ b. if You include all or a substantial portion of the database
314
+ contents in a database in which You have Sui Generis Database
315
+ Rights, then the database in which You have Sui Generis Database
316
+ Rights (but not its individual contents) is Adapted Material,
317
+ including for purposes of Section 3(b); and
318
+
319
+ c. You must comply with the conditions in Section 3(a) if You Share
320
+ all or a substantial portion of the contents of the database.
321
+
322
+ For the avoidance of doubt, this Section 4 supplements and does not
323
+ replace Your obligations under this Public License where the Licensed
324
+ Rights include other Copyright and Similar Rights.
325
+
326
+
327
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328
+
329
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339
+
340
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349
+
350
+ c. The disclaimer of warranties and limitation of liability provided
351
+ above shall be interpreted in a manner that, to the extent
352
+ possible, most closely approximates an absolute disclaimer and
353
+ waiver of all liability.
354
+
355
+
356
+ Section 6 -- Term and Termination.
357
+
358
+ a. This Public License applies for the term of the Copyright and
359
+ Similar Rights licensed here. However, if You fail to comply with
360
+ this Public License, then Your rights under this Public License
361
+ terminate automatically.
362
+
363
+ b. Where Your right to use the Licensed Material has terminated under
364
+ Section 6(a), it reinstates:
365
+
366
+ 1. automatically as of the date the violation is cured, provided
367
+ it is cured within 30 days of Your discovery of the
368
+ violation; or
369
+
370
+ 2. upon express reinstatement by the Licensor.
371
+
372
+ For the avoidance of doubt, this Section 6(b) does not affect any
373
+ right the Licensor may have to seek remedies for Your violations
374
+ of this Public License.
375
+
376
+ c. For the avoidance of doubt, the Licensor may also offer the
377
+ Licensed Material under separate terms or conditions or stop
378
+ distributing the Licensed Material at any time; however, doing so
379
+ will not terminate this Public License.
380
+
381
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382
+ License.
383
+
384
+
385
+ Section 7 -- Other Terms and Conditions.
386
+
387
+ a. The Licensor shall not be bound by any additional or different
388
+ terms or conditions communicated by You unless expressly agreed.
389
+
390
+ b. Any arrangements, understandings, or agreements regarding the
391
+ Licensed Material not stated herein are separate from and
392
+ independent of the terms and conditions of this Public License.
393
+
394
+
395
+ Section 8 -- Interpretation.
396
+
397
+ a. For the avoidance of doubt, this Public License does not, and
398
+ shall not be interpreted to, reduce, limit, restrict, or impose
399
+ conditions on any use of the Licensed Material that could lawfully
400
+ be made without permission under this Public License.
401
+
402
+ b. To the extent possible, if any provision of this Public License is
403
+ deemed unenforceable, it shall be automatically reformed to the
404
+ minimum extent necessary to make it enforceable. If the provision
405
+ cannot be reformed, it shall be severed from this Public License
406
+ without affecting the enforceability of the remaining terms and
407
+ conditions.
408
+
409
+ c. No term or condition of this Public License will be waived and no
410
+ failure to comply consented to unless expressly agreed to by the
411
+ Licensor.
412
+
413
+ d. Nothing in this Public License constitutes or may be interpreted
414
+ as a limitation upon, or waiver of, any privileges and immunities
415
+ that apply to the Licensor or You, including from the legal
416
+ processes of any jurisdiction or authority.
417
+
418
+ =======================================================================
419
+
420
+ Creative Commons is not a party to its public
421
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
422
+ its public licenses to material it publishes and in those instances
423
+ will be considered the “Licensor.” The text of the Creative Commons
424
+ public licenses is dedicated to the public domain under the CC0 Public
425
+ Domain Dedication. Except for the limited purpose of indicating that
426
+ material is shared under a Creative Commons public license or as
427
+ otherwise permitted by the Creative Commons policies published at
428
+ creativecommons.org/policies, Creative Commons does not authorize the
429
+ use of the trademark "Creative Commons" or any other trademark or logo
430
+ of Creative Commons without its prior written consent including,
431
+ without limitation, in connection with any unauthorized modifications
432
+ to any of its public licenses or any other arrangements,
433
+ understandings, or agreements concerning use of licensed material. For
434
+ the avoidance of doubt, this paragraph does not form part of the
435
+ public licenses.
436
+
437
+ Creative Commons may be contacted at creativecommons.org.
model/ImageBind/README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ImageBind: One Embedding Space To Bind Them All
2
+
3
+ **[FAIR, Meta AI](https://ai.facebook.com/research/)**
4
+
5
+ Rohit Girdhar*,
6
+ Alaaeldin El-Nouby*,
7
+ Zhuang Liu,
8
+ Mannat Singh,
9
+ Kalyan Vasudev Alwala,
10
+ Armand Joulin,
11
+ Ishan Misra*
12
+
13
+ To appear at CVPR 2023 (*Highlighted paper*)
14
+
15
+ [[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)]
16
+
17
+ PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
18
+
19
+ ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
20
+
21
+
22
+
23
+ ![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)
24
+
25
+ ## ImageBind model
26
+
27
+ Emergent zero-shot classification performance.
28
+
29
+ <table style="margin: auto">
30
+ <tr>
31
+ <th>Model</th>
32
+ <th><span style="color:blue">IN1k</span></th>
33
+ <th><span style="color:purple">K400</span></th>
34
+ <th><span style="color:green">NYU-D</span></th>
35
+ <th><span style="color:LightBlue">ESC</span></th>
36
+ <th><span style="color:orange">LLVIP</span></th>
37
+ <th><span style="color:purple">Ego4D</span></th>
38
+ <th>download</th>
39
+ </tr>
40
+ <tr>
41
+ <td>imagebind_huge</td>
42
+ <td align="right">77.7</td>
43
+ <td align="right">50.0</td>
44
+ <td align="right">54.0</td>
45
+ <td align="right">66.9</td>
46
+ <td align="right">63.4</td>
47
+ <td align="right">25.0</td>
48
+ <td><a href="https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth">checkpoint</a></td>
49
+ </tr>
50
+
51
+ </table>
52
+
53
+ ## Usage
54
+
55
+ Install pytorch 1.13+ and other 3rd party dependencies.
56
+
57
+ ```shell
58
+ conda create --name imagebind python=3.8 -y
59
+ conda activate imagebind
60
+
61
+ pip install -r requirements.txt
62
+ ```
63
+
64
+ For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
65
+
66
+ ```
67
+ pip install soundfile
68
+ ```
69
+
70
+
71
+ Extract and compare features across modalities (e.g. Image, Text and Audio).
72
+
73
+ ```python
74
+ import data
75
+ import torch
76
+ from models import imagebind_model
77
+ from models.imagebind_model import ModalityType
78
+
79
+ text_list=["A dog.", "A car", "A bird"]
80
+ image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
81
+ audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
82
+
83
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
84
+
85
+ # Instantiate model
86
+ model = imagebind_model.imagebind_huge(pretrained=True)
87
+ model.eval()
88
+ model.to(device)
89
+
90
+ # Load data
91
+ inputs = {
92
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
93
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
94
+ ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
95
+ }
96
+
97
+ with torch.no_grad():
98
+ embeddings = model(inputs)
99
+
100
+ print(
101
+ "Vision x Text: ",
102
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
103
+ )
104
+ print(
105
+ "Audio x Text: ",
106
+ torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
107
+ )
108
+ print(
109
+ "Vision x Audio: ",
110
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
111
+ )
112
+
113
+ # Expected output:
114
+ #
115
+ # Vision x Text:
116
+ # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
117
+ # [3.3836e-05, 9.9994e-01, 2.4118e-05],
118
+ # [4.7997e-05, 1.3496e-02, 9.8646e-01]])
119
+ #
120
+ # Audio x Text:
121
+ # tensor([[1., 0., 0.],
122
+ # [0., 1., 0.],
123
+ # [0., 0., 1.]])
124
+ #
125
+ # Vision x Audio:
126
+ # tensor([[0.8070, 0.1088, 0.0842],
127
+ # [0.1036, 0.7884, 0.1079],
128
+ # [0.0018, 0.0022, 0.9960]])
129
+
130
+ ```
131
+
132
+ ## Model card
133
+ Please see the [model card](model_card.md) for details.
134
+
135
+ ## License
136
+
137
+ ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
138
+
139
+ ## Contributing
140
+
141
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
142
+
143
+ ## Citing ImageBind
144
+
145
+ If you find this repository useful, please consider giving a star :star: and citation
146
+
147
+ ```
148
+ @inproceedings{girdhar2023imagebind,
149
+ title={ImageBind: One Embedding Space To Bind Them All},
150
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
151
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
152
+ booktitle={CVPR},
153
+ year={2023}
154
+ }
155
+ ```
model/ImageBind/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .models import imagebind_model
2
+ from .models.imagebind_model import ModalityType
model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
model/ImageBind/data.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import math
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torchaudio
13
+ import logging
14
+
15
+ from .models.multimodal_preprocessors import SimpleTokenizer
16
+ from PIL import Image
17
+ from pytorchvideo import transforms as pv_transforms
18
+ from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
19
+ from pytorchvideo.data.encoded_video import EncodedVideo
20
+
21
+ from torchvision import transforms
22
+ from torchvision.transforms._transforms_video import NormalizeVideo
23
+
24
+ DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
25
+
26
+ BPE_PATH = "/data/guzhaopeng/PandaGPT/code/model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz"
27
+
28
+
29
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
30
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
31
+ waveform -= waveform.mean()
32
+ fbank = torchaudio.compliance.kaldi.fbank(
33
+ waveform,
34
+ htk_compat=True,
35
+ sample_frequency=sample_rate,
36
+ use_energy=False,
37
+ window_type="hanning",
38
+ num_mel_bins=num_mel_bins,
39
+ dither=0.0,
40
+ frame_length=25,
41
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
42
+ )
43
+ # Convert to [mel_bins, num_frames] shape
44
+ fbank = fbank.transpose(0, 1)
45
+ # Pad to target_length
46
+ n_frames = fbank.size(1)
47
+ p = target_length - n_frames
48
+ # if p is too large (say >20%), flash a warning
49
+ if abs(p) / n_frames > 0.2:
50
+ logging.warning(
51
+ "Large gap between audio n_frames(%d) and "
52
+ "target_length (%d). Is the audio_target_length "
53
+ "setting correct?",
54
+ n_frames,
55
+ target_length,
56
+ )
57
+ # cut and pad
58
+ if p > 0:
59
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
60
+ elif p < 0:
61
+ fbank = fbank[:, 0:target_length]
62
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
63
+ # channel image
64
+ fbank = fbank.unsqueeze(0)
65
+ return fbank
66
+
67
+
68
+ def get_clip_timepoints(clip_sampler, duration):
69
+ # Read out all clips in this video
70
+ all_clips_timepoints = []
71
+ is_last_clip = False
72
+ end = 0.0
73
+ while not is_last_clip:
74
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
75
+ all_clips_timepoints.append((start, end))
76
+ return all_clips_timepoints
77
+
78
+
79
+ def load_and_transform_vision_data(image_paths, device):
80
+ if image_paths is None:
81
+ return None
82
+
83
+ image_ouputs = []
84
+ for image_path in image_paths:
85
+ data_transform = transforms.Compose(
86
+ [
87
+ transforms.Resize(
88
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
89
+ ),
90
+ transforms.CenterCrop(224),
91
+ transforms.ToTensor(),
92
+ transforms.Normalize(
93
+ mean=(0.48145466, 0.4578275, 0.40821073),
94
+ std=(0.26862954, 0.26130258, 0.27577711),
95
+ ),
96
+ ]
97
+ )
98
+ with open(image_path, "rb") as fopen:
99
+ image = Image.open(fopen).convert("RGB")
100
+
101
+ image = data_transform(image).to(device)
102
+ image_ouputs.append(image)
103
+ return torch.stack(image_ouputs, dim=0)
104
+
105
+
106
+ def load_and_transform_vision_data_for_web_demo(image_paths, device):
107
+ if image_paths is None:
108
+ return None
109
+
110
+ image_ouputs = []
111
+ for image_path in image_paths:
112
+ data_transform = transforms.Compose(
113
+ [
114
+ transforms.Resize(
115
+ (224,224), interpolation=transforms.InterpolationMode.BICUBIC
116
+ ),
117
+ transforms.CenterCrop(224),
118
+ transforms.ToTensor(),
119
+ transforms.Normalize(
120
+ mean=(0.48145466, 0.4578275, 0.40821073),
121
+ std=(0.26862954, 0.26130258, 0.27577711),
122
+ ),
123
+ ]
124
+ )
125
+ with open(image_path, "rb") as fopen:
126
+ image = Image.open(fopen).convert("RGB")
127
+
128
+ image = data_transform(image).to(device)
129
+ image_ouputs.append(image)
130
+ return torch.stack(image_ouputs, dim=0)
131
+
132
+
133
+ def load_and_transform_thermal_data(thermal_paths, device):
134
+ if thermal_paths is None:
135
+ return None
136
+
137
+ thermal_ouputs = []
138
+ for thermal_path in thermal_paths:
139
+ data_transform = transforms.Compose(
140
+ [
141
+ transforms.Resize(
142
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
143
+ ),
144
+ transforms.CenterCrop(224),
145
+ transforms.ToTensor(),
146
+ ]
147
+ )
148
+ with open(thermal_path, "rb") as fopen:
149
+ thermal = Image.open(fopen).convert("L")
150
+ thermal = data_transform(thermal).to(device)
151
+ thermal_ouputs.append(thermal)
152
+ return torch.stack(thermal_ouputs, dim=0)
153
+
154
+
155
+ def load_and_transform_text(text, device):
156
+ if text is None:
157
+ return None
158
+ tokenizer = SimpleTokenizer(bpe_path=BPE_PATH)
159
+ tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
160
+ tokens = torch.cat(tokens, dim=0)
161
+ return tokens
162
+
163
+
164
+ def load_and_transform_audio_data(
165
+ audio_paths,
166
+ device,
167
+ num_mel_bins=128,
168
+ target_length=204,
169
+ sample_rate=16000,
170
+ clip_duration=2,
171
+ clips_per_video=3,
172
+ mean=-4.268,
173
+ std=9.138,
174
+ ):
175
+ if audio_paths is None:
176
+ return None
177
+
178
+ audio_outputs = []
179
+ clip_sampler = ConstantClipsPerVideoSampler(
180
+ clip_duration=clip_duration, clips_per_video=clips_per_video
181
+ )
182
+
183
+ for audio_path in audio_paths:
184
+ waveform, sr = torchaudio.load(audio_path)
185
+ if sample_rate != sr:
186
+ waveform = torchaudio.functional.resample(
187
+ waveform, orig_freq=sr, new_freq=sample_rate
188
+ )
189
+ all_clips_timepoints = get_clip_timepoints(
190
+ clip_sampler, waveform.size(1) / sample_rate
191
+ )
192
+ all_clips = []
193
+ for clip_timepoints in all_clips_timepoints:
194
+ waveform_clip = waveform[
195
+ :,
196
+ int(clip_timepoints[0] * sample_rate) : int(
197
+ clip_timepoints[1] * sample_rate
198
+ ),
199
+ ]
200
+ waveform_melspec = waveform2melspec(
201
+ waveform_clip, sample_rate, num_mel_bins, target_length
202
+ )
203
+ all_clips.append(waveform_melspec)
204
+
205
+ normalize = transforms.Normalize(mean=mean, std=std)
206
+ all_clips = [normalize(ac).to(device) for ac in all_clips]
207
+
208
+ all_clips = torch.stack(all_clips, dim=0)
209
+ audio_outputs.append(all_clips)
210
+
211
+ return torch.stack(audio_outputs, dim=0)
212
+
213
+
214
+ def get_clip_timepoints(clip_sampler, duration):
215
+ # Read out all clips in this video
216
+ all_clips_timepoints = []
217
+ is_last_clip = False
218
+ end = 0.0
219
+ while not is_last_clip:
220
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
221
+ all_clips_timepoints.append((start, end))
222
+ return all_clips_timepoints
223
+
224
+
225
+ def crop_boxes(boxes, x_offset, y_offset):
226
+ """
227
+ Peform crop on the bounding boxes given the offsets.
228
+ Args:
229
+ boxes (ndarray or None): bounding boxes to peform crop. The dimension
230
+ is `num boxes` x 4.
231
+ x_offset (int): cropping offset in the x axis.
232
+ y_offset (int): cropping offset in the y axis.
233
+ Returns:
234
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
235
+ `num boxes` x 4.
236
+ """
237
+ cropped_boxes = boxes.copy()
238
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
239
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
240
+
241
+ return cropped_boxes
242
+
243
+
244
+ def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
245
+ """
246
+ Perform uniform spatial sampling on the images and corresponding boxes.
247
+ Args:
248
+ images (tensor): images to perform uniform crop. The dimension is
249
+ `num frames` x `channel` x `height` x `width`.
250
+ size (int): size of height and weight to crop the images.
251
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
252
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
253
+ crop if height is larger than width.
254
+ boxes (ndarray or None): optional. Corresponding boxes to images.
255
+ Dimension is `num boxes` x 4.
256
+ scale_size (int): optinal. If not None, resize the images to scale_size before
257
+ performing any crop.
258
+ Returns:
259
+ cropped (tensor): images with dimension of
260
+ `num frames` x `channel` x `size` x `size`.
261
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
262
+ `num boxes` x 4.
263
+ """
264
+ assert spatial_idx in [0, 1, 2]
265
+ ndim = len(images.shape)
266
+ if ndim == 3:
267
+ images = images.unsqueeze(0)
268
+ height = images.shape[2]
269
+ width = images.shape[3]
270
+
271
+ if scale_size is not None:
272
+ if width <= height:
273
+ width, height = scale_size, int(height / width * scale_size)
274
+ else:
275
+ width, height = int(width / height * scale_size), scale_size
276
+ images = torch.nn.functional.interpolate(
277
+ images,
278
+ size=(height, width),
279
+ mode="bilinear",
280
+ align_corners=False,
281
+ )
282
+
283
+ y_offset = int(math.ceil((height - size) / 2))
284
+ x_offset = int(math.ceil((width - size) / 2))
285
+
286
+ if height > width:
287
+ if spatial_idx == 0:
288
+ y_offset = 0
289
+ elif spatial_idx == 2:
290
+ y_offset = height - size
291
+ else:
292
+ if spatial_idx == 0:
293
+ x_offset = 0
294
+ elif spatial_idx == 2:
295
+ x_offset = width - size
296
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
297
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
298
+ if ndim == 3:
299
+ cropped = cropped.squeeze(0)
300
+ return cropped, cropped_boxes
301
+
302
+
303
+ class SpatialCrop(nn.Module):
304
+ """
305
+ Convert the video into 3 smaller clips spatially. Must be used after the
306
+ temporal crops to get spatial crops, and should be used with
307
+ -2 in the spatial crop at the slowfast augmentation stage (so full
308
+ frames are passed in here). Will return a larger list with the
309
+ 3x spatial crops as well.
310
+ """
311
+
312
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
313
+ super().__init__()
314
+ self.crop_size = crop_size
315
+ if num_crops == 3:
316
+ self.crops_to_ext = [0, 1, 2]
317
+ self.flipped_crops_to_ext = []
318
+ elif num_crops == 1:
319
+ self.crops_to_ext = [1]
320
+ self.flipped_crops_to_ext = []
321
+ else:
322
+ raise NotImplementedError("Nothing else supported yet")
323
+
324
+ def forward(self, videos):
325
+ """
326
+ Args:
327
+ videos: A list of C, T, H, W videos.
328
+ Returns:
329
+ videos: A list with 3x the number of elements. Each video converted
330
+ to C, T, H', W' by spatial cropping.
331
+ """
332
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
333
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
334
+ res = []
335
+ for video in videos:
336
+ for spatial_idx in self.crops_to_ext:
337
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
338
+ if not self.flipped_crops_to_ext:
339
+ continue
340
+ flipped_video = transforms.functional.hflip(video)
341
+ for spatial_idx in self.flipped_crops_to_ext:
342
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
343
+ return res
344
+
345
+
346
+ def load_and_transform_video_data(
347
+ video_paths,
348
+ device,
349
+ clip_duration=2,
350
+ clips_per_video=5,
351
+ sample_rate=16000,
352
+ ):
353
+ if video_paths is None:
354
+ return None
355
+
356
+ video_outputs = []
357
+ video_transform = transforms.Compose(
358
+ [
359
+ pv_transforms.ShortSideScale(224),
360
+ NormalizeVideo(
361
+ mean=(0.48145466, 0.4578275, 0.40821073),
362
+ std=(0.26862954, 0.26130258, 0.27577711),
363
+ ),
364
+ ]
365
+ )
366
+
367
+ clip_sampler = ConstantClipsPerVideoSampler(
368
+ clip_duration=clip_duration, clips_per_video=clips_per_video
369
+ )
370
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
371
+
372
+ for video_path in video_paths:
373
+ video = EncodedVideo.from_path(
374
+ video_path,
375
+ decoder="decord",
376
+ decode_audio=False,
377
+ **{"sample_rate": sample_rate},
378
+ )
379
+
380
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
381
+
382
+ all_video = []
383
+ for clip_timepoints in all_clips_timepoints:
384
+ # Read the clip, get frames
385
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
386
+ if clip is None:
387
+ raise ValueError("No clip found")
388
+ video_clip = frame_sampler(clip["video"])
389
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
390
+
391
+ all_video.append(video_clip)
392
+
393
+ all_video = [video_transform(clip) for clip in all_video]
394
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
395
+
396
+ all_video = torch.stack(all_video, dim=0)
397
+ video_outputs.append(all_video)
398
+
399
+ return torch.stack(video_outputs, dim=0).to(device)
model/ImageBind/model_card.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card for ImageBind
2
+
3
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.
4
+ Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.
5
+
6
+ # Model Details
7
+
8
+ ## Model Description
9
+
10
+ <!-- Provide a longer summary of what this model is/does. -->
11
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images
12
+
13
+ - **Developed by:** Meta AI
14
+ - **Model type:** Multimodal model
15
+ - **Language(s) (NLP):** en
16
+ - **License:** CC BY-NC-SA 4.0
17
+ - **Resources for more information:**
18
+ - [GitHub Repo](https://github.com/facebookresearch/ImageBind)
19
+
20
+
21
+ # Uses
22
+
23
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
24
+ This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images.
25
+ We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities.
26
+
27
+ ## Out-of-Scope Use
28
+
29
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
30
+ <!-- If the user enters content, print that. If not, but they enter a task in the list, use that. If neither, say "more info needed." -->
31
+
32
+ This model is *NOT* intended to be used in any real world application -- commercial or otherwise.
33
+ It may produce harmful associations with different inputs.
34
+ The model needs to be investigated and likely re-trained on specific data for any such application.
35
+ The model is expected to work better on web-based visual data since it was trained on such data.
36
+ The text encoder is likely to work only on English language text because of the underlying training datasets.
37
+
38
+ # Bias, Risks, and Limitations
39
+
40
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
41
+ Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness).
42
+ Since our model uses such models as initialization, it will exhibit such biases too.
43
+ Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes.
44
+
45
+
46
+
47
+ # Training Details
48
+
49
+ ## Training Data
50
+
51
+ <!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
52
+
53
+ ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.
54
+ In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.
55
+ We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset.
56
+ We provide the exact training data details in the paper.
57
+
58
+
59
+ ## Training Procedure
60
+
61
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
62
+ Please refer to the research paper and github repo for exact details on this.
63
+
64
+ # Evaluation
65
+
66
+ ## Testing Data, Factors & Metrics
67
+
68
+ We evaluate the model on a variety of different classification benchmarks for each modality.
69
+ The evaluation details are presented in the paper.
70
+ The models performance is measured using standard classification metrics such as accuracy and mAP.
71
+
72
+ # Citation
73
+
74
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
75
+
76
+ **BibTeX:**
77
+ ```
78
+ @inproceedings{girdhar2023imagebind,
79
+ title={ImageBind: One Embedding Space To Bind Them All},
80
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
81
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
82
+ booktitle={CVPR},
83
+ year={2023}
84
+ }
85
+ ```
86
+
87
+
88
+ # Model Card Contact
89
+
90
+ Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com
91
+
92
+ # How to Get Started with the Model
93
+
94
+ Our github repo provides a simple example to extract embeddings from images, audio etc.
model/ImageBind/models/__init__.py ADDED
File without changes
model/ImageBind/models/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (161 Bytes). View file
 
model/ImageBind/models/__pycache__/helpers.cpython-38.pyc ADDED
Binary file (5.2 kB). View file
 
model/ImageBind/models/__pycache__/imagebind_model.cpython-38.pyc ADDED
Binary file (8.83 kB). View file
 
model/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-38.pyc ADDED
Binary file (20 kB). View file
 
model/ImageBind/models/__pycache__/transformer.cpython-38.pyc ADDED
Binary file (7.96 kB). View file
 
model/ImageBind/models/helpers.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+
9
+ import einops
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+
14
+
15
+ class Normalize(nn.Module):
16
+ def __init__(self, dim: int) -> None:
17
+ super().__init__()
18
+ self.dim = dim
19
+
20
+ def forward(self, x):
21
+ return torch.nn.functional.normalize(x, dim=self.dim, p=2)
22
+
23
+
24
+ class LearnableLogitScaling(nn.Module):
25
+ def __init__(
26
+ self,
27
+ logit_scale_init: float = 1 / 0.07,
28
+ learnable: bool = True,
29
+ max_logit_scale: float = 100,
30
+ ) -> None:
31
+ super().__init__()
32
+ self.max_logit_scale = max_logit_scale
33
+ self.logit_scale_init = logit_scale_init
34
+ self.learnable = learnable
35
+ log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
36
+ if learnable:
37
+ self.log_logit_scale = nn.Parameter(log_logit_scale)
38
+ else:
39
+ self.register_buffer("log_logit_scale", log_logit_scale)
40
+
41
+ def forward(self, x):
42
+ return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
43
+
44
+ def extra_repr(self):
45
+ st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \
46
+ f" max_logit_scale={self.max_logit_scale}"
47
+ return st
48
+
49
+
50
+ class EinOpsRearrange(nn.Module):
51
+ def __init__(self, rearrange_expr: str, **kwargs) -> None:
52
+ super().__init__()
53
+ self.rearrange_expr = rearrange_expr
54
+ self.kwargs = kwargs
55
+
56
+ def forward(self, x):
57
+ assert isinstance(x, torch.Tensor)
58
+ return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
59
+
60
+
61
+ class VerboseNNModule(nn.Module):
62
+ """
63
+ Wrapper around nn.Module that prints registered buffers and parameter names.
64
+ """
65
+
66
+ @staticmethod
67
+ def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
68
+ st = (
69
+ "("
70
+ + name
71
+ + "): "
72
+ + "tensor("
73
+ + str(tuple(tensor[1].shape))
74
+ + ", requires_grad="
75
+ + str(tensor[1].requires_grad)
76
+ + ")\n"
77
+ )
78
+ return st
79
+
80
+ def extra_repr(self) -> str:
81
+ named_modules = set()
82
+ for p in self.named_modules():
83
+ named_modules.update([p[0]])
84
+ named_modules = list(named_modules)
85
+
86
+ string_repr = ""
87
+ for p in self.named_parameters():
88
+ name = p[0].split(".")[0]
89
+ if name not in named_modules:
90
+ string_repr += self.get_readable_tensor_repr(name, p)
91
+
92
+ for p in self.named_buffers():
93
+ name = p[0].split(".")[0]
94
+ string_repr += self.get_readable_tensor_repr(name, p)
95
+
96
+ return string_repr
97
+
98
+
99
+ def cast_if_src_dtype(
100
+ tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
101
+ ):
102
+ updated = False
103
+ if tensor.dtype == src_dtype:
104
+ tensor = tensor.to(dtype=tgt_dtype)
105
+ updated = True
106
+ return tensor, updated
107
+
108
+
109
+ class QuickGELU(nn.Module):
110
+ # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
111
+ def forward(self, x: torch.Tensor):
112
+ return x * torch.sigmoid(1.702 * x)
113
+
114
+
115
+ class SelectElement(nn.Module):
116
+ def __init__(self, index) -> None:
117
+ super().__init__()
118
+ self.index = index
119
+
120
+ def forward(self, x):
121
+ assert x.ndim >= 3
122
+ return x[:, self.index, ...]
123
+
124
+ class SelectEOSAndProject(nn.Module):
125
+ """
126
+ Text Pooling used in OpenCLIP
127
+ """
128
+
129
+ def __init__(self, proj: nn.Module) -> None:
130
+ super().__init__()
131
+ self.proj = proj
132
+
133
+ def forward(self, x, seq_len):
134
+ assert x.ndim == 3
135
+ # x is of shape B x L x D
136
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
137
+ x = x[torch.arange(x.shape[0]), seq_len]
138
+ x = self.proj(x)
139
+ return x
model/ImageBind/models/imagebind_model.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import os
10
+ from functools import partial
11
+ from types import SimpleNamespace
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ # from pytorch_lightning.utilities import rank_zero_only
16
+ from .helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize,
17
+ SelectElement, SelectEOSAndProject)
18
+ from .multimodal_preprocessors import (AudioPreprocessor,
19
+ IMUPreprocessor, PadIm2Video,
20
+ PatchEmbedGeneric,
21
+ RGBDTPreprocessor,
22
+ SpatioTemporalPosEmbeddingHelper,
23
+ TextPreprocessor,
24
+ ThermalPreprocessor)
25
+ from .transformer import MultiheadAttention, SimpleTransformer
26
+
27
+ ModalityType = SimpleNamespace(
28
+ VISION="vision",
29
+ TEXT="text",
30
+ AUDIO="audio",
31
+ THERMAL="thermal",
32
+ DEPTH="depth",
33
+ IMU="imu",
34
+ POINT="point",
35
+ )
36
+
37
+
38
+ class ImageBindModel(nn.Module):
39
+ def __init__(
40
+ self,
41
+ video_frames=2,
42
+ kernel_size=(2, 14, 14),
43
+ audio_kernel_size=16,
44
+ audio_stride=10,
45
+ out_embed_dim=768,
46
+ vision_embed_dim=1024,
47
+ vision_num_blocks=24,
48
+ vision_num_heads=16,
49
+ audio_embed_dim=768,
50
+ audio_num_blocks=12,
51
+ audio_num_heads=12,
52
+ audio_num_mel_bins=128,
53
+ audio_target_len=204,
54
+ audio_drop_path=0.1,
55
+ text_embed_dim=768,
56
+ text_num_blocks=12,
57
+ text_num_heads=12,
58
+ depth_embed_dim=384,
59
+ depth_kernel_size=16,
60
+ depth_num_blocks=12,
61
+ depth_num_heads=8,
62
+ depth_drop_path=0.0,
63
+ thermal_embed_dim=768,
64
+ thermal_kernel_size=16,
65
+ thermal_num_blocks=12,
66
+ thermal_num_heads=12,
67
+ thermal_drop_path=0.0,
68
+ imu_embed_dim=512,
69
+ imu_kernel_size=8,
70
+ imu_num_blocks=6,
71
+ imu_num_heads=8,
72
+ imu_drop_path=0.7,
73
+ layers = [7,15,23,31]
74
+ ):
75
+ super().__init__()
76
+
77
+ self.out_layers = layers
78
+
79
+ self.modality_preprocessors = self._create_modality_preprocessors(
80
+ video_frames,
81
+ vision_embed_dim,
82
+ kernel_size,
83
+ text_embed_dim,
84
+ audio_embed_dim,
85
+ audio_kernel_size,
86
+ audio_stride,
87
+ audio_num_mel_bins,
88
+ audio_target_len,
89
+ depth_embed_dim,
90
+ depth_kernel_size,
91
+ thermal_embed_dim,
92
+ thermal_kernel_size,
93
+ imu_embed_dim,
94
+ )
95
+
96
+ self.modality_trunks = self._create_modality_trunks(
97
+ vision_embed_dim,
98
+ vision_num_blocks,
99
+ vision_num_heads,
100
+ text_embed_dim,
101
+ text_num_blocks,
102
+ text_num_heads,
103
+ audio_embed_dim,
104
+ audio_num_blocks,
105
+ audio_num_heads,
106
+ audio_drop_path,
107
+ depth_embed_dim,
108
+ depth_num_blocks,
109
+ depth_num_heads,
110
+ depth_drop_path,
111
+ thermal_embed_dim,
112
+ thermal_num_blocks,
113
+ thermal_num_heads,
114
+ thermal_drop_path,
115
+ imu_embed_dim,
116
+ imu_num_blocks,
117
+ imu_num_heads,
118
+ imu_drop_path,
119
+ )
120
+
121
+ self.modality_heads = self._create_modality_heads(
122
+ out_embed_dim,
123
+ vision_embed_dim,
124
+ text_embed_dim,
125
+ audio_embed_dim,
126
+ depth_embed_dim,
127
+ thermal_embed_dim,
128
+ imu_embed_dim,
129
+ )
130
+
131
+ self.modality_postprocessors = self._create_modality_postprocessors(
132
+ out_embed_dim
133
+ )
134
+
135
+
136
+ def _create_modality_preprocessors(
137
+ self,
138
+ video_frames=2,
139
+ vision_embed_dim=1024,
140
+ kernel_size=(2, 14, 14),
141
+ text_embed_dim=768,
142
+ audio_embed_dim=768,
143
+ audio_kernel_size=16,
144
+ audio_stride=10,
145
+ audio_num_mel_bins=128,
146
+ audio_target_len=204,
147
+ depth_embed_dim=768,
148
+ depth_kernel_size=16,
149
+ thermal_embed_dim=768,
150
+ thermal_kernel_size=16,
151
+ imu_embed_dim=512,
152
+ ):
153
+ rgbt_stem = PatchEmbedGeneric(
154
+ proj_stem=[
155
+ PadIm2Video(pad_type="repeat", ntimes=2),
156
+ nn.Conv3d(
157
+ in_channels=3,
158
+ kernel_size=kernel_size,
159
+ out_channels=vision_embed_dim,
160
+ stride=kernel_size,
161
+ bias=False,
162
+ ),
163
+ ]
164
+ )
165
+ rgbt_preprocessor = RGBDTPreprocessor(
166
+ img_size=[3, video_frames, 224, 224],
167
+ num_cls_tokens=1,
168
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
169
+ rgbt_stem=rgbt_stem,
170
+ depth_stem=None,
171
+ )
172
+
173
+ text_preprocessor = TextPreprocessor(
174
+ context_length=77,
175
+ vocab_size=49408,
176
+ embed_dim=text_embed_dim,
177
+ causal_masking=True,
178
+ )
179
+
180
+ audio_stem = PatchEmbedGeneric(
181
+ proj_stem=[
182
+ nn.Conv2d(
183
+ in_channels=1,
184
+ kernel_size=audio_kernel_size,
185
+ stride=audio_stride,
186
+ out_channels=audio_embed_dim,
187
+ bias=False,
188
+ ),
189
+ ],
190
+ norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
191
+ )
192
+ audio_preprocessor = AudioPreprocessor(
193
+ img_size=[1, audio_num_mel_bins, audio_target_len],
194
+ num_cls_tokens=1,
195
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
196
+ audio_stem=audio_stem,
197
+ )
198
+
199
+ depth_stem = PatchEmbedGeneric(
200
+ [
201
+ nn.Conv2d(
202
+ kernel_size=depth_kernel_size,
203
+ in_channels=1,
204
+ out_channels=depth_embed_dim,
205
+ stride=depth_kernel_size,
206
+ bias=False,
207
+ ),
208
+ ],
209
+ norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
210
+ )
211
+
212
+ depth_preprocessor = RGBDTPreprocessor(
213
+ img_size=[1, 224, 224],
214
+ num_cls_tokens=1,
215
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
216
+ rgbt_stem=None,
217
+ depth_stem=depth_stem,
218
+ )
219
+
220
+ thermal_stem = PatchEmbedGeneric(
221
+ [
222
+ nn.Conv2d(
223
+ kernel_size=thermal_kernel_size,
224
+ in_channels=1,
225
+ out_channels=thermal_embed_dim,
226
+ stride=thermal_kernel_size,
227
+ bias=False,
228
+ ),
229
+ ],
230
+ norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
231
+ )
232
+ thermal_preprocessor = ThermalPreprocessor(
233
+ img_size=[1, 224, 224],
234
+ num_cls_tokens=1,
235
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
236
+ thermal_stem=thermal_stem,
237
+ )
238
+
239
+ imu_stem = PatchEmbedGeneric(
240
+ [
241
+ nn.Linear(
242
+ in_features=48,
243
+ out_features=imu_embed_dim,
244
+ bias=False,
245
+ ),
246
+ ],
247
+ norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
248
+ )
249
+
250
+ imu_preprocessor = IMUPreprocessor(
251
+ img_size=[6, 2000],
252
+ num_cls_tokens=1,
253
+ kernel_size=8,
254
+ embed_dim=imu_embed_dim,
255
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
256
+ imu_stem=imu_stem,
257
+ )
258
+
259
+ modality_preprocessors = {
260
+ ModalityType.VISION: rgbt_preprocessor,
261
+ ModalityType.TEXT: text_preprocessor,
262
+ ModalityType.AUDIO: audio_preprocessor,
263
+ ModalityType.DEPTH: depth_preprocessor,
264
+ ModalityType.THERMAL: thermal_preprocessor,
265
+ ModalityType.IMU: imu_preprocessor,
266
+ }
267
+
268
+ return nn.ModuleDict(modality_preprocessors)
269
+
270
+ def _create_modality_trunks(
271
+ self,
272
+ vision_embed_dim=1024,
273
+ vision_num_blocks=24,
274
+ vision_num_heads=16,
275
+ text_embed_dim=768,
276
+ text_num_blocks=12,
277
+ text_num_heads=12,
278
+ audio_embed_dim=768,
279
+ audio_num_blocks=12,
280
+ audio_num_heads=12,
281
+ audio_drop_path=0.0,
282
+ depth_embed_dim=768,
283
+ depth_num_blocks=12,
284
+ depth_num_heads=12,
285
+ depth_drop_path=0.0,
286
+ thermal_embed_dim=768,
287
+ thermal_num_blocks=12,
288
+ thermal_num_heads=12,
289
+ thermal_drop_path=0.0,
290
+ imu_embed_dim=512,
291
+ imu_num_blocks=6,
292
+ imu_num_heads=8,
293
+ imu_drop_path=0.7,
294
+ ):
295
+ def instantiate_trunk(
296
+ embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
297
+ ):
298
+ return SimpleTransformer(
299
+ embed_dim=embed_dim,
300
+ num_blocks=num_blocks,
301
+ ffn_dropout_rate=0.0,
302
+ drop_path_rate=drop_path,
303
+ attn_target=partial(
304
+ MultiheadAttention,
305
+ embed_dim=embed_dim,
306
+ num_heads=num_heads,
307
+ bias=True,
308
+ add_bias_kv=add_bias_kv,
309
+ ),
310
+ pre_transformer_layer=nn.Sequential(
311
+ nn.LayerNorm(embed_dim, eps=1e-6)
312
+ if pre_transformer_ln
313
+ else nn.Identity(),
314
+ EinOpsRearrange("b l d -> l b d"),
315
+ ),
316
+ post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
317
+ )
318
+
319
+ modality_trunks = {}
320
+ modality_trunks[ModalityType.VISION] = instantiate_trunk(
321
+ vision_embed_dim,
322
+ vision_num_blocks,
323
+ vision_num_heads,
324
+ pre_transformer_ln=True,
325
+ add_bias_kv=False,
326
+ drop_path=0.0,
327
+ )
328
+ modality_trunks[ModalityType.TEXT] = instantiate_trunk(
329
+ text_embed_dim,
330
+ text_num_blocks,
331
+ text_num_heads,
332
+ pre_transformer_ln=False,
333
+ add_bias_kv=False,
334
+ drop_path=0.0,
335
+ )
336
+ modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
337
+ audio_embed_dim,
338
+ audio_num_blocks,
339
+ audio_num_heads,
340
+ pre_transformer_ln=False,
341
+ add_bias_kv=True,
342
+ drop_path=audio_drop_path,
343
+ )
344
+ modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
345
+ depth_embed_dim,
346
+ depth_num_blocks,
347
+ depth_num_heads,
348
+ pre_transformer_ln=False,
349
+ add_bias_kv=True,
350
+ drop_path=depth_drop_path,
351
+ )
352
+ modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
353
+ thermal_embed_dim,
354
+ thermal_num_blocks,
355
+ thermal_num_heads,
356
+ pre_transformer_ln=False,
357
+ add_bias_kv=True,
358
+ drop_path=thermal_drop_path,
359
+ )
360
+ modality_trunks[ModalityType.IMU] = instantiate_trunk(
361
+ imu_embed_dim,
362
+ imu_num_blocks,
363
+ imu_num_heads,
364
+ pre_transformer_ln=False,
365
+ add_bias_kv=True,
366
+ drop_path=imu_drop_path,
367
+ )
368
+
369
+ return nn.ModuleDict(modality_trunks)
370
+
371
+ def _create_modality_heads(
372
+ self,
373
+ out_embed_dim,
374
+ vision_embed_dim,
375
+ text_embed_dim,
376
+ audio_embed_dim,
377
+ depth_embed_dim,
378
+ thermal_embed_dim,
379
+ imu_embed_dim,
380
+ ):
381
+ modality_heads = {}
382
+
383
+ modality_heads[ModalityType.VISION] = nn.Sequential(
384
+ nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
385
+ SelectElement(index=0),
386
+ nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
387
+ )
388
+
389
+ modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
390
+ proj=nn.Sequential(
391
+ nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
392
+ nn.Linear(text_embed_dim, out_embed_dim, bias=False),
393
+ )
394
+ )
395
+
396
+ modality_heads[ModalityType.AUDIO] = nn.Sequential(
397
+ nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
398
+ SelectElement(index=0),
399
+ nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
400
+ )
401
+
402
+ modality_heads[ModalityType.DEPTH] = nn.Sequential(
403
+ nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
404
+ SelectElement(index=0),
405
+ nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
406
+ )
407
+
408
+ modality_heads[ModalityType.THERMAL] = nn.Sequential(
409
+ nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
410
+ SelectElement(index=0),
411
+ nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
412
+ )
413
+
414
+ modality_heads[ModalityType.IMU] = nn.Sequential(
415
+ nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
416
+ SelectElement(index=0),
417
+ nn.Dropout(p=0.5),
418
+ nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
419
+ )
420
+
421
+ return nn.ModuleDict(modality_heads)
422
+
423
+ def _create_modality_postprocessors(self, out_embed_dim):
424
+ modality_postprocessors = {}
425
+
426
+ modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
427
+ modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
428
+ Normalize(dim=-1), LearnableLogitScaling(learnable=True)
429
+ )
430
+ modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
431
+ Normalize(dim=-1),
432
+ LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
433
+ )
434
+ modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
435
+ Normalize(dim=-1),
436
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
437
+ )
438
+ modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
439
+ Normalize(dim=-1),
440
+ LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
441
+ )
442
+ modality_postprocessors[ModalityType.IMU] = nn.Sequential(
443
+ Normalize(dim=-1),
444
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
445
+ )
446
+
447
+ return nn.ModuleDict(modality_postprocessors)
448
+
449
+ def forward(self, inputs):
450
+ outputs = {}
451
+ for modality_key, modality_value in inputs.items():
452
+ reduce_list = (
453
+ modality_value.ndim >= 5
454
+ ) # Audio and Video inputs consist of multiple clips
455
+ if reduce_list:
456
+ B, S = modality_value.shape[:2]
457
+ modality_value = modality_value.reshape(
458
+ B * S, *modality_value.shape[2:]
459
+ )
460
+
461
+ if modality_value is not None:
462
+ modality_value = self.modality_preprocessors[modality_key](
463
+ **{modality_key: modality_value}
464
+ )
465
+ trunk_inputs = modality_value["trunk"]
466
+ head_inputs = modality_value["head"]
467
+
468
+ modality_value, modality_full_value = self.modality_trunks[modality_key](**trunk_inputs, out_layers=self.out_layers)
469
+
470
+
471
+ modality_value = self.modality_heads[modality_key](
472
+ modality_value, **head_inputs
473
+ )
474
+ modality_value = self.modality_postprocessors[modality_key](
475
+ modality_value
476
+ )
477
+
478
+ if reduce_list:
479
+ modality_value = modality_value.reshape(B, S, -1)
480
+ modality_value = modality_value.mean(dim=1)
481
+
482
+ outputs[modality_key] = modality_value, modality_full_value
483
+
484
+ return outputs
485
+
486
+
487
+ def imagebind_huge(args):
488
+
489
+ if 'layers' in args:
490
+ layers = args['layers']
491
+ else:
492
+ layers = [7,15,23,31]
493
+
494
+ return ImageBindModel(
495
+ vision_embed_dim=1280,
496
+ vision_num_blocks=32,
497
+ vision_num_heads=16,
498
+ text_embed_dim=1024,
499
+ text_num_blocks=24,
500
+ text_num_heads=16,
501
+ out_embed_dim=1024,
502
+ audio_drop_path=0.1,
503
+ imu_drop_path=0.7,
504
+ layers = layers
505
+ ), 1024
506
+
507
+
508
+ def save_module(module_dict: nn.ModuleDict, module_name: str = "",
509
+ checkpoint_dir: str = "./.checkpoints/full", postfix: str = "_last",
510
+ extension: str = "pth"):
511
+ try:
512
+ torch.save(module_dict.state_dict(),
513
+ os.path.join(checkpoint_dir, f"imagebind-{module_name}{postfix}.{extension}"))
514
+ logging.info(f"Saved parameters for module {module_name} to {checkpoint_dir}.")
515
+ except FileNotFoundError:
516
+ logging.warning(f"Could not save module parameters for {module_name} to {checkpoint_dir}.")
517
+
518
+
519
+ def load_module(module_dict: nn.ModuleDict, module_name: str = "",
520
+ checkpoint_dir: str = "./.checkpoints/full", postfix: str = "_last",
521
+ extension: str = "pth"):
522
+ try:
523
+ module_dict.load_state_dict(torch.load(
524
+ os.path.join(checkpoint_dir, f"imagebind-{module_name}{postfix}.{extension}")), strict=False)
525
+ logging.info(f"Loaded parameters for module {module_name} from {checkpoint_dir}.")
526
+ except FileNotFoundError:
527
+ logging.warning(f"Could not load module parameters for {module_name} from {checkpoint_dir}.")
model/ImageBind/models/multimodal_preprocessors.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import gzip
9
+ import html
10
+ import io
11
+ import math
12
+ from functools import lru_cache
13
+ from typing import Callable, List, Optional, Tuple
14
+
15
+ import ftfy
16
+ import numpy as np
17
+ import regex as re
18
+ import torch
19
+ import torch.nn as nn
20
+ from iopath.common.file_io import g_pathmgr
21
+ from timm.models.layers import trunc_normal_
22
+
23
+ from .helpers import VerboseNNModule, cast_if_src_dtype
24
+
25
+
26
+ def get_sinusoid_encoding_table(n_position, d_hid):
27
+ """Sinusoid position encoding table"""
28
+
29
+ # TODO: make it with torch instead of numpy
30
+ def get_position_angle_vec(position):
31
+ return [
32
+ position / np.power(10000, 2 * (hid_j // 2) / d_hid)
33
+ for hid_j in range(d_hid)
34
+ ]
35
+
36
+ sinusoid_table = np.array(
37
+ [get_position_angle_vec(pos_i) for pos_i in range(n_position)]
38
+ )
39
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
40
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
41
+
42
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
43
+
44
+
45
+ def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
46
+ N = pos_embed.shape[1]
47
+ if N == target_spatial_size:
48
+ return pos_embed
49
+ dim = pos_embed.shape[-1]
50
+ # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
51
+ pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
52
+ pos_embed = nn.functional.interpolate(
53
+ pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
54
+ 0, 3, 1, 2
55
+ ),
56
+ scale_factor=math.sqrt(target_spatial_size / N),
57
+ mode="bicubic",
58
+ )
59
+ if updated:
60
+ pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
61
+ pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
62
+ return pos_embed
63
+
64
+
65
+ def interpolate_pos_encoding(
66
+ npatch_per_img,
67
+ pos_embed,
68
+ patches_layout,
69
+ input_shape=None,
70
+ first_patch_idx=1,
71
+ ):
72
+ assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
73
+ N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
74
+ if npatch_per_img == N:
75
+ return pos_embed
76
+
77
+ assert (
78
+ patches_layout[-1] == patches_layout[-2]
79
+ ), "Interpolation of pos embed not supported for non-square layouts"
80
+
81
+ class_emb = pos_embed[:, :first_patch_idx]
82
+ pos_embed = pos_embed[:, first_patch_idx:]
83
+
84
+ if input_shape is None or patches_layout[0] == 1:
85
+ # simple 2D pos embedding, no temporal component
86
+ pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
87
+ elif patches_layout[0] > 1:
88
+ # pos embed has a temporal component
89
+ assert len(input_shape) == 4, "temporal interpolation not supported"
90
+ # we only support 2D interpolation in this case
91
+ num_frames = patches_layout[0]
92
+ num_spatial_tokens = patches_layout[1] * patches_layout[2]
93
+ pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
94
+ # interpolate embedding for zeroth frame
95
+ pos_embed = interpolate_pos_encoding_2d(
96
+ npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
97
+ )
98
+ else:
99
+ raise ValueError("This type of interpolation isn't implemented")
100
+
101
+ return torch.cat((class_emb, pos_embed), dim=1)
102
+
103
+
104
+ def _get_pos_embedding(
105
+ npatch_per_img,
106
+ pos_embed,
107
+ patches_layout,
108
+ input_shape,
109
+ first_patch_idx=1,
110
+ ):
111
+ pos_embed = interpolate_pos_encoding(
112
+ npatch_per_img,
113
+ pos_embed,
114
+ patches_layout,
115
+ input_shape=input_shape,
116
+ first_patch_idx=first_patch_idx,
117
+ )
118
+ return pos_embed
119
+
120
+
121
+ class PatchEmbedGeneric(nn.Module):
122
+ """
123
+ PatchEmbed from Hydra
124
+ """
125
+
126
+ def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
127
+ super().__init__()
128
+
129
+ if len(proj_stem) > 1:
130
+ self.proj = nn.Sequential(*proj_stem)
131
+ else:
132
+ # Special case to be able to load pre-trained models that were
133
+ # trained with a standard stem
134
+ self.proj = proj_stem[0]
135
+ self.norm_layer = norm_layer
136
+
137
+ def get_patch_layout(self, img_size):
138
+ with torch.no_grad():
139
+ dummy_img = torch.zeros(
140
+ [
141
+ 1,
142
+ ]
143
+ + img_size
144
+ )
145
+ dummy_out = self.proj(dummy_img)
146
+ embed_dim = dummy_out.shape[1]
147
+ patches_layout = tuple(dummy_out.shape[2:])
148
+ num_patches = np.prod(patches_layout)
149
+ return patches_layout, num_patches, embed_dim
150
+
151
+ def forward(self, x):
152
+ x = self.proj(x)
153
+ # B C (T) H W -> B (T)HW C
154
+ x = x.flatten(2).transpose(1, 2)
155
+ if self.norm_layer is not None:
156
+ x = self.norm_layer(x)
157
+ return x
158
+
159
+
160
+ class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
161
+ def __init__(
162
+ self,
163
+ patches_layout: List,
164
+ num_patches: int,
165
+ num_cls_tokens: int,
166
+ embed_dim: int,
167
+ learnable: bool,
168
+ ) -> None:
169
+ super().__init__()
170
+ self.num_cls_tokens = num_cls_tokens
171
+ self.patches_layout = patches_layout
172
+ self.num_patches = num_patches
173
+ self.num_tokens = num_cls_tokens + num_patches
174
+ self.learnable = learnable
175
+ if self.learnable:
176
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
177
+ trunc_normal_(self.pos_embed, std=0.02)
178
+ else:
179
+ self.register_buffer(
180
+ "pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
181
+ )
182
+
183
+ def get_pos_embedding(self, vision_input, all_vision_tokens):
184
+ input_shape = vision_input.shape
185
+ pos_embed = _get_pos_embedding(
186
+ all_vision_tokens.size(1) - self.num_cls_tokens,
187
+ pos_embed=self.pos_embed,
188
+ patches_layout=self.patches_layout,
189
+ input_shape=input_shape,
190
+ first_patch_idx=self.num_cls_tokens,
191
+ )
192
+ return pos_embed
193
+
194
+
195
+ class RGBDTPreprocessor(VerboseNNModule):
196
+ def __init__(
197
+ self,
198
+ rgbt_stem: PatchEmbedGeneric,
199
+ depth_stem: Optional[PatchEmbedGeneric],
200
+ img_size: Tuple = (3, 224, 224),
201
+ num_cls_tokens: int = 1,
202
+ pos_embed_fn: Optional[Callable] = None,
203
+ use_type_embed: bool = False,
204
+ init_param_style: str = "openclip",
205
+ ) -> None:
206
+ super().__init__()
207
+ stem = rgbt_stem if rgbt_stem is not None else depth_stem
208
+ (
209
+ self.patches_layout,
210
+ self.num_patches,
211
+ self.embed_dim,
212
+ ) = stem.get_patch_layout(img_size)
213
+ self.rgbt_stem = rgbt_stem
214
+ self.depth_stem = depth_stem
215
+ self.use_pos_embed = pos_embed_fn is not None
216
+ self.use_type_embed = use_type_embed
217
+ self.num_cls_tokens = num_cls_tokens
218
+
219
+ if self.use_pos_embed:
220
+ self.pos_embedding_helper = pos_embed_fn(
221
+ patches_layout=self.patches_layout,
222
+ num_cls_tokens=num_cls_tokens,
223
+ num_patches=self.num_patches,
224
+ embed_dim=self.embed_dim,
225
+ )
226
+ if self.num_cls_tokens > 0:
227
+ self.cls_token = nn.Parameter(
228
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
229
+ )
230
+ if self.use_type_embed:
231
+ self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
232
+
233
+ self.init_parameters(init_param_style)
234
+
235
+ @torch.no_grad()
236
+ def init_parameters(self, init_param_style):
237
+ if init_param_style == "openclip":
238
+ # OpenCLIP style initialization
239
+ scale = self.embed_dim**-0.5
240
+ if self.use_pos_embed:
241
+ nn.init.normal_(self.pos_embedding_helper.pos_embed)
242
+ self.pos_embedding_helper.pos_embed *= scale
243
+
244
+ if self.num_cls_tokens > 0:
245
+ nn.init.normal_(self.cls_token)
246
+ self.cls_token *= scale
247
+ elif init_param_style == "vit":
248
+ self.cls_token.data.fill_(0)
249
+ else:
250
+ raise ValueError(f"Unknown init {init_param_style}")
251
+
252
+ if self.use_type_embed:
253
+ nn.init.normal_(self.type_embed)
254
+
255
+ def tokenize_input_and_cls_pos(self, input, stem, mask):
256
+ # tokens is of shape B x L x D
257
+ tokens = stem(input)
258
+ assert tokens.ndim == 3
259
+ assert tokens.shape[2] == self.embed_dim
260
+ B = tokens.shape[0]
261
+ if self.num_cls_tokens > 0:
262
+ class_tokens = self.cls_token.expand(
263
+ B, -1, -1
264
+ ) # stole class_tokens impl from Phil Wang, thanks
265
+ tokens = torch.cat((class_tokens, tokens), dim=1)
266
+ if self.use_pos_embed:
267
+ pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
268
+ tokens = tokens + pos_embed
269
+ if self.use_type_embed:
270
+ tokens = tokens + self.type_embed.expand(B, -1, -1)
271
+ return tokens
272
+
273
+ def forward(self, vision=None, depth=None, patch_mask=None):
274
+ if patch_mask is not None:
275
+ raise NotImplementedError()
276
+
277
+ if vision is not None:
278
+ vision_tokens = self.tokenize_input_and_cls_pos(
279
+ vision, self.rgbt_stem, patch_mask
280
+ )
281
+
282
+ if depth is not None:
283
+ depth_tokens = self.tokenize_input_and_cls_pos(
284
+ depth, self.depth_stem, patch_mask
285
+ )
286
+
287
+ # aggregate tokens
288
+ if vision is not None and depth is not None:
289
+ final_tokens = vision_tokens + depth_tokens
290
+ else:
291
+ final_tokens = vision_tokens if vision is not None else depth_tokens
292
+ return_dict = {
293
+ "trunk": {
294
+ "tokens": final_tokens,
295
+ },
296
+ "head": {},
297
+ }
298
+ return return_dict
299
+
300
+
301
+ class AudioPreprocessor(RGBDTPreprocessor):
302
+ def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
303
+ super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
304
+
305
+ def forward(self, audio=None):
306
+ return super().forward(vision=audio)
307
+
308
+
309
+ class ThermalPreprocessor(RGBDTPreprocessor):
310
+ def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
311
+ super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
312
+
313
+ def forward(self, thermal=None):
314
+ return super().forward(vision=thermal)
315
+
316
+
317
+ def build_causal_attention_mask(context_length):
318
+ # lazily create causal attention mask, with full attention between the vision tokens
319
+ # pytorch uses additive attention mask; fill with -inf
320
+ mask = torch.empty(context_length, context_length, requires_grad=False)
321
+ mask.fill_(float("-inf"))
322
+ mask.triu_(1) # zero out the lower diagonal
323
+ return mask
324
+
325
+
326
+ class TextPreprocessor(VerboseNNModule):
327
+ def __init__(
328
+ self,
329
+ vocab_size: int,
330
+ context_length: int,
331
+ embed_dim: int,
332
+ causal_masking: bool,
333
+ supply_seq_len_to_head: bool = True,
334
+ num_cls_tokens: int = 0,
335
+ init_param_style: str = "openclip",
336
+ ) -> None:
337
+ super().__init__()
338
+ self.vocab_size = vocab_size
339
+ self.context_length = context_length
340
+ self.token_embedding = nn.Embedding(vocab_size, embed_dim)
341
+ self.pos_embed = nn.Parameter(
342
+ torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
343
+ )
344
+ self.causal_masking = causal_masking
345
+ if self.causal_masking:
346
+ mask = build_causal_attention_mask(self.context_length)
347
+ # register the mask as a buffer so it can be moved to the right device
348
+ self.register_buffer("mask", mask)
349
+
350
+ self.supply_seq_len_to_head = supply_seq_len_to_head
351
+ self.num_cls_tokens = num_cls_tokens
352
+ self.embed_dim = embed_dim
353
+ if num_cls_tokens > 0:
354
+ assert self.causal_masking is False, "Masking + CLS token isn't implemented"
355
+ self.cls_token = nn.Parameter(
356
+ torch.zeros(1, self.num_cls_tokens, embed_dim)
357
+ )
358
+
359
+ self.init_parameters(init_param_style)
360
+
361
+ @torch.no_grad()
362
+ def init_parameters(self, init_param_style="openclip"):
363
+ # OpenCLIP style initialization
364
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
365
+ nn.init.normal_(self.pos_embed, std=0.01)
366
+
367
+ if init_param_style == "openclip":
368
+ # OpenCLIP style initialization
369
+ scale = self.embed_dim**-0.5
370
+ if self.num_cls_tokens > 0:
371
+ nn.init.normal_(self.cls_token)
372
+ self.cls_token *= scale
373
+ elif init_param_style == "vit":
374
+ self.cls_token.data.fill_(0)
375
+ else:
376
+ raise ValueError(f"Unknown init {init_param_style}")
377
+
378
+ def forward(self, text):
379
+ # text tokens are of shape B x L x D
380
+ text_tokens = self.token_embedding(text)
381
+ # concat CLS tokens if any
382
+ if self.num_cls_tokens > 0:
383
+ B = text_tokens.shape[0]
384
+ class_tokens = self.cls_token.expand(
385
+ B, -1, -1
386
+ ) # stole class_tokens impl from Phil Wang, thanks
387
+ text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
388
+ text_tokens = text_tokens + self.pos_embed
389
+ return_dict = {
390
+ "trunk": {
391
+ "tokens": text_tokens,
392
+ },
393
+ "head": {},
394
+ }
395
+ # Compute sequence length after adding CLS tokens
396
+ if self.supply_seq_len_to_head:
397
+ text_lengths = text.argmax(dim=-1)
398
+ return_dict["head"] = {
399
+ "seq_len": text_lengths,
400
+ }
401
+ if self.causal_masking:
402
+ return_dict["trunk"].update({"attn_mask": self.mask})
403
+ return return_dict
404
+
405
+
406
+ class Im2Video(nn.Module):
407
+ """Convert an image into a trivial video."""
408
+
409
+ def __init__(self, time_dim=2):
410
+ super().__init__()
411
+ self.time_dim = time_dim
412
+
413
+ def forward(self, x):
414
+ if x.ndim == 4:
415
+ # B, C, H, W -> B, C, T, H, W
416
+ return x.unsqueeze(self.time_dim)
417
+ elif x.ndim == 5:
418
+ return x
419
+ else:
420
+ raise ValueError(f"Dimension incorrect {x.shape}")
421
+
422
+
423
+ class PadIm2Video(Im2Video):
424
+ def __init__(self, ntimes, pad_type, time_dim=2):
425
+ super().__init__(time_dim=time_dim)
426
+ assert ntimes > 0
427
+ assert pad_type in ["zero", "repeat"]
428
+ self.ntimes = ntimes
429
+ self.pad_type = pad_type
430
+
431
+ def forward(self, x):
432
+ x = super().forward(x)
433
+ if x.shape[self.time_dim] == 1:
434
+ if self.pad_type == "repeat":
435
+ new_shape = [1] * len(x.shape)
436
+ new_shape[self.time_dim] = self.ntimes
437
+ x = x.repeat(new_shape)
438
+ elif self.pad_type == "zero":
439
+ padarg = [0, 0] * len(x.shape)
440
+ padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
441
+ x = nn.functional.pad(x, padarg)
442
+ return x
443
+
444
+
445
+ # Modified from github.com/openai/CLIP
446
+ @lru_cache()
447
+ def bytes_to_unicode():
448
+ """
449
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
450
+ The reversible bpe codes work on unicode strings.
451
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
452
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
453
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
454
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
455
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
456
+ """
457
+ bs = (
458
+ list(range(ord("!"), ord("~") + 1))
459
+ + list(range(ord("¡"), ord("¬") + 1))
460
+ + list(range(ord("®"), ord("ÿ") + 1))
461
+ )
462
+ cs = bs[:]
463
+ n = 0
464
+ for b in range(2**8):
465
+ if b not in bs:
466
+ bs.append(b)
467
+ cs.append(2**8 + n)
468
+ n += 1
469
+ cs = [chr(n) for n in cs]
470
+ return dict(zip(bs, cs))
471
+
472
+
473
+ def get_pairs(word):
474
+ """Return set of symbol pairs in a word.
475
+ Word is represented as tuple of symbols (symbols being variable-length strings).
476
+ """
477
+ pairs = set()
478
+ prev_char = word[0]
479
+ for char in word[1:]:
480
+ pairs.add((prev_char, char))
481
+ prev_char = char
482
+ return pairs
483
+
484
+
485
+ def basic_clean(text):
486
+ text = ftfy.fix_text(text)
487
+ text = html.unescape(html.unescape(text))
488
+ return text.strip()
489
+
490
+
491
+ def whitespace_clean(text):
492
+ text = re.sub(r"\s+", " ", text)
493
+ text = text.strip()
494
+ return text
495
+
496
+
497
+ class SimpleTokenizer(object):
498
+ def __init__(self, bpe_path: str, context_length=77):
499
+ self.byte_encoder = bytes_to_unicode()
500
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
501
+
502
+ with g_pathmgr.open(bpe_path, "rb") as fh:
503
+ bpe_bytes = io.BytesIO(fh.read())
504
+ merges: List[str] = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
505
+ merges = merges[1 : 49152 - 256 - 2 + 1]
506
+ merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges]
507
+ vocab = list(bytes_to_unicode().values())
508
+ vocab = vocab + [v + "</w>" for v in vocab]
509
+ for merge in merges:
510
+ vocab.append("".join(merge))
511
+ vocab.extend(["<|startoftext|>", "<|endoftext|>"])
512
+ self.encoder = dict(zip(vocab, range(len(vocab))))
513
+ self.decoder = {v: k for k, v in self.encoder.items()}
514
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
515
+ self.cache = {
516
+ "<|startoftext|>": "<|startoftext|>",
517
+ "<|endoftext|>": "<|endoftext|>",
518
+ }
519
+ self.pat = re.compile(
520
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
521
+ re.IGNORECASE,
522
+ )
523
+ self.context_length = context_length
524
+
525
+ def bpe(self, token):
526
+ if token in self.cache:
527
+ return self.cache[token]
528
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
529
+ pairs = get_pairs(word)
530
+
531
+ if not pairs:
532
+ return token + "</w>"
533
+
534
+ while True:
535
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
536
+ if bigram not in self.bpe_ranks:
537
+ break
538
+ first, second = bigram
539
+ new_word = []
540
+ i = 0
541
+ while i < len(word):
542
+ try:
543
+ j = word.index(first, i)
544
+ new_word.extend(word[i:j])
545
+ i = j
546
+ except:
547
+ new_word.extend(word[i:])
548
+ break
549
+
550
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
551
+ new_word.append(first + second)
552
+ i += 2
553
+ else:
554
+ new_word.append(word[i])
555
+ i += 1
556
+ new_word = tuple(new_word)
557
+ word = new_word
558
+ if len(word) == 1:
559
+ break
560
+ else:
561
+ pairs = get_pairs(word)
562
+ word = " ".join(word)
563
+ self.cache[token] = word
564
+ return word
565
+
566
+ def encode(self, text):
567
+ bpe_tokens = []
568
+ text = whitespace_clean(basic_clean(text)).lower()
569
+ for token in re.findall(self.pat, text):
570
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
571
+ bpe_tokens.extend(
572
+ self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
573
+ )
574
+ return bpe_tokens
575
+
576
+ def decode(self, tokens):
577
+ text = "".join([self.decoder[token] for token in tokens])
578
+ text = (
579
+ bytearray([self.byte_decoder[c] for c in text])
580
+ .decode("utf-8", errors="replace")
581
+ .replace("</w>", " ")
582
+ )
583
+ return text
584
+
585
+ def __call__(self, texts, context_length=None):
586
+ if not context_length:
587
+ context_length = self.context_length
588
+
589
+ if isinstance(texts, str):
590
+ texts = [texts]
591
+
592
+ sot_token = self.encoder["<|startoftext|>"]
593
+ eot_token = self.encoder["<|endoftext|>"]
594
+ all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
595
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
596
+
597
+ for i, tokens in enumerate(all_tokens):
598
+ tokens = tokens[:context_length]
599
+ result[i, : len(tokens)] = torch.tensor(tokens)
600
+
601
+ if len(result) == 1:
602
+ return result[0]
603
+ return result
604
+
605
+
606
+ class IMUPreprocessor(VerboseNNModule):
607
+ def __init__(
608
+ self,
609
+ kernel_size: int,
610
+ imu_stem: PatchEmbedGeneric,
611
+ embed_dim: int,
612
+ img_size: Tuple = (6, 2000),
613
+ num_cls_tokens: int = 1,
614
+ pos_embed_fn: Optional[Callable] = None,
615
+ init_param_style: str = "openclip",
616
+ ) -> None:
617
+ super().__init__()
618
+ self.imu_stem = imu_stem
619
+ self.embed_dim = embed_dim
620
+ self.use_pos_embed = pos_embed_fn is not None
621
+ self.num_cls_tokens = num_cls_tokens
622
+ self.kernel_size = kernel_size
623
+ self.pos_embed = nn.Parameter(
624
+ torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
625
+ )
626
+
627
+ if self.num_cls_tokens > 0:
628
+ self.cls_token = nn.Parameter(
629
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
630
+ )
631
+
632
+ self.init_parameters(init_param_style)
633
+
634
+ @torch.no_grad()
635
+ def init_parameters(self, init_param_style):
636
+ nn.init.normal_(self.pos_embed, std=0.01)
637
+
638
+ if init_param_style == "openclip":
639
+ # OpenCLIP style initialization
640
+ scale = self.embed_dim**-0.5
641
+
642
+ if self.num_cls_tokens > 0:
643
+ nn.init.normal_(self.cls_token)
644
+ self.cls_token *= scale
645
+ elif init_param_style == "vit":
646
+ self.cls_token.data.fill_(0)
647
+ else:
648
+ raise ValueError(f"Unknown init {init_param_style}")
649
+
650
+ def tokenize_input_and_cls_pos(self, input, stem):
651
+ # tokens is of shape B x L x D
652
+ tokens = stem.norm_layer(stem.proj(input))
653
+ assert tokens.ndim == 3
654
+ assert tokens.shape[2] == self.embed_dim
655
+ B = tokens.shape[0]
656
+ if self.num_cls_tokens > 0:
657
+ class_tokens = self.cls_token.expand(
658
+ B, -1, -1
659
+ ) # stole class_tokens impl from Phil Wang, thanks
660
+ tokens = torch.cat((class_tokens, tokens), dim=1)
661
+ if self.use_pos_embed:
662
+ tokens = tokens + self.pos_embed
663
+ return tokens
664
+
665
+ def forward(self, imu):
666
+ # Patchify
667
+ imu = imu.unfold(
668
+ -1,
669
+ self.kernel_size,
670
+ self.kernel_size,
671
+ ).permute(0, 2, 1, 3)
672
+ imu = imu.reshape(imu.size(0), imu.size(1), -1)
673
+
674
+ imu_tokens = self.tokenize_input_and_cls_pos(
675
+ imu,
676
+ self.imu_stem,
677
+ )
678
+
679
+ return_dict = {
680
+ "trunk": {
681
+ "tokens": imu_tokens,
682
+ },
683
+ "head": {},
684
+ }
685
+ return return_dict
model/ImageBind/models/transformer.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ # Code modified from
9
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
10
+ # https://github.com/facebookresearch/deit/blob/main/models.py
11
+ # and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
12
+
13
+
14
+ from functools import partial
15
+ from typing import Callable, List, Optional
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint as checkpoint
20
+ from timm.models.layers import DropPath, trunc_normal_
21
+
22
+
23
+ class Attention(nn.Module):
24
+ def __init__(
25
+ self,
26
+ dim,
27
+ num_heads=8,
28
+ qkv_bias=False,
29
+ qk_scale=None,
30
+ attn_drop=0.0,
31
+ proj_drop=0.0,
32
+ ):
33
+ super().__init__()
34
+ self.num_heads = num_heads
35
+ head_dim = dim // num_heads
36
+ # NOTE scale factor was wrong in my original version,
37
+ # can set manually to be compat with prev weights
38
+ self.scale = qk_scale or head_dim**-0.5
39
+
40
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
41
+ self.attn_drop = nn.Dropout(attn_drop)
42
+ self.proj = nn.Linear(dim, dim)
43
+ self.proj_drop = nn.Dropout(proj_drop)
44
+
45
+ def forward(self, x):
46
+ B, N, C = x.shape
47
+ qkv = (
48
+ self.qkv(x)
49
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
50
+ .permute(2, 0, 3, 1, 4)
51
+ )
52
+ q, k, v = (
53
+ qkv[0],
54
+ qkv[1],
55
+ qkv[2],
56
+ ) # make torchscript happy (cannot use tensor as tuple)
57
+
58
+ attn = (q @ k.transpose(-2, -1)) * self.scale
59
+ attn = attn.softmax(dim=-1)
60
+ attn = self.attn_drop(attn)
61
+
62
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
63
+ x = self.proj(x)
64
+ x = self.proj_drop(x)
65
+ return x
66
+
67
+
68
+ class Mlp(nn.Module):
69
+ def __init__(
70
+ self,
71
+ in_features,
72
+ hidden_features=None,
73
+ out_features=None,
74
+ act_layer=nn.GELU,
75
+ drop=0.0,
76
+ ):
77
+ super().__init__()
78
+ out_features = out_features or in_features
79
+ hidden_features = hidden_features or in_features
80
+ self.fc1 = nn.Linear(in_features, hidden_features)
81
+ self.act = act_layer()
82
+ self.fc2 = nn.Linear(hidden_features, out_features)
83
+ self.drop = nn.Dropout(drop)
84
+
85
+ def forward(self, x):
86
+ x = self.fc1(x)
87
+ x = self.act(x)
88
+ x = self.drop(x)
89
+ x = self.fc2(x)
90
+ x = self.drop(x)
91
+ return x
92
+
93
+
94
+ class MultiheadAttention(nn.MultiheadAttention):
95
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
96
+ return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
97
+
98
+
99
+ class ViTAttention(Attention):
100
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
101
+ assert attn_mask is None
102
+ return super().forward(x)
103
+
104
+
105
+ class BlockWithMasking(nn.Module):
106
+ def __init__(
107
+ self,
108
+ dim: int,
109
+ attn_target: Callable,
110
+ mlp_ratio: int = 4,
111
+ act_layer: Callable = nn.GELU,
112
+ norm_layer: Callable = nn.LayerNorm,
113
+ ffn_dropout_rate: float = 0.0,
114
+ drop_path: float = 0.0,
115
+ layer_scale_type: Optional[str] = None,
116
+ layer_scale_init_value: float = 1e-4,
117
+ ):
118
+ super().__init__()
119
+
120
+ assert not isinstance(
121
+ attn_target, nn.Module
122
+ ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
123
+ self.attn = attn_target()
124
+ if drop_path > 0.0:
125
+ self.drop_path = DropPath(drop_path)
126
+ else:
127
+ self.drop_path = nn.Identity()
128
+ self.norm_1 = norm_layer(dim)
129
+ mlp_hidden_dim = int(mlp_ratio * dim)
130
+ self.mlp = Mlp(
131
+ in_features=dim,
132
+ hidden_features=mlp_hidden_dim,
133
+ act_layer=act_layer,
134
+ drop=ffn_dropout_rate,
135
+ )
136
+ self.norm_2 = norm_layer(dim)
137
+ self.layer_scale_type = layer_scale_type
138
+ if self.layer_scale_type is not None:
139
+ assert self.layer_scale_type in [
140
+ "per_channel",
141
+ "scalar",
142
+ ], f"Found Layer scale type {self.layer_scale_type}"
143
+ if self.layer_scale_type == "per_channel":
144
+ # one gamma value per channel
145
+ gamma_shape = [1, 1, dim]
146
+ elif self.layer_scale_type == "scalar":
147
+ # single gamma value for all channels
148
+ gamma_shape = [1, 1, 1]
149
+ # two gammas: for each part of the fwd in the encoder
150
+ self.layer_scale_gamma1 = nn.Parameter(
151
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
152
+ requires_grad=True,
153
+ )
154
+ self.layer_scale_gamma2 = nn.Parameter(
155
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
156
+ requires_grad=True,
157
+ )
158
+
159
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
160
+ if self.layer_scale_type is None:
161
+ x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
162
+ x = x + self.drop_path(self.mlp(self.norm_2(x)))
163
+ else:
164
+ x = (
165
+ x
166
+ + self.drop_path(self.attn(self.norm_1(x), attn_mask))
167
+ # * self.layer_scale_gamma1
168
+ )
169
+ x = x + self.drop_path(self.mlp(self.norm_2(x))) # * self.layer_scale_gamma2
170
+ return x
171
+
172
+
173
+ _LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
174
+
175
+
176
+ class SimpleTransformer(nn.Module):
177
+ def __init__(
178
+ self,
179
+ attn_target: Callable,
180
+ embed_dim: int,
181
+ num_blocks: int,
182
+ block: Callable = BlockWithMasking,
183
+ pre_transformer_layer: Optional[Callable] = None,
184
+ post_transformer_layer: Optional[Callable] = None,
185
+ drop_path_rate: float = 0.0,
186
+ drop_path_type: str = "progressive",
187
+ norm_layer: Callable = _LAYER_NORM,
188
+ mlp_ratio: int = 4,
189
+ ffn_dropout_rate: float = 0.0,
190
+ layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar"
191
+ layer_scale_init_value: float = 1e-4, # from cait; float
192
+ weight_init_style: str = "jax", # possible values jax or pytorch
193
+ ):
194
+ """
195
+ Simple Transformer with the following features
196
+ 1. Supports masked attention
197
+ 2. Supports DropPath
198
+ 3. Supports LayerScale
199
+ 4. Supports Dropout in Attention and FFN
200
+ 5. Makes few assumptions about the input except that it is a Tensor
201
+ """
202
+ super().__init__()
203
+ self.pre_transformer_layer = pre_transformer_layer
204
+ if drop_path_type == "progressive":
205
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
206
+ elif drop_path_type == "uniform":
207
+ dpr = [drop_path_rate for i in range(num_blocks)]
208
+ else:
209
+ raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
210
+
211
+ self.blocks = nn.Sequential(
212
+ *[
213
+ block(
214
+ dim=embed_dim,
215
+ attn_target=attn_target,
216
+ mlp_ratio=mlp_ratio,
217
+ ffn_dropout_rate=ffn_dropout_rate,
218
+ drop_path=dpr[i],
219
+ norm_layer=norm_layer,
220
+ layer_scale_type=layer_scale_type,
221
+ layer_scale_init_value=layer_scale_init_value,
222
+ )
223
+ for i in range(num_blocks)
224
+ ]
225
+ )
226
+ self.post_transformer_layer = post_transformer_layer
227
+ self.weight_init_style = weight_init_style
228
+ self.apply(self._init_weights)
229
+
230
+ def _init_weights(self, m):
231
+ if isinstance(m, nn.Linear):
232
+ if self.weight_init_style == "jax":
233
+ # Based on MAE and official Jax ViT implementation
234
+ torch.nn.init.xavier_uniform_(m.weight)
235
+ elif self.weight_init_style == "pytorch":
236
+ # PyTorch ViT uses trunc_normal_
237
+ trunc_normal_(m.weight, std=0.02)
238
+
239
+ if m.bias is not None:
240
+ nn.init.constant_(m.bias, 0)
241
+ elif isinstance(m, (nn.LayerNorm)):
242
+ nn.init.constant_(m.bias, 0)
243
+ nn.init.constant_(m.weight, 1.0)
244
+
245
+ def forward(
246
+ self,
247
+ tokens: torch.Tensor,
248
+ attn_mask: torch.Tensor = None,
249
+ use_checkpoint: bool = False,
250
+ checkpoint_every_n: int = 1,
251
+ checkpoint_blk_ids: Optional[List[int]] = None,
252
+ # return_multi_layer_outputs = False,
253
+ out_layers = []
254
+ ):
255
+
256
+ """
257
+ Inputs
258
+ - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
259
+ - attn: mask of shape L x L
260
+
261
+ Output
262
+ - x: data of shape N x L x D (or L x N x D depending on the attention implementation)
263
+ """
264
+ out_tokens = []
265
+
266
+ if self.pre_transformer_layer:
267
+ tokens = self.pre_transformer_layer(tokens)
268
+ if use_checkpoint and checkpoint_blk_ids is None:
269
+ checkpoint_blk_ids = [
270
+ blk_id
271
+ for blk_id in range(len(self.blocks))
272
+ if blk_id % checkpoint_every_n == 0
273
+ ]
274
+ if checkpoint_blk_ids:
275
+ checkpoint_blk_ids = set(checkpoint_blk_ids)
276
+ for blk_id, blk in enumerate(self.blocks):
277
+ if use_checkpoint and blk_id in checkpoint_blk_ids:
278
+ tokens = checkpoint.checkpoint(
279
+ blk, tokens, attn_mask, use_reentrant=False
280
+ )
281
+ else:
282
+ tokens = blk(tokens, attn_mask=attn_mask)
283
+ if blk_id in out_layers:
284
+ out_tokens.append(tokens)
285
+ if self.post_transformer_layer:
286
+ tokens = self.post_transformer_layer(tokens)
287
+ return tokens, out_tokens
model/ImageBind/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torchvision==0.14.0
3
+ torchaudio==0.13.0
4
+ pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d
5
+ timm==0.6.7
6
+ ftfy
7
+ regex
8
+ einops
9
+ fvcore
10
+ decord==0.6.0
model/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .agent import DeepSpeedAgent
2
+ from .openllama import OpenLLAMAPEFTModel
3
+ # from .openllama_CLIP import OpenLLAMAPEFTModel_CLIP
4
+ from .ImageBind import models
5
+
6
+ def load_model(args):
7
+ agent_name = args['models'][args['model']]['agent_name']
8
+ model_name = args['models'][args['model']]['model_name']
9
+ model = globals()[model_name](**args)
10
+ agent = globals()[agent_name](model, args)
11
+ return agent
model/agent.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ class DeepSpeedAgent:
4
+
5
+ def __init__(self, model, args):
6
+ super(DeepSpeedAgent, self).__init__()
7
+ self.args = args
8
+ self.model = model
9
+ self.load_stage_1_parameters(args["delta_ckpt_path"])
10
+
11
+
12
+
13
+ for name, param in self.model.named_parameters():
14
+ param.requires_grad = False
15
+
16
+ for name, param in self.model.image_decoder.named_parameters():
17
+ param.requires_grad = True
18
+
19
+ for name, param in self.model.prompt_learner.named_parameters():
20
+ param.requires_grad = True
21
+
22
+
23
+
24
+
25
+ # load config parameters of deepspeed
26
+ ds_params = json.load(open(self.args['ds_config_path']))
27
+ ds_params['scheduler']['params']['total_num_steps'] = self.args['total_steps']
28
+ ds_params['scheduler']['params']['warmup_num_steps'] = max(10, int(self.args['total_steps'] * self.args['warmup_rate']))
29
+ self.ds_engine, self.optimizer, _ , _ = deepspeed.initialize(
30
+ model=self.model,
31
+ model_parameters=self.model.parameters(),
32
+ config_params=ds_params,
33
+ dist_init_required=True,
34
+ args=types.SimpleNamespace(**args)
35
+ )
36
+
37
+ @torch.no_grad()
38
+ def predict(self, batch):
39
+ self.model.eval()
40
+ string = self.model.generate_one_sample(batch)
41
+ return string
42
+
43
+ def train_model(self, batch, current_step=0, pbar=None):
44
+ self.ds_engine.module.train()
45
+ loss, mle_acc = self.ds_engine(batch)
46
+
47
+ self.ds_engine.backward(loss)
48
+ self.ds_engine.step()
49
+ pbar.set_description(f'[!] loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc*100, 2)}')
50
+ pbar.update(1)
51
+ if self.args['local_rank'] == 0 and self.args['log_path'] and current_step % self.args['logging_step'] == 0:
52
+ elapsed = pbar.format_dict['elapsed']
53
+ rate = pbar.format_dict['rate']
54
+ remaining = (pbar.total - pbar.n) / rate if rate and pbar.total else 0
55
+ remaining = str(datetime.timedelta(seconds=remaining))
56
+ logging.info(f'[!] progress: {round(pbar.n/pbar.total, 5)}; remaining time: {remaining}; loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc*100, 2)}')
57
+
58
+ mle_acc *= 100
59
+ return mle_acc
60
+
61
+ def save_model(self, path, current_step):
62
+ # only save trainable model parameters
63
+ param_grad_dic = {
64
+ k: v.requires_grad for (k, v) in self.ds_engine.module.named_parameters()
65
+ }
66
+ state_dict = self.ds_engine.module.state_dict()
67
+ checkpoint = OrderedDict()
68
+ for k, v in self.ds_engine.module.named_parameters():
69
+ if v.requires_grad:
70
+ print(k)
71
+ checkpoint[k] = v
72
+ torch.save(checkpoint, f'{path}/pytorch_model.pt')
73
+ # save tokenizer
74
+ self.model.llama_tokenizer.save_pretrained(path)
75
+ # save configuration
76
+ self.model.llama_model.config.save_pretrained(path)
77
+ print(f'[!] save model into {path}')
78
+
79
+ def load_stage_1_parameters(self, path):
80
+ delta_ckpt = torch.load(path, map_location=torch.device('cpu'))
81
+ self.model.load_state_dict(delta_ckpt, strict=False)
model/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
+
model/openllama.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+ import torch.nn.functional as F
3
+ from .ImageBind import *
4
+ from .ImageBind import data
5
+ from .modeling_llama import LlamaForCausalLM
6
+ from .AnomalyGPT_models import LinearLayer, PromptLearner
7
+ from transformers import StoppingCriteria, StoppingCriteriaList
8
+ from utils.loss import FocalLoss, BinaryDiceLoss
9
+ import kornia as K
10
+
11
+ import torch
12
+ from torch.nn.utils import rnn
13
+
14
+ CLASS_NAMES = ['bottle', 'cable', 'capsule', 'carpet', 'grid', 'hazelnut', 'leather', 'metal nut', 'pill', 'screw', 'tile', 'toothbrush', 'transistor', 'wood', 'zipper', 'object',
15
+ 'candle', 'cashew', 'chewinggum', 'fryum', 'macaroni', 'pcb', 'pipe fryum']
16
+
17
+ prompt_normal = ['{}', 'flawless {}', 'perfect {}', 'unblemished {}', '{} without flaw', '{} without defect', '{} without damage']
18
+ prompt_abnormal = ['damaged {}', 'broken {}', '{} with flaw', '{} with defect', '{} with damage']
19
+
20
+ prompt_state = [prompt_normal, prompt_abnormal]
21
+ prompt_templates = ['a photo of a {}.', 'a photo of the {}.']
22
+ # prompt_templates = [
23
+ # 'a cropped photo of the {}.', 'a cropped photo of a {}.', 'a close-up photo of a {}.', 'a close-up photo of the {}.',
24
+ # 'a bright photo of the {}.', 'a bright photo of a {}.', 'a dark photo of a {}.', 'a dark photo of the {}.',
25
+ # 'a dark photo of the {}.', 'a dark photo of a {}.', 'a jpeg corrupted photo of a {}.', 'a jpeg corrupted photo of the {}.',
26
+ # 'a blurry photo of the {}.', 'a blurry photo of a {}.', 'a photo of a {}.', 'a photo of the {}.',
27
+ # 'a photo of the small {}.', 'a photo of a small {}.', 'a photo of the large {}.', 'a photo of a large {}.',
28
+ # 'a photo of the {} for visual insprction.', 'a photo of a {} for visual insprction.',
29
+ # 'a photo of the {} for anomaly detection.', 'a photo of a {} for anomaly detection.'
30
+ # ]
31
+ objs = ['bottle', 'cable', 'capsule', 'carpet', 'grid', 'hazelnut', 'leather', 'metal nut', 'pill', 'screw', 'tile', 'toothbrush', 'transistor', 'wood', 'zipper', 'object',
32
+ 'candle', 'cashew', 'chewinggum', 'fryum', 'macaroni', 'pcb', 'pipe fryum', 'macaroni1', 'macaroni2','pcb1', 'pcb2', 'pcb3', 'pcb4', 'capsules']
33
+
34
+ prompt_sentences = {}
35
+
36
+ for obj in objs:
37
+ prompt_sentence_obj = []
38
+ for i in range(len(prompt_state)):
39
+ prompted_state = [state.format(obj) for state in prompt_state[i]]
40
+ prompted_sentence = []
41
+ for s in prompted_state:
42
+ for template in prompt_templates:
43
+ prompted_sentence.append(template.format(s))
44
+ prompted_sentence = data.load_and_transform_text(prompted_sentence, torch.device('cpu'))#torch.cuda.current_device())
45
+ prompt_sentence_obj.append(prompted_sentence)
46
+ prompt_sentences[obj] = prompt_sentence_obj
47
+
48
+
49
+
50
+ def encode_text_with_prompt_ensemble(model, obj, device):
51
+
52
+ global prompt_sentences
53
+ normal_sentences = []
54
+ abnormal_sentences = []
55
+ for idx in range(len(obj)):
56
+ sentence = prompt_sentences[obj[idx].replace('_', ' ')]
57
+ normal_sentences.append(sentence[0])
58
+ abnormal_sentences.append(sentence[1])
59
+
60
+ normal_sentences = torch.cat(normal_sentences).to(device)
61
+ abnormal_sentences = torch.cat(abnormal_sentences).to(device)
62
+
63
+ class_embeddings_normal = model({ModalityType.TEXT: normal_sentences})[ModalityType.TEXT][0]
64
+ class_embeddings_abnormal = model({ModalityType.TEXT: abnormal_sentences})[ModalityType.TEXT][0]
65
+ # class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
66
+
67
+ class_embeddings_normal = class_embeddings_normal.reshape((len(obj), len(prompt_templates) * len(prompt_normal), 1024))
68
+ class_embeddings_normal = class_embeddings_normal.mean(dim=1, keepdim=True)
69
+ class_embeddings_normal = class_embeddings_normal / class_embeddings_normal.norm(dim=-1, keepdim=True)
70
+
71
+ class_embeddings_abnormal = class_embeddings_abnormal.reshape((len(obj), len(prompt_templates) * len(prompt_abnormal), 1024))
72
+ class_embeddings_abnormal = class_embeddings_abnormal.mean(dim=1, keepdim=True)
73
+ class_embeddings_abnormal = class_embeddings_abnormal / class_embeddings_abnormal.norm(dim=-1, keepdim=True)
74
+
75
+ text_features = torch.cat([class_embeddings_normal, class_embeddings_abnormal], dim=1)
76
+
77
+ return text_features
78
+
79
+
80
+
81
+ class StoppingCriteriaSub(StoppingCriteria):
82
+
83
+ def __init__(self, stops = [], encounters=1):
84
+ super().__init__()
85
+ self.stops = stops
86
+ self.ENCOUNTERS = encounters
87
+
88
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
89
+ stop_count = 0
90
+ for stop in self.stops:
91
+ stop_count = (stop == input_ids[0]).sum().item()
92
+ if stop_count >= self.ENCOUNTERS:
93
+ return True
94
+ return False
95
+
96
+ def build_one_instance(tokenizer, conversation):
97
+ text_list = []
98
+ turn_num = len(conversation)
99
+ input_ids, target_ids = [], []
100
+ for i in range(turn_num):
101
+ turn = conversation[i]
102
+ role = turn['from']
103
+ if i == 0: # the first human turn
104
+ assert role == 'human'
105
+ text = turn['value'] + '\n### Assistant:'
106
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
107
+ input_ids += one_input_id
108
+ target_ids += [-100]*len(one_input_id) # do not perform loss regression on human prompt
109
+ else:
110
+ if role == 'human':
111
+ text = 'Human: ' + turn['value'] + '\n### Assistant:'
112
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
113
+ input_ids += one_input_id
114
+ target_ids += [-100]*len(one_input_id)
115
+ elif role == 'gpt':
116
+ text = turn['value'] + '\n###'
117
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
118
+ input_ids += one_input_id
119
+ target_ids += one_input_id
120
+ else:
121
+ raise Exception('Wrong Role!!!')
122
+ text_list.append(text)
123
+ assert len(input_ids) == len(target_ids)
124
+ return text_list, input_ids, target_ids
125
+
126
+ def process_batch_instance(tokenizer, batch_of_conversations, max_tgt_len):
127
+ batch_input_ids, batch_target_ids = [], []
128
+ for conversation in batch_of_conversations:
129
+ _, one_input_ids, one_target_ids = build_one_instance(tokenizer, conversation)
130
+ batch_input_ids.append(torch.LongTensor(one_input_ids))
131
+ batch_target_ids.append(torch.LongTensor(one_target_ids))
132
+ input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
133
+ target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
134
+ assert input_ids.size() == target_ids.size()
135
+ input_ids = input_ids[:,:max_tgt_len]
136
+ target_ids = target_ids[:,:max_tgt_len]
137
+ attention_mask = input_ids.ne(tokenizer.pad_token_id)
138
+ assert attention_mask.size() == input_ids.size()
139
+ return input_ids, target_ids, attention_mask.long()
140
+
141
+ def find_first_file_in_directory(directory_path):
142
+ try:
143
+ file_list = os.listdir(directory_path)
144
+ for item in file_list:
145
+ item_path = os.path.join(directory_path, item)
146
+ if os.path.isfile(item_path):
147
+ return item_path
148
+ return None
149
+
150
+ except OSError as e:
151
+ print(f"Error while accessing directory: {e}")
152
+ return None
153
+
154
+
155
+ PROMPT_START = '### Human: <Img>'
156
+ class OpenLLAMAPEFTModel(nn.Module):
157
+
158
+ '''LoRA for LLaMa model'''
159
+
160
+ def __init__(self, **args):
161
+ super(OpenLLAMAPEFTModel, self).__init__()
162
+ self.args = args
163
+ imagebind_ckpt_path = args['imagebind_ckpt_path']
164
+ vicuna_ckpt_path = args['vicuna_ckpt_path']
165
+ max_tgt_len = args['max_tgt_len']
166
+ stage = args['stage']
167
+
168
+ print (f'Initializing visual encoder from {imagebind_ckpt_path} ...')
169
+
170
+ self.visual_encoder, self.visual_hidden_size = imagebind_model.imagebind_huge(args)
171
+ imagebind_ckpt = torch.load(imagebind_ckpt_path, map_location=torch.device('cpu'))
172
+ self.visual_encoder.load_state_dict(imagebind_ckpt, strict=True)
173
+
174
+ self.iter = 0
175
+
176
+ self.image_decoder = LinearLayer(1280, 1024, 4)
177
+
178
+ self.prompt_learner = PromptLearner(1, 4096)
179
+
180
+ self.loss_focal = FocalLoss()
181
+ self.loss_dice = BinaryDiceLoss()
182
+
183
+
184
+ # free vision encoder
185
+ for name, param in self.visual_encoder.named_parameters():
186
+ param.requires_grad = False
187
+ self.visual_encoder.eval()
188
+ print ('Visual encoder initialized.')
189
+
190
+ print (f'Initializing language decoder from {vicuna_ckpt_path} ...')
191
+
192
+ # add the lora module
193
+ peft_config = LoraConfig(
194
+ task_type=TaskType.CAUSAL_LM,
195
+ inference_mode=False,
196
+ r=self.args['lora_r'],
197
+ lora_alpha=self.args['lora_alpha'],
198
+ lora_dropout=self.args['lora_dropout'],
199
+ target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj']
200
+ )
201
+
202
+ self.llama_model = LlamaForCausalLM.from_pretrained(vicuna_ckpt_path)
203
+ self.llama_model = get_peft_model(self.llama_model, peft_config)
204
+ self.llama_model.print_trainable_parameters()
205
+
206
+ self.llama_tokenizer = LlamaTokenizer.from_pretrained(vicuna_ckpt_path, use_fast=False)
207
+ self.llama_tokenizer.pad_token = self.llama_tokenizer.eos_token
208
+ self.llama_tokenizer.padding_side = "right"
209
+ print ('Language decoder initialized.')
210
+
211
+ self.llama_proj = nn.Linear(
212
+ self.visual_hidden_size, self.llama_model.config.hidden_size
213
+ )
214
+
215
+ self.max_tgt_len = max_tgt_len
216
+ self.device = torch.device('cpu')#torch.cuda.current_device()
217
+
218
+
219
+ def rot90_img(self,x,k):
220
+ # k is 0,1,2,3
221
+ degreesarr = [0., 90., 180., 270., 360]
222
+ degrees = torch.tensor(degreesarr[k]).to(self.llama_model.dtype).to(self.device)
223
+ x = K.geometry.transform.rotate(x, angle = degrees, padding_mode='reflection')
224
+ return x
225
+
226
+ def encode_video(self, video_paths):
227
+ inputs = {ModalityType.VISION: data.load_and_transform_video_data(video_paths, self.device)}
228
+ # convert into visual dtype
229
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
230
+ with torch.no_grad():
231
+ embeddings = self.visual_encoder(inputs)
232
+ video_embeds = embeddings[ModalityType.VISION][0] # bsz x 1024
233
+ inputs_llama = self.llama_proj(video_embeds).unsqueeze(1) # bsz x 1 x llama_size
234
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
235
+ return inputs_llama, atts_llama
236
+
237
+ def encode_audio(self, audio_paths):
238
+ inputs = {ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, self.device)}
239
+ # convert into visual dtype
240
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
241
+ with torch.no_grad():
242
+ embeddings = self.visual_encoder(inputs)
243
+ audio_embeds = embeddings[ModalityType.AUDIO][0] # bsz x 1024
244
+ inputs_llama = self.llama_proj(audio_embeds).unsqueeze(1) # bsz x 1 x llama_size
245
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
246
+ return inputs_llama, atts_llama
247
+
248
+ def encode_thermal(self, thermal_paths):
249
+ inputs = {ModalityType.THERMAL: data.load_and_transform_thermal_data(thermal_paths, self.device)}
250
+ # convert into visual dtype
251
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
252
+ with torch.no_grad():
253
+ embeddings = self.visual_encoder(inputs)
254
+ image_embeds = embeddings['thermal'][0] # bsz x 1024
255
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
256
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
257
+ return inputs_llama, atts_llama
258
+
259
+ def encode_image(self, image_paths):
260
+ inputs = {ModalityType.VISION: data.load_and_transform_vision_data(image_paths, self.device)}
261
+ # convert into visual dtype
262
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
263
+ with torch.no_grad():
264
+ embeddings = self.visual_encoder(inputs)
265
+ image_embeds = embeddings['vision'][0] # bsz x 1024
266
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1280
267
+ patch_tokens = self.image_decoder(patch_features) # bsz x h*w x 1024
268
+
269
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
270
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
271
+ return inputs_llama, atts_llama, patch_tokens
272
+
273
+ def encode_image_for_web_demo(self, image_paths):
274
+ inputs = {ModalityType.VISION: data.load_and_transform_vision_data_for_web_demo(image_paths, self.device)}
275
+ # convert into visual dtype
276
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
277
+ with torch.no_grad():
278
+ embeddings = self.visual_encoder(inputs)
279
+ image_embeds = embeddings['vision'][0] # bsz x 1024
280
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1280
281
+ patch_tokens = self.image_decoder(patch_features) # bsz x h*w x 1024
282
+
283
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
284
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
285
+ return inputs_llama, atts_llama, patch_tokens
286
+
287
+ def encode_image_for_one_shot(self, image_paths):
288
+ inputs = {ModalityType.VISION: data.load_and_transform_vision_data(image_paths, self.device)}
289
+ # convert into visual dtype
290
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
291
+ with torch.no_grad():
292
+ embeddings = self.visual_encoder(inputs)
293
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1280
294
+ for i in range(len(patch_features)):
295
+ patch_features[i] = patch_features[i].transpose(0, 1)[:, 1:, :]
296
+
297
+ return patch_features
298
+
299
+ def encode_image_for_one_shot_from_tensor(self, image_tensors):
300
+ if not isinstance(image_tensors, list):
301
+ image_tensors = [image_tensors]
302
+ inputs = {ModalityType.VISION: torch.stack(image_tensors, dim=0).to(self.device)}
303
+ # convert into visual dtype
304
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
305
+ with torch.no_grad():
306
+ embeddings = self.visual_encoder(inputs)
307
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1280
308
+ for i in range(len(patch_features)):
309
+ patch_features[i] = patch_features[i].transpose(0, 1)[:, 1:, :]
310
+
311
+ return patch_features
312
+
313
+ def encode_image_for_one_shot_with_aug(self, image_paths):
314
+ image_tensors = data.load_and_transform_vision_data(image_paths, self.device).to(self.llama_model.dtype)
315
+ B,C,H,W = image_tensors.shape
316
+ # print(B,C,H,W)
317
+
318
+ rotated_images = torch.zeros((4, B, C, H, W)).to(self.llama_model.dtype).to(self.device)
319
+
320
+
321
+ for j, degree in enumerate([0, 1, 2, 3]):
322
+ rotated_img = self.rot90_img(image_tensors, degree)
323
+ # 存储旋转后的图像
324
+ rotated_images[j] = rotated_img
325
+
326
+ image_tensors = rotated_images.transpose(0,1).reshape(B * 4, C, H, W)
327
+
328
+ inputs = {ModalityType.VISION: image_tensors}
329
+ # convert into visual dtype
330
+ inputs = {key: inputs[key] for key in inputs}
331
+ with torch.no_grad():
332
+ embeddings = self.visual_encoder(inputs)
333
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1280
334
+ for i in range(len(patch_features)):
335
+ patch_features[i] = patch_features[i].transpose(0, 1)[:, 1:, :].reshape(B,4,256,1280).reshape(B, 4 * 256, 1280)
336
+
337
+ return patch_features
338
+
339
+ def encode_image_from_tensor(self, image_tensors):
340
+ if not isinstance(image_tensors, list):
341
+ image_tensors = [image_tensors]
342
+ inputs = {ModalityType.VISION: torch.stack(image_tensors, dim=0).to(self.device)}
343
+ # convert into visual dtype
344
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
345
+ with torch.no_grad():
346
+ embeddings = self.visual_encoder(inputs)
347
+ image_embeds = embeddings['vision'][0] # bsz x 1024
348
+ patch_features = embeddings['vision'][1] # bsz x h*w x 1024
349
+ patch_tokens = self.image_decoder(patch_features)
350
+
351
+
352
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
353
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
354
+ return inputs_llama, atts_llama, patch_tokens
355
+
356
+ def encode_image_from_tensor_no_patch(self, image_tensors):
357
+ if not isinstance(image_tensors, list):
358
+ image_tensors = [image_tensors]
359
+ inputs = {ModalityType.VISION: torch.stack(image_tensors, dim=0).to(self.device)}
360
+ # convert into visual dtype
361
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
362
+ with torch.no_grad():
363
+ embeddings = self.visual_encoder(inputs)
364
+ image_embeds = embeddings['vision'][0] # bsz x 1024
365
+
366
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
367
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
368
+ return inputs_llama, atts_llama
369
+
370
+
371
+
372
+ def prompt_wrap(self, img_embeds, input_ids, target_ids, attention_mask, anomaly_embedding = None):
373
+ '''
374
+ input_ids, target_ids, attention_mask: bsz x s2
375
+ '''
376
+ input_ids = input_ids.to(self.device) # bsz x s2
377
+ target_ids = target_ids.to(self.device) # bsz x s2
378
+ attention_mask = attention_mask.to(self.device) # bsz x s2
379
+
380
+ batch_size = img_embeds.shape[0]
381
+ p_before = PROMPT_START
382
+ p_before_tokens = self.llama_tokenizer(p_before,
383
+ return_tensors="pt", add_special_tokens=False).to(self.device)
384
+ # peft model need deeper call
385
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
386
+
387
+ p_middle = '</Img> '
388
+ p_middle_tokens = self.llama_tokenizer(p_middle,
389
+ return_tensors="pt", add_special_tokens=False).to(self.device)
390
+ # peft model need deeper call
391
+ p_middle_embeds = self.llama_model.model.model.embed_tokens(p_middle_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
392
+
393
+
394
+ p_after_embeds = self.llama_model.model.model.embed_tokens(input_ids).expand(batch_size, -1, -1) # bsz x s2 x embed_dim
395
+ bos = torch.ones([batch_size, 1],
396
+ dtype=p_before_tokens.input_ids.dtype,
397
+ device=p_before_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
398
+ bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
399
+
400
+
401
+
402
+ if anomaly_embedding != None:
403
+ inputs_embeds = torch.cat([bos_embeds, p_before_embeds, img_embeds, p_middle_embeds, anomaly_embedding, p_after_embeds], dim=1) # bsz x (1+s1+1+s2) x embed_dim
404
+ # create targets
405
+ empty_targets = (
406
+ torch.ones([batch_size, 1+p_before_embeds.size()[1]+1+p_middle_embeds.size()[1] + anomaly_embedding.size()[1]], # 1 (bos) + s1 + 1 (image vector)
407
+ dtype=torch.long).to(self.device).fill_(-100)
408
+ ) # bsz x (1 + s1 + 1)
409
+ targets = torch.cat([empty_targets, target_ids], dim=1) # bsz x (1 + s1 + 1 + s2)
410
+ assert inputs_embeds.size()[1] == targets.size()[1]
411
+
412
+ atts_prefix = torch.ones([batch_size, 1+p_before_embeds.size()[1]+1+p_middle_embeds.size()[1] + anomaly_embedding.size()[1]], dtype=torch.long).to(self.device) # bsz x (1 + s1 +1)
413
+ attention_mask = torch.cat([atts_prefix, attention_mask], dim=1)
414
+ assert attention_mask.size() == targets.size() # bsz x (1 + s1 + 1 + s2)
415
+ return inputs_embeds, targets, attention_mask
416
+ else:
417
+ inputs_embeds = torch.cat([bos_embeds, p_before_embeds, img_embeds, p_middle_embeds, p_after_embeds], dim=1) # bsz x (1+s1+1+s2) x embed_dim
418
+ # create targets
419
+ empty_targets = (
420
+ torch.ones([batch_size, 1+p_before_embeds.size()[1]+1+p_middle_embeds.size()[1]], # 1 (bos) + s1 + 1 (image vector)
421
+ dtype=torch.long).to(self.device).fill_(-100)
422
+ ) # bsz x (1 + s1 + 1)
423
+ targets = torch.cat([empty_targets, target_ids], dim=1) # bsz x (1 + s1 + 1 + s2)
424
+ assert inputs_embeds.size()[1] == targets.size()[1]
425
+
426
+ atts_prefix = torch.ones([batch_size, 1+p_before_embeds.size()[1]+1+p_middle_embeds.size()[1]], dtype=torch.long).to(self.device) # bsz x (1 + s1 +1)
427
+ attention_mask = torch.cat([atts_prefix, attention_mask], dim=1)
428
+ assert attention_mask.size() == targets.size() # bsz x (1 + s1 + 1 + s2)
429
+ return inputs_embeds, targets, attention_mask
430
+
431
+
432
+ def forward(self, inputs):
433
+
434
+ if 'masks' in inputs:
435
+
436
+ image_paths = inputs['images']
437
+ img_embeds, _, patch_tokens = self.encode_image_from_tensor(image_paths)
438
+ class_name = inputs['class_names']
439
+
440
+ loss_pixel = 0
441
+ feats_text_tensor = encode_text_with_prompt_ensemble(self.visual_encoder, ['object' for _ in class_name], self.device)
442
+
443
+ anomaly_maps = []
444
+ for layer in range(len(patch_tokens)):
445
+ patch_tokens[layer] = patch_tokens[layer] / patch_tokens[layer].norm(dim=-1, keepdim=True)
446
+ # print(patch_tokens[layer].shape)
447
+ # anomaly_map = torch.bmm(patch_tokens[layer], feats_text_tensor.transpose(-2,-1))
448
+ anomaly_map = (100.0 * patch_tokens[layer] @ feats_text_tensor.transpose(-2,-1))
449
+ B, L, C = anomaly_map.shape
450
+ H = int(np.sqrt(L))
451
+ anomaly_map = F.interpolate(anomaly_map.permute(0, 2, 1).view(B, 2, H, H),
452
+ size=224, mode='bilinear', align_corners=True)
453
+ # anomaly_map_no_softmax = anomaly_map
454
+ anomaly_map = torch.softmax(anomaly_map, dim=1)
455
+ anomaly_maps.append(anomaly_map)
456
+ # anomaly_maps_ns.append(anomaly_map_no_softmax)
457
+
458
+ gt = inputs['masks']
459
+ gt = torch.stack(gt, dim=0).to(self.device)
460
+ gt = gt.squeeze()
461
+ # print(gt.max(), gt.min())
462
+ gt[gt > 0.3], gt[gt <= 0.3] = 1, 0
463
+
464
+
465
+ for num in range(len(anomaly_maps)):
466
+ f_loss = self.loss_focal(anomaly_maps[num], gt)
467
+ d_loss = self.loss_dice(anomaly_maps[num][:, 1, :, :], gt)
468
+ loss_pixel = loss_pixel + f_loss + d_loss
469
+
470
+ for num in range(len(anomaly_maps)):
471
+ anomaly_maps[num] = anomaly_maps[num][:,1,:,:]
472
+
473
+ anomaly_map_all = torch.mean(torch.stack(anomaly_maps, dim=0), dim=0).unsqueeze(1)
474
+
475
+ if random.randint(0,1) == 0 and len(inputs['img_paths']) == len(image_paths):
476
+
477
+ normal_paths = []
478
+ for path in inputs['img_paths']:
479
+ normal_path = path.replace('test', 'train')
480
+ normal_path = find_first_file_in_directory("/".join(normal_path.split('/')[:-2])+'/good')
481
+ normal_paths.append(normal_path)
482
+
483
+ print(normal_paths)
484
+ query_patch_tokens = self.encode_image_for_one_shot_from_tensor(image_paths)
485
+ normal_patch_tokens = self.encode_image_for_one_shot_with_aug(normal_paths)
486
+ sims = []
487
+ B = len(image_paths)
488
+
489
+ for i in range(len(query_patch_tokens)):
490
+ query_patch_tokens_reshaped = query_patch_tokens[i].view(B,256,1,1280)
491
+ normal_tokens_reshaped = normal_patch_tokens[i].reshape(B,1,-1,1280)
492
+ cosine_similarity_matrix = F.cosine_similarity(query_patch_tokens_reshaped, normal_tokens_reshaped, dim=-1)
493
+ sim_max, _ = torch.max(cosine_similarity_matrix, dim=-1)
494
+ sims.append(sim_max)
495
+
496
+ sim = torch.mean(torch.stack(sims,dim=0), dim=0).reshape(B,1,16,16)
497
+ sim = F.interpolate(sim,size=224, mode='bilinear', align_corners=True)
498
+ anomaly_map_all = 1 - sim # (anomaly_map_all + 1 - sim) / 2
499
+
500
+ anomaly_map_prompts = self.prompt_learner(anomaly_map_all)
501
+
502
+ # img_embeds = img_embeds + anomaly_map_prompts
503
+
504
+ output_texts = inputs['texts']
505
+ input_ids, target_ids, attention_mask = process_batch_instance(self.llama_tokenizer, output_texts, self.max_tgt_len)
506
+ inputs_embeds, targets, attention_mask = self.prompt_wrap(img_embeds, input_ids, target_ids, attention_mask, anomaly_map_prompts)
507
+
508
+ outputs = self.llama_model(
509
+ inputs_embeds=inputs_embeds,
510
+ attention_mask=attention_mask,
511
+ return_dict=True,
512
+ labels=targets,
513
+ )
514
+ loss = outputs.loss
515
+
516
+ # loss_l2 = torch.norm(anomaly_map_prompts / 2 , p=2)
517
+ # loss_l2 = nn.MSELoss()(img_embeds_origin, img_embeds)
518
+ # calculate the token accuarcy
519
+ chosen_tokens = torch.max(outputs.logits, dim=-1)[1][:, 1:-1] # [B, S-1]
520
+ # print(self.llama_tokenizer.decode(chosen_tokens[0], skip_special_tokens=True))
521
+ labels = targets[:, 2:]
522
+ gen_acc = (chosen_tokens.reshape(-1) == labels.reshape(-1)).to(torch.long) # [B*S]
523
+ valid_mask = (labels != -100).reshape(-1)
524
+ # print(self.llama_tokenizer.decode(chosen_tokens.reshape(-1)[valid_mask], skip_special_tokens=True))
525
+ valid_tokens = gen_acc & valid_mask # [B*S]
526
+ gen_acc = valid_tokens.sum().item() / valid_mask.sum().item()
527
+
528
+ return loss + loss_pixel, gen_acc
529
+
530
+ else:
531
+
532
+ image_paths = inputs['image_paths']
533
+ img_embeds, _, patch_tokens = self.encode_image_from_tensor(image_paths)
534
+
535
+ output_texts = inputs['output_texts']
536
+
537
+ c_name = 'object'
538
+ for name in CLASS_NAMES:
539
+ if name in output_texts:
540
+ c_name = name
541
+ break
542
+
543
+ feats_text_tensor = encode_text_with_prompt_ensemble(self.visual_encoder, ['object'] * len(image_paths), self.device)
544
+
545
+ anomaly_maps = []
546
+ for layer in range(len(patch_tokens)):
547
+ patch_tokens[layer] = patch_tokens[layer] / patch_tokens[layer].norm(dim=-1, keepdim=True)
548
+ # print(patch_tokens[layer].shape)
549
+ # anomaly_map = torch.bmm(patch_tokens[layer], feats_text_tensor.transpose(-2,-1))
550
+ anomaly_map = (100.0 * patch_tokens[layer] @ feats_text_tensor.transpose(-2,-1))
551
+ B, L, C = anomaly_map.shape
552
+ H = int(np.sqrt(L))
553
+ anomaly_map = F.interpolate(anomaly_map.permute(0, 2, 1).view(B, 2, H, H),
554
+ size=224, mode='bilinear', align_corners=True)
555
+ # anomaly_map_no_softmax = anomaly_map
556
+ anomaly_map = torch.softmax(anomaly_map, dim=1)
557
+ anomaly_maps.append(anomaly_map)
558
+
559
+ for num in range(len(anomaly_maps)):
560
+ anomaly_maps[num] = anomaly_maps[num][:,1,:,:]
561
+
562
+ anomaly_map_all = torch.mean(torch.stack(anomaly_maps, dim=0), dim=0).unsqueeze(1)
563
+
564
+ anomaly_map_prompts = self.prompt_learner(anomaly_map_all)
565
+
566
+ # img_embeds = img_embeds + anomaly_map_prompts
567
+
568
+ input_ids, target_ids, attention_mask = process_batch_instance(self.llama_tokenizer, output_texts, self.max_tgt_len)
569
+ inputs_embeds, targets, attention_mask = self.prompt_wrap(img_embeds, input_ids, target_ids, attention_mask, anomaly_map_prompts)
570
+
571
+ outputs = self.llama_model(
572
+ inputs_embeds=inputs_embeds,
573
+ attention_mask=attention_mask,
574
+ return_dict=True,
575
+ labels=targets,
576
+ )
577
+ loss = outputs.loss
578
+ # calculate the token accuarcy
579
+ chosen_tokens = torch.max(outputs.logits, dim=-1)[1][:, 1:-1] # [B, S-1]
580
+ labels = targets[:, 2:]
581
+ gen_acc = (chosen_tokens.reshape(-1) == labels.reshape(-1)).to(torch.long) # [B*S]
582
+ valid_mask = (labels != -100).reshape(-1)
583
+ valid_tokens = gen_acc & valid_mask # [B*S]
584
+ gen_acc = valid_tokens.sum().item() / valid_mask.sum().item()
585
+
586
+ return loss, gen_acc
587
+
588
+
589
+ def extract_multimodal_feature(self, inputs, web_demo):
590
+ features = []
591
+ if inputs['image_paths']:
592
+
593
+ prompt = inputs['prompt']
594
+ c_name = 'object'
595
+ for name in CLASS_NAMES:
596
+ if name in prompt:
597
+ c_name = name
598
+ break
599
+
600
+ if not web_demo:
601
+ image_embeds, _, patch_tokens = self.encode_image(inputs['image_paths'])
602
+ feats_text_tensor = encode_text_with_prompt_ensemble(self.visual_encoder, [c_name], self.device)
603
+ else:
604
+ image_embeds, _, patch_tokens = self.encode_image_for_web_demo(inputs['image_paths'])
605
+ feats_text_tensor = encode_text_with_prompt_ensemble(self.visual_encoder, ['object'], self.device)
606
+
607
+ anomaly_maps = []
608
+ for layer in range(len(patch_tokens)):
609
+ patch_tokens[layer] = patch_tokens[layer] / patch_tokens[layer].norm(dim=-1, keepdim=True)
610
+ # print(patch_tokens[layer].shape)
611
+ # anomaly_map = torch.bmm(patch_tokens[layer], feats_text_tensor.transpose(-2,-1))
612
+ anomaly_map = (100.0 * patch_tokens[layer] @ feats_text_tensor.transpose(-2,-1))
613
+ B, L, C = anomaly_map.shape
614
+ H = int(np.sqrt(L))
615
+ anomaly_map = F.interpolate(anomaly_map.permute(0, 2, 1).view(B, 2, H, H),
616
+ size=224, mode='bilinear', align_corners=True)
617
+ anomaly_map = torch.softmax(anomaly_map, dim=1)
618
+ anomaly_maps.append(anomaly_map[:,1,:,:])
619
+
620
+ anomaly_map_ret = torch.mean(torch.stack(anomaly_maps, dim=0), dim=0).unsqueeze(1)
621
+ # anomaly_map_all = anomaly_map_ret.unsqueeze(1).repeat((1,3,1,1))
622
+ # anomaly_map_feature, _, _ = self.encode_image_from_tensor(anomaly_map_all)
623
+ # image_embeds = anomaly_map_feature + image_embeds
624
+ if inputs['normal_img_paths']:
625
+ query_patch_tokens = self.encode_image_for_one_shot(inputs['image_paths'])
626
+ if 'mvtec' in 'normal_img_paths':
627
+ normal_patch_tokens = self.encode_image_for_one_shot_with_aug(inputs['normal_img_paths'])
628
+ else:
629
+ normal_patch_tokens = self.encode_image_for_one_shot(inputs['normal_img_paths'])
630
+ sims = []
631
+
632
+ for i in range(len(query_patch_tokens)):
633
+ query_patch_tokens_reshaped = query_patch_tokens[i].view(256,1,1280)
634
+ normal_tokens_reshaped = normal_patch_tokens[i].reshape(1,-1,1280)
635
+ cosine_similarity_matrix = F.cosine_similarity(query_patch_tokens_reshaped, normal_tokens_reshaped, dim=2)
636
+ sim_max, _ = torch.max(cosine_similarity_matrix, dim=1)
637
+ sims.append(sim_max)
638
+
639
+ sim = torch.mean(torch.stack(sims,dim=0), dim=0).reshape(1,1,16,16)
640
+ sim = F.interpolate(sim,size=224, mode='bilinear', align_corners=True)
641
+ anomaly_map_ret = 1 - sim # (anomaly_map_ret + 1 - sim) / 2
642
+
643
+
644
+ features.append(image_embeds)
645
+ if inputs['audio_paths']:
646
+ audio_embeds, _ = self.encode_audio(inputs['audio_paths'])
647
+ features.append(audio_embeds)
648
+ if inputs['video_paths']:
649
+ video_embeds, _ = self.encode_video(inputs['video_paths'])
650
+ features.append(video_embeds)
651
+ if inputs['thermal_paths']:
652
+ thermal_embeds, _ = self.encode_thermal(inputs['thermal_paths'])
653
+ features.append(thermal_embeds)
654
+
655
+ feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
656
+ return feature_embeds, anomaly_map_ret
657
+
658
+ def prepare_generation_embedding(self, inputs, web_demo):
659
+ prompt = inputs['prompt']
660
+ # if len(inputs['modality_embeds']) == 1:
661
+ # feature_embeds = inputs['modality_embeds'][0]
662
+ # else:
663
+ feature_embeds, anomaly_map = self.extract_multimodal_feature(inputs, web_demo)
664
+ # print(anomaly_map.shape)
665
+ inputs['modality_embeds'].append(feature_embeds)
666
+
667
+ batch_size = feature_embeds.shape[0]
668
+ p_before = PROMPT_START
669
+ p_before_tokens = self.llama_tokenizer(p_before,
670
+ return_tensors="pt", add_special_tokens=False).to(self.device)
671
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
672
+
673
+ p_middle = '</Img> '
674
+ p_middle_tokens = self.llama_tokenizer(p_middle,
675
+ return_tensors="pt", add_special_tokens=False).to(self.device)
676
+ # peft model need deeper call
677
+ p_middle_embeds = self.llama_model.model.model.embed_tokens(p_middle_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
678
+
679
+ # self.prompt_learner.eval()
680
+ anomaly_map_prompts = self.prompt_learner(anomaly_map)
681
+
682
+
683
+
684
+
685
+ text = prompt + '\n### Assistant:'
686
+ p_after_tokens = self.llama_tokenizer(text, add_special_tokens=False, return_tensors='pt').to(self.device)
687
+ p_after_embeds = self.llama_model.model.model.embed_tokens(p_after_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s2 x embed_dim
688
+ bos = torch.ones([batch_size, 1],
689
+ dtype=p_before_tokens.input_ids.dtype,
690
+ device=p_before_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
691
+ bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
692
+ inputs_embeds = torch.cat([bos_embeds, p_before_embeds, feature_embeds, p_middle_embeds, anomaly_map_prompts, p_after_embeds], dim=1) # bsz x (1+s1+1+s2) x embed_dim
693
+
694
+ return inputs_embeds, anomaly_map
695
+
696
+ def generate(self, inputs, web_demo=False):
697
+ '''
698
+ inputs = {
699
+ 'image_paths': optional,
700
+ 'audio_paths': optional
701
+ 'video_paths': optional
702
+ 'thermal_paths': optional
703
+ 'mode': generation mode,
704
+ 'prompt': human input prompt,
705
+ 'max_tgt_len': generation length,
706
+ 'top_p': top_p,
707
+ 'temperature': temperature
708
+ 'modality_embeds': None or torch.tensor
709
+ 'modality_cache': save the image cache
710
+ }
711
+ '''
712
+ # self.prompt_learner.eval()
713
+ # self.llama_model.eval()
714
+ # self.llama_proj.eval()
715
+ # self.image_decoder.eval()
716
+ # self.llama_tokenizer.eval()
717
+ input_embeds, pixel_output = self.prepare_generation_embedding(inputs, web_demo)
718
+ stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=[2277], encounters=1)])
719
+ outputs = self.llama_model.generate(
720
+ inputs_embeds=input_embeds,
721
+ max_new_tokens=inputs['max_tgt_len'],
722
+ top_p=inputs['top_p'],
723
+ temperature=inputs['temperature'],
724
+ do_sample=True,
725
+ use_cache=True,
726
+ stopping_criteria=stopping_criteria,
727
+ )
728
+ output_text = self.llama_tokenizer.decode(outputs[0][:-2], skip_special_tokens=True)
729
+ return output_text, pixel_output
pretrained_ckpt/imagebind_ckpt/imagebind_huge.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6f6c22bedcc90708448d5d2fbb7b2db9c73f505dc89bd0b2e09b23af1b62157
3
+ size 4803584173
pretrained_ckpt/pandagpt_ckpt/13b/empty.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ empty placeholder
pretrained_ckpt/pandagpt_ckpt/7b/empty.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ empty placeholder
pretrained_ckpt/pandagpt_ckpt/7b/pytorch_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0d56d6fc00051c10c554f4d2aa9f8410e24ee6b754ae94dc8e2373d49571b94
3
+ size 75557949
pretrained_ckpt/vicuna_ckpt/13b_v0/empty.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ empty placeholder
pretrained_ckpt/vicuna_ckpt/7b_v0/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "llama-7b-hf-transformers-4.29/",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "bos_token_id": 1,
7
+ "eos_token_id": 2,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 4096,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 11008,
12
+ "max_position_embeddings": 2048,
13
+ "model_type": "llama",
14
+ "num_attention_heads": 32,
15
+ "num_hidden_layers": 32,
16
+ "pad_token_id": 0,
17
+ "rms_norm_eps": 1e-06,
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float16",
20
+ "transformers_version": "4.29.1",
21
+ "use_cache": true,
22
+ "vocab_size": 32001
23
+ }
pretrained_ckpt/vicuna_ckpt/7b_v0/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.29.1"
7
+ }
pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model-00001-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef1b2c502e2eab32176400bd8af8636163619fb04e65c0c0fdea58f1cbe21807
3
+ size 9976642750
pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model-00002-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f3789f864bf21ca0733d782022e3656759728151fab435e6799696124099a9a
3
+ size 3500323731
pretrained_ckpt/vicuna_ckpt/7b_v0/pytorch_model.bin.index.json ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13476855808
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00002-of-00002.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
14
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
15
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
16
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
17
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
18
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
19
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
20
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
21
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
22
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
23
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
24
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
25
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
26
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
27
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
28
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
29
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
30
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
31
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
32
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
33
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
34
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
35
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
36
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
37
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
38
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
39
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
40
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
41
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
42
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
43
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
44
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
45
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
46
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
47
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
48
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
49
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
50
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
51
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
52
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
53
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
54
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
55
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
56
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
57
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
58
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
59
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
60
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
61
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
62
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
63
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
64
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
65
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
66
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
67
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
68
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
69
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
70
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
71
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
72
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
73
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
74
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
75
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
76
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
77
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
78
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
79
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
80
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
81
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
82
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
83
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
84
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
85
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
86
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
87
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
88
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
89
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
90
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
91
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
92
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
93
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
94
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
95
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
96
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
97
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
98
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
99
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
100
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
101
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
102
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
103
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
104
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
105
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
106
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
107
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
108
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
109
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
110
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
111
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
112
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
113
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
114
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
115
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
116
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
117
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
118
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
119
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
120
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
121
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
122
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
123
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
124
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
125
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
126
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
127
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
128
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
129
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
130
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
131
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
132
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
133
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
134
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
135
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
136
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
137
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
138
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
139
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
140
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
141
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
142
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
143
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
144
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
145
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
146
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
147
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
148
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
149
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
150
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
151
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
152
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
153
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
154
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
155
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
156
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
157
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
158
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
159
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
160
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
161
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
162
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
163
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
164
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
165
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
166
+ "model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
167
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
168
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
169
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
170
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
171
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
172
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
173
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
174
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
175
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
176
+ "model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
177
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
178
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
179
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
180
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
181
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
182
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
183
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
184
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
185
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
186
+ "model.layers.24.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
187
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
188
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
189
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
190
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
191
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
192
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
193
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
194
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
195
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
196
+ "model.layers.25.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
197
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
198
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
199
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
200
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
201
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
202
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
203
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
204
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
205
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
206
+ "model.layers.26.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
207
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
208
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
209
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
210
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
211
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
212
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
213
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
214
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
215
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
216
+ "model.layers.27.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
217
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
218
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
219
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
220
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
221
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
222
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
223
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
224
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
225
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
226
+ "model.layers.28.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
227
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
228
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
229
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
230
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
231
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
232
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
233
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
234
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
235
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
236
+ "model.layers.29.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
237
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
238
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
239
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
240
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
241
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
242
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
243
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
244
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
245
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
246
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
247
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
248
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
249
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
250
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
251
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
252
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
253
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
254
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
255
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
256
+ "model.layers.30.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
257
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
258
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
259
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
260
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
261
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
262
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
263
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
264
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
265
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
266
+ "model.layers.31.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
267
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
268
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
269
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
270
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
271
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
272
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
273
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
274
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
275
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
276
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
277
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
278
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
279
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
280
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
281
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
282
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
283
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
284
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
285
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
286
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
287
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
288
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
289
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
290
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
291
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
292
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
293
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
294
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
295
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
296
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
297
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
298
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
299
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
300
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
301
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
302
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
303
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
304
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
305
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
306
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
307
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
308
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
309
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
310
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
311
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
312
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
313
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
314
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
315
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
316
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
317
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
318
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
319
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
320
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
321
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
322
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
323
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
324
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
325
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
326
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
327
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
328
+ "model.norm.weight": "pytorch_model-00002-of-00002.bin"
329
+ }
330
+ }
pretrained_ckpt/vicuna_ckpt/7b_v0/special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
pretrained_ckpt/vicuna_ckpt/7b_v0/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
pretrained_ckpt/vicuna_ckpt/7b_v0/tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "model_max_length": 1000000000000000019884624838656,
22
+ "pad_token": null,
23
+ "sp_model_kwargs": {},
24
+ "tokenizer_class": "LlamaTokenizer",
25
+ "unk_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ deepspeed==0.9.2
2
+ easydict==1.10
3
+ einops==0.6.1
4
+ ftfy==6.1.1
5
+ gradio==3.41.2
6
+ h5py==3.9.0
7
+ iopath==0.1.10
8
+ ipdb==0.13.13
9
+ kornia==0.7.0
10
+ matplotlib==3.7.2
11
+ mdtex2html==1.2.0
12
+ numpy==1.24.3
13
+ open3d_python==0.3.0.0
14
+ opencv_python==4.8.0.74
15
+ peft==0.3.0
16
+ Pillow==10.0.0
17
+ pytorchvideo==0.1.5
18
+ PyYAML==6.0.1
19
+ regex==2022.10.31
20
+ timm==0.6.7
21
+ torch==1.13.1
22
+ torchaudio==0.13.1
23
+ torchvision==0.14.1
24
+ tqdm==4.64.1
25
+ transformers==4.29.1
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (144 Bytes). View file
 
utils/__pycache__/loss.cpython-38.pyc ADDED
Binary file (3.53 kB). View file
 
utils/build.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..utils import registry
2
+
3
+
4
+ DATASETS = registry.Registry('dataset')
5
+
6
+
7
+ def build_dataset_from_cfg(cfg, default_args = None):
8
+ """
9
+ Build a dataset, defined by `dataset_name`.
10
+ Args:
11
+ cfg (eDICT):
12
+ Returns:
13
+ Dataset: a constructed dataset specified by dataset_name.
14
+ """
15
+ return DATASETS.build(cfg, default_args = default_args)
16
+
17
+
utils/config.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+ from easydict import EasyDict
3
+ import os
4
+ from .logger import print_log
5
+
6
+ def log_args_to_file(args, pre='args', logger=None):
7
+ for key, val in args.__dict__.items():
8
+ print_log(f'{pre}.{key} : {val}', logger = logger)
9
+
10
+ def log_config_to_file(cfg, pre='cfg', logger=None):
11
+ for key, val in cfg.items():
12
+ if isinstance(cfg[key], EasyDict):
13
+ print_log(f'{pre}.{key} = edict()', logger = logger)
14
+ log_config_to_file(cfg[key], pre=pre + '.' + key, logger=logger)
15
+ continue
16
+ print_log(f'{pre}.{key} : {val}', logger = logger)
17
+
18
+ def merge_new_config(config, new_config):
19
+ for key, val in new_config.items():
20
+ if not isinstance(val, dict):
21
+ if key == '_base_':
22
+ with open(new_config['_base_'], 'r') as f:
23
+ try:
24
+ val = yaml.load(f, Loader=yaml.FullLoader)
25
+ except:
26
+ val = yaml.load(f)
27
+ config[key] = EasyDict()
28
+ merge_new_config(config[key], val)
29
+ else:
30
+ config[key] = val
31
+ continue
32
+ if key not in config:
33
+ config[key] = EasyDict()
34
+ merge_new_config(config[key], val)
35
+ return config
36
+
37
+ def cfg_from_yaml_file(cfg_file):
38
+ config = EasyDict()
39
+ with open(cfg_file, 'r') as f:
40
+ try:
41
+ new_config = yaml.load(f, Loader=yaml.FullLoader)
42
+ except:
43
+ new_config = yaml.load(f)
44
+ merge_new_config(config=config, new_config=new_config)
45
+ return config
46
+
47
+ def get_config(args, logger=None):
48
+ if args.resume:
49
+ cfg_path = os.path.join(args.experiment_path, 'config.yaml')
50
+ if not os.path.exists(cfg_path):
51
+ print_log("Failed to resume", logger = logger)
52
+ raise FileNotFoundError()
53
+ print_log(f'Resume yaml from {cfg_path}', logger = logger)
54
+ args.config = cfg_path
55
+ config = cfg_from_yaml_file(args.config)
56
+ if not args.resume and args.local_rank == 0:
57
+ save_experiment_config(args, config, logger)
58
+ return config
59
+
60
+ def save_experiment_config(args, config, logger = None):
61
+ config_path = os.path.join(args.experiment_path, 'config.yaml')
62
+ os.system('cp %s %s' % (args.config, config_path))
63
+ print_log(f'Copy the Config file from {args.config} to {config_path}',logger = logger )
utils/data_transform.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import math
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torchaudio
14
+ from PIL import Image
15
+ from pytorchvideo import transforms as pv_transforms
16
+ from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
17
+ from pytorchvideo.data.encoded_video import EncodedVideo
18
+ from torchvision import transforms
19
+ from torchvision.transforms._transforms_video import NormalizeVideo
20
+
21
+ from ..model.ImageBind.models.multimodal_preprocessors import SimpleTokenizer
22
+
23
+ DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
24
+
25
+ BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz"
26
+
27
+
28
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
29
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
30
+ waveform -= waveform.mean()
31
+ fbank = torchaudio.compliance.kaldi.fbank(
32
+ waveform,
33
+ htk_compat=True,
34
+ sample_frequency=sample_rate,
35
+ use_energy=False,
36
+ window_type="hanning",
37
+ num_mel_bins=num_mel_bins,
38
+ dither=0.0,
39
+ frame_length=25,
40
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
41
+ )
42
+ # Convert to [mel_bins, num_frames] shape
43
+ fbank = fbank.transpose(0, 1)
44
+ # Pad to target_length
45
+ n_frames = fbank.size(1)
46
+ p = target_length - n_frames
47
+ # if p is too large (say >20%), flash a warning
48
+ if abs(p) / n_frames > 0.2:
49
+ logging.warning(
50
+ "Large gap between audio n_frames(%d) and "
51
+ "target_length (%d). Is the audio_target_length "
52
+ "setting correct?",
53
+ n_frames,
54
+ target_length,
55
+ )
56
+ # cut and pad
57
+ if p > 0:
58
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
59
+ elif p < 0:
60
+ fbank = fbank[:, 0:target_length]
61
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
62
+ # channel image
63
+ fbank = fbank.unsqueeze(0)
64
+ return fbank
65
+
66
+
67
+ def get_clip_timepoints(clip_sampler, duration):
68
+ # Read out all clips in this video
69
+ all_clips_timepoints = []
70
+ is_last_clip = False
71
+ end = 0.0
72
+ while not is_last_clip:
73
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
74
+ all_clips_timepoints.append((start, end))
75
+ return all_clips_timepoints
76
+
77
+
78
+
79
+ def load_and_transform_vision_data(image_paths, device):
80
+ if image_paths is None:
81
+ return None
82
+
83
+ image_ouputs = []
84
+ for image_path in image_paths:
85
+ data_transform = transforms.Compose(
86
+ [
87
+ transforms.Resize(
88
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
89
+ ),
90
+ transforms.CenterCrop(224),
91
+ transforms.ToTensor(),
92
+ transforms.Normalize(
93
+ mean=(0.48145466, 0.4578275, 0.40821073),
94
+ std=(0.26862954, 0.26130258, 0.27577711),
95
+ ),
96
+ ]
97
+ )
98
+ with open(image_path, "rb") as fopen:
99
+ image = Image.open(fopen).convert("RGB")
100
+
101
+ image = data_transform(image)
102
+ image_ouputs.append(image)
103
+ return torch.stack(image_ouputs, dim=0)
104
+
105
+
106
+ def load_and_transform_text(text, device):
107
+ if text is None:
108
+ return None
109
+ tokenizer = SimpleTokenizer(bpe_path=BPE_PATH)
110
+ tokens = [tokenizer(t).unsqueeze(0) for t in text]
111
+ tokens = torch.cat(tokens, dim=0)
112
+ return tokens
113
+
114
+
115
+ def load_and_transform_audio_data(
116
+ audio_paths,
117
+ device,
118
+ num_mel_bins=128,
119
+ target_length=204,
120
+ sample_rate=16000,
121
+ clip_duration=2,
122
+ clips_per_video=3,
123
+ mean=-4.268,
124
+ std=9.138,
125
+ ):
126
+ if audio_paths is None:
127
+ return None
128
+
129
+ audio_outputs = []
130
+ clip_sampler = ConstantClipsPerVideoSampler(
131
+ clip_duration=clip_duration, clips_per_video=clips_per_video
132
+ )
133
+
134
+ for audio_path in audio_paths:
135
+ waveform, sr = torchaudio.load(audio_path)
136
+ if sample_rate != sr:
137
+ waveform = torchaudio.functional.resample(
138
+ waveform, orig_freq=sr, new_freq=sample_rate
139
+ )
140
+ all_clips_timepoints = get_clip_timepoints(
141
+ clip_sampler, waveform.size(1) / sample_rate
142
+ )
143
+ all_clips = []
144
+ for clip_timepoints in all_clips_timepoints:
145
+ waveform_clip = waveform[
146
+ :,
147
+ int(clip_timepoints[0] * sample_rate) : int(
148
+ clip_timepoints[1] * sample_rate
149
+ ),
150
+ ]
151
+ waveform_melspec = waveform2melspec(
152
+ waveform_clip, sample_rate, num_mel_bins, target_length
153
+ )
154
+ all_clips.append(waveform_melspec)
155
+
156
+ normalize = transforms.Normalize(mean=mean, std=std)
157
+ all_clips = [normalize(ac) for ac in all_clips]
158
+
159
+ all_clips = torch.stack(all_clips, dim=0)
160
+ audio_outputs.append(all_clips)
161
+
162
+ return torch.stack(audio_outputs, dim=0)
163
+
164
+
165
+ def crop_boxes(boxes, x_offset, y_offset):
166
+ """
167
+ Perform crop on the bounding boxes given the offsets.
168
+ Args:
169
+ boxes (ndarray or None): bounding boxes to perform crop. The dimension
170
+ is `num boxes` x 4.
171
+ x_offset (int): cropping offset in the x axis.
172
+ y_offset (int): cropping offset in the y axis.
173
+ Returns:
174
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
175
+ `num boxes` x 4.
176
+ """
177
+ cropped_boxes = boxes.copy()
178
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
179
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
180
+
181
+ return cropped_boxes
182
+
183
+
184
+ def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
185
+ """
186
+ Perform uniform spatial sampling on the images and corresponding boxes.
187
+ Args:
188
+ images (tensor): images to perform uniform crop. The dimension is
189
+ `num frames` x `channel` x `height` x `width`.
190
+ size (int): size of height and weight to crop the images.
191
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
192
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
193
+ crop if height is larger than width.
194
+ boxes (ndarray or None): optional. Corresponding boxes to images.
195
+ Dimension is `num boxes` x 4.
196
+ scale_size (int): optinal. If not None, resize the images to scale_size before
197
+ performing any crop.
198
+ Returns:
199
+ cropped (tensor): images with dimension of
200
+ `num frames` x `channel` x `size` x `size`.
201
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
202
+ `num boxes` x 4.
203
+ """
204
+ assert spatial_idx in [0, 1, 2]
205
+ ndim = len(images.shape)
206
+ if ndim == 3:
207
+ images = images.unsqueeze(0)
208
+ height = images.shape[2]
209
+ width = images.shape[3]
210
+
211
+ if scale_size is not None:
212
+ if width <= height:
213
+ width, height = scale_size, int(height / width * scale_size)
214
+ else:
215
+ width, height = int(width / height * scale_size), scale_size
216
+ images = torch.nn.functional.interpolate(
217
+ images,
218
+ size=(height, width),
219
+ mode="bilinear",
220
+ align_corners=False,
221
+ )
222
+
223
+ y_offset = int(math.ceil((height - size) / 2))
224
+ x_offset = int(math.ceil((width - size) / 2))
225
+
226
+ if height > width:
227
+ if spatial_idx == 0:
228
+ y_offset = 0
229
+ elif spatial_idx == 2:
230
+ y_offset = height - size
231
+ else:
232
+ if spatial_idx == 0:
233
+ x_offset = 0
234
+ elif spatial_idx == 2:
235
+ x_offset = width - size
236
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
237
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
238
+ if ndim == 3:
239
+ cropped = cropped.squeeze(0)
240
+ return cropped, cropped_boxes
241
+
242
+
243
+ class SpatialCrop(nn.Module):
244
+ """
245
+ Convert the video into 3 smaller clips spatially. Must be used after the
246
+ temporal crops to get spatial crops, and should be used with
247
+ -2 in the spatial crop at the slowfast augmentation stage (so full
248
+ frames are passed in here). Will return a larger list with the
249
+ 3x spatial crops as well.
250
+ """
251
+
252
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
253
+ super().__init__()
254
+ self.crop_size = crop_size
255
+ if num_crops == 3:
256
+ self.crops_to_ext = [0, 1, 2]
257
+ self.flipped_crops_to_ext = []
258
+ elif num_crops == 1:
259
+ self.crops_to_ext = [1]
260
+ self.flipped_crops_to_ext = []
261
+ else:
262
+ raise NotImplementedError("Nothing else supported yet")
263
+
264
+ def forward(self, videos):
265
+ """
266
+ Args:
267
+ videos: A list of C, T, H, W videos.
268
+ Returns:
269
+ videos: A list with 3x the number of elements. Each video converted
270
+ to C, T, H', W' by spatial cropping.
271
+ """
272
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
273
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
274
+ res = []
275
+ for video in videos:
276
+ for spatial_idx in self.crops_to_ext:
277
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
278
+ if not self.flipped_crops_to_ext:
279
+ continue
280
+ flipped_video = transforms.functional.hflip(video)
281
+ for spatial_idx in self.flipped_crops_to_ext:
282
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
283
+ return res
284
+
285
+
286
+ def load_and_transform_video_data(
287
+ video_paths,
288
+ device,
289
+ clip_duration=2,
290
+ clips_per_video=5,
291
+ sample_rate=16000,
292
+ ):
293
+ if video_paths is None:
294
+ return None
295
+
296
+ video_outputs = []
297
+ video_transform = transforms.Compose(
298
+ [
299
+ pv_transforms.ShortSideScale(224),
300
+ NormalizeVideo(
301
+ mean=(0.48145466, 0.4578275, 0.40821073),
302
+ std=(0.26862954, 0.26130258, 0.27577711),
303
+ ),
304
+ ]
305
+ )
306
+
307
+ clip_sampler = ConstantClipsPerVideoSampler(
308
+ clip_duration=clip_duration, clips_per_video=clips_per_video
309
+ )
310
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
311
+
312
+ for video_path in video_paths:
313
+ video = EncodedVideo.from_path(
314
+ video_path,
315
+ decoder="decord",
316
+ decode_audio=False,
317
+ **{"sample_rate": sample_rate},
318
+ )
319
+
320
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
321
+
322
+ all_video = []
323
+ for clip_timepoints in all_clips_timepoints:
324
+ # Read the clip, get frames
325
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
326
+ if clip is None:
327
+ raise ValueError("No clip found")
328
+ video_clip = frame_sampler(clip["video"])
329
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
330
+
331
+ all_video.append(video_clip)
332
+
333
+ all_video = [video_transform(clip) for clip in all_video]
334
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
335
+
336
+ all_video = torch.stack(all_video, dim=0)
337
+ video_outputs.append(all_video)
338
+
339
+ return torch.stack(video_outputs, dim=0)
utils/io.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import h5py
2
+ import numpy as np
3
+ import open3d
4
+ import os
5
+
6
+ class IO:
7
+ @classmethod
8
+ def get(cls, file_path):
9
+ _, file_extension = os.path.splitext(file_path)
10
+
11
+ if file_extension in ['.npy']:
12
+ return cls._read_npy(file_path)
13
+ elif file_extension in ['.pcd']:
14
+ return cls._read_pcd(file_path)
15
+ elif file_extension in ['.h5']:
16
+ return cls._read_h5(file_path)
17
+ elif file_extension in ['.txt']:
18
+ return cls._read_txt(file_path)
19
+ else:
20
+ raise Exception('Unsupported file extension: %s' % file_extension)
21
+
22
+ # References: https://github.com/numpy/numpy/blob/master/numpy/lib/format.py
23
+ @classmethod
24
+ def _read_npy(cls, file_path):
25
+ return np.load(file_path)
26
+
27
+ # References: https://github.com/dimatura/pypcd/blob/master/pypcd/pypcd.py#L275
28
+ # Support PCD files without compression ONLY!
29
+ @classmethod
30
+ def _read_pcd(cls, file_path):
31
+ pc = open3d.io.read_point_cloud(file_path)
32
+ ptcloud = np.array(pc.points)
33
+ return ptcloud
34
+
35
+ @classmethod
36
+ def _read_txt(cls, file_path):
37
+ return np.loadtxt(file_path)
38
+
39
+ @classmethod
40
+ def _read_h5(cls, file_path):
41
+ f = h5py.File(file_path, 'r')
42
+ return f['data'][()]