OpenFace-CQUPT
commited on
Commit
•
3d7aa36
1
Parent(s):
37be766
Upload 16 files
Browse files- ckpt/FLIP-FaceCaption-15M.pth +3 -0
- configs/bert_config.json +21 -0
- configs/pretrain.yaml +28 -0
- configs/vision_config.json +17 -0
- data/__init__.py +61 -0
- data/facecaption_dataset.py +97 -0
- data/randaugment.py +374 -0
- data/utils.py +112 -0
- eval/pretrain_eval.py +156 -0
- models/__init__.py +0 -0
- models/fflip.py +468 -0
- models/fflip_pretrain.py +314 -0
- models/mm.py +1652 -0
- models/utils.py +548 -0
- pretrain.py +202 -0
- utils.py +278 -0
ckpt/FLIP-FaceCaption-15M.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b5d00a8eaff814d33c9900b0699f954b40c1883dee436e2607fc4881a09a1e37
|
3 |
+
size 3702484906
|
configs/bert_config.json
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"BertModel"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"hidden_act": "gelu",
|
7 |
+
"hidden_dropout_prob": 0.1,
|
8 |
+
"hidden_size": 768,
|
9 |
+
"initializer_range": 0.02,
|
10 |
+
"intermediate_size": 3072,
|
11 |
+
"layer_norm_eps": 1e-12,
|
12 |
+
"max_position_embeddings": 512,
|
13 |
+
"model_type": "bert",
|
14 |
+
"num_attention_heads": 12,
|
15 |
+
"num_hidden_layers": 12,
|
16 |
+
"pad_token_id": 0,
|
17 |
+
"type_vocab_size": 2,
|
18 |
+
"vocab_size": 30522,
|
19 |
+
"encoder_width": 768,
|
20 |
+
"add_cross_attention": true
|
21 |
+
}
|
configs/pretrain.yaml
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
image_root: '' # for image path
|
2 |
+
ann_root: '' # for json path
|
3 |
+
dataset: 'facecaption'
|
4 |
+
|
5 |
+
config: './configs'
|
6 |
+
|
7 |
+
|
8 |
+
pretrained: ''
|
9 |
+
intermediate_hidden_state: False
|
10 |
+
|
11 |
+
# size of vit model; base or large
|
12 |
+
vit: 'base'
|
13 |
+
image_size: 224
|
14 |
+
batch_size_train: 80
|
15 |
+
batch_size_test: 80
|
16 |
+
|
17 |
+
queue_size: 61440
|
18 |
+
alpha: 0.4
|
19 |
+
k_test: 256
|
20 |
+
|
21 |
+
# optimizer
|
22 |
+
weight_decay: 0.05
|
23 |
+
init_lr: 3e-5
|
24 |
+
min_lr: 1e-6
|
25 |
+
warmup_lr: 1e-6
|
26 |
+
lr_decay_rate: 0.9
|
27 |
+
max_epoch: 15
|
28 |
+
warmup_steps: 20000
|
configs/vision_config.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"attention_dropout": 0.0,
|
3 |
+
"hidden_act": "quick_gelu",
|
4 |
+
"hidden_size": 768,
|
5 |
+
"image_size": 224,
|
6 |
+
"initializer_factor": 1.0,
|
7 |
+
"initializer_range": 0.02,
|
8 |
+
"intermediate_size": 3072,
|
9 |
+
"layer_norm_eps": 1e-05,
|
10 |
+
"model_type": "clip_vision_model",
|
11 |
+
"num_attention_heads": 12,
|
12 |
+
"num_channels": 3,
|
13 |
+
"num_hidden_layers": 12,
|
14 |
+
"patch_size": 16,
|
15 |
+
"projection_dim": 512,
|
16 |
+
"intermediate_transformer_output": [4, 6, 8]
|
17 |
+
}
|
data/__init__.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils.data import DataLoader
|
3 |
+
from torchvision import transforms
|
4 |
+
from torchvision.transforms.functional import InterpolationMode
|
5 |
+
from data.facecaption_dataset import facecaption_train, facecaption_test
|
6 |
+
from data.randaugment import RandomAugment
|
7 |
+
|
8 |
+
def create_dataset(dataset, config, min_scale=0.5):
|
9 |
+
|
10 |
+
normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
|
11 |
+
|
12 |
+
transform_train = transforms.Compose([
|
13 |
+
transforms.Resize((config['image_size'], config['image_size']),interpolation=InterpolationMode.BICUBIC),
|
14 |
+
transforms.RandomHorizontalFlip(),
|
15 |
+
RandomAugment(2,5,isPIL=True,augs=['Identity','Brightness','Sharpness','Equalize',
|
16 |
+
'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']),
|
17 |
+
transforms.ToTensor(),
|
18 |
+
normalize,
|
19 |
+
])
|
20 |
+
transform_test = transforms.Compose([
|
21 |
+
transforms.Resize((config['image_size'], config['image_size']),interpolation=InterpolationMode.BICUBIC),
|
22 |
+
transforms.ToTensor(),
|
23 |
+
normalize,
|
24 |
+
])
|
25 |
+
|
26 |
+
if dataset=='facecaption':
|
27 |
+
train_dataset = facecaption_train(transform_train, config['image_root'], config['ann_root'])
|
28 |
+
eval_dataset = facecaption_test(transform_test, config['image_root'], config['ann_root'])
|
29 |
+
return train_dataset, eval_dataset
|
30 |
+
|
31 |
+
|
32 |
+
def create_sampler(datasets, shuffles, num_tasks, global_rank):
|
33 |
+
samplers = []
|
34 |
+
for dataset,shuffle in zip(datasets,shuffles):
|
35 |
+
sampler = torch.utils.data.DistributedSampler(dataset, num_replicas=num_tasks, rank=global_rank, shuffle=shuffle)
|
36 |
+
samplers.append(sampler)
|
37 |
+
return samplers
|
38 |
+
|
39 |
+
|
40 |
+
def create_loader(datasets, samplers, batch_size, num_workers, is_trains, collate_fns):
|
41 |
+
loaders = []
|
42 |
+
for dataset,sampler,bs,n_worker,is_train,collate_fn in zip(datasets,samplers,batch_size,num_workers,is_trains,collate_fns):
|
43 |
+
if is_train:
|
44 |
+
shuffle = (sampler is None)
|
45 |
+
drop_last = True
|
46 |
+
else:
|
47 |
+
shuffle = False
|
48 |
+
drop_last = False
|
49 |
+
loader = DataLoader(
|
50 |
+
dataset,
|
51 |
+
batch_size=bs,
|
52 |
+
num_workers=n_worker,
|
53 |
+
pin_memory=True,
|
54 |
+
sampler=sampler,
|
55 |
+
shuffle=shuffle,
|
56 |
+
collate_fn=collate_fn,
|
57 |
+
drop_last=drop_last,
|
58 |
+
)
|
59 |
+
loaders.append(loader)
|
60 |
+
return loaders
|
61 |
+
|
data/facecaption_dataset.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import torch
|
4 |
+
from torch.utils.data import Dataset
|
5 |
+
from torchvision.datasets.utils import download_url
|
6 |
+
from PIL import Image, ImageFile
|
7 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
8 |
+
from glob import glob
|
9 |
+
from data.utils import pre_caption
|
10 |
+
|
11 |
+
|
12 |
+
class facecaption_train(Dataset):
|
13 |
+
def __init__(self, transform, image_root, ann_root, max_words=65, prompt=''):
|
14 |
+
'''
|
15 |
+
image_root (string): Root directory of images (e.g. coco/images/)
|
16 |
+
ann_root (string): directory to store the annotation file
|
17 |
+
'''
|
18 |
+
all_json = sorted(glob(os.path.join(ann_root, '*.json')))
|
19 |
+
self.annotation = []
|
20 |
+
for json_path in all_json[0:1]:
|
21 |
+
# for json_path in all_json[:-1]:
|
22 |
+
with open(json_path, 'r') as json_file:
|
23 |
+
data = json.load(json_file)
|
24 |
+
self.annotation.extend(data)
|
25 |
+
|
26 |
+
self.transform = transform
|
27 |
+
self.image_root = image_root
|
28 |
+
self.max_words = max_words
|
29 |
+
self.prompt = prompt
|
30 |
+
|
31 |
+
self.img_ids = {}
|
32 |
+
n = 0
|
33 |
+
for ann in self.annotation:
|
34 |
+
img_id = ann['image_id']#[7:]
|
35 |
+
if img_id not in self.img_ids.keys():
|
36 |
+
self.img_ids[img_id] = n
|
37 |
+
n += 1
|
38 |
+
|
39 |
+
def __len__(self):
|
40 |
+
return len(self.annotation)
|
41 |
+
|
42 |
+
def __getitem__(self, index):
|
43 |
+
|
44 |
+
ann = self.annotation[index]
|
45 |
+
image_path = os.path.join(self.image_root, ann['image'])
|
46 |
+
image = Image.open(image_path).convert('RGB')
|
47 |
+
image = self.transform(image)
|
48 |
+
|
49 |
+
|
50 |
+
caption = self.prompt + pre_caption(*ann['caption'], self.max_words)
|
51 |
+
image_id = self.img_ids[ann['image_id']]
|
52 |
+
return image, caption, image_id
|
53 |
+
|
54 |
+
|
55 |
+
class facecaption_test(Dataset):
|
56 |
+
def __init__(self, transform, image_root, ann_root, max_words=65):
|
57 |
+
'''
|
58 |
+
image_root (string): Root directory of images (e.g. coco/images/)
|
59 |
+
ann_root (string): directory to store the annotation file
|
60 |
+
'''
|
61 |
+
all_json = sorted(glob(os.path.join(ann_root, '*.json')))
|
62 |
+
self.annotation = []
|
63 |
+
for json_path in all_json[-1:]:
|
64 |
+
with open(json_path, 'r') as json_file:
|
65 |
+
data = json.load(json_file)
|
66 |
+
self.annotation.extend(data)
|
67 |
+
self.annotation = self.annotation[:5000]
|
68 |
+
|
69 |
+
self.transform = transform
|
70 |
+
self.image_root = image_root
|
71 |
+
|
72 |
+
self.text = []
|
73 |
+
self.image = []
|
74 |
+
self.txt2img = {}
|
75 |
+
self.img2txt = {}
|
76 |
+
|
77 |
+
txt_id = 0
|
78 |
+
for img_id, ann in enumerate(self.annotation):
|
79 |
+
self.image.append(ann['image'])
|
80 |
+
self.img2txt[img_id] = []
|
81 |
+
for i, caption in enumerate(ann['caption']):
|
82 |
+
self.text.append(pre_caption(caption, max_words))
|
83 |
+
self.img2txt[img_id].append(txt_id)
|
84 |
+
self.txt2img[txt_id] = img_id
|
85 |
+
txt_id += 1
|
86 |
+
|
87 |
+
def __len__(self):
|
88 |
+
return len(self.annotation)
|
89 |
+
|
90 |
+
def __getitem__(self, index):
|
91 |
+
|
92 |
+
ann = self.annotation[index]
|
93 |
+
|
94 |
+
image_path = os.path.join(self.image_root, ann['image'])
|
95 |
+
image = Image.open(image_path).convert('RGB')
|
96 |
+
image = self.transform(image)
|
97 |
+
return image, index
|
data/randaugment.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
## aug functions
|
6 |
+
def identity_func(img):
|
7 |
+
return img
|
8 |
+
|
9 |
+
|
10 |
+
def autocontrast_func(img, cutoff=0):
|
11 |
+
'''
|
12 |
+
same output as PIL.ImageOps.autocontrast
|
13 |
+
'''
|
14 |
+
n_bins = 256
|
15 |
+
|
16 |
+
def tune_channel(ch):
|
17 |
+
n = ch.size
|
18 |
+
cut = cutoff * n // 100
|
19 |
+
if cut == 0:
|
20 |
+
high, low = ch.max(), ch.min()
|
21 |
+
else:
|
22 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
23 |
+
low = np.argwhere(np.cumsum(hist) > cut)
|
24 |
+
low = 0 if low.shape[0] == 0 else low[0]
|
25 |
+
high = np.argwhere(np.cumsum(hist[::-1]) > cut)
|
26 |
+
high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0]
|
27 |
+
if high <= low:
|
28 |
+
table = np.arange(n_bins)
|
29 |
+
else:
|
30 |
+
scale = (n_bins - 1) / (high - low)
|
31 |
+
offset = -low * scale
|
32 |
+
table = np.arange(n_bins) * scale + offset
|
33 |
+
table[table < 0] = 0
|
34 |
+
table[table > n_bins - 1] = n_bins - 1
|
35 |
+
table = table.clip(0, 255).astype(np.uint8)
|
36 |
+
return table[ch]
|
37 |
+
|
38 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
39 |
+
out = cv2.merge(channels)
|
40 |
+
return out
|
41 |
+
|
42 |
+
|
43 |
+
def equalize_func(img):
|
44 |
+
'''
|
45 |
+
same output as PIL.ImageOps.equalize
|
46 |
+
PIL's implementation is different from cv2.equalize
|
47 |
+
'''
|
48 |
+
n_bins = 256
|
49 |
+
|
50 |
+
def tune_channel(ch):
|
51 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
52 |
+
non_zero_hist = hist[hist != 0].reshape(-1)
|
53 |
+
step = np.sum(non_zero_hist[:-1]) // (n_bins - 1)
|
54 |
+
if step == 0: return ch
|
55 |
+
n = np.empty_like(hist)
|
56 |
+
n[0] = step // 2
|
57 |
+
n[1:] = hist[:-1]
|
58 |
+
table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8)
|
59 |
+
return table[ch]
|
60 |
+
|
61 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
62 |
+
out = cv2.merge(channels)
|
63 |
+
return out
|
64 |
+
|
65 |
+
|
66 |
+
def rotate_func(img, degree, fill=(0, 0, 0)):
|
67 |
+
'''
|
68 |
+
like PIL, rotate by degree, not radians
|
69 |
+
'''
|
70 |
+
H, W = img.shape[0], img.shape[1]
|
71 |
+
center = W / 2, H / 2
|
72 |
+
M = cv2.getRotationMatrix2D(center, degree, 1)
|
73 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill)
|
74 |
+
return out
|
75 |
+
|
76 |
+
|
77 |
+
def solarize_func(img, thresh=128):
|
78 |
+
'''
|
79 |
+
same output as PIL.ImageOps.posterize
|
80 |
+
'''
|
81 |
+
table = np.array([el if el < thresh else 255 - el for el in range(256)])
|
82 |
+
table = table.clip(0, 255).astype(np.uint8)
|
83 |
+
out = table[img]
|
84 |
+
return out
|
85 |
+
|
86 |
+
|
87 |
+
def color_func(img, factor):
|
88 |
+
'''
|
89 |
+
same output as PIL.ImageEnhance.Color
|
90 |
+
'''
|
91 |
+
## implementation according to PIL definition, quite slow
|
92 |
+
# degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis]
|
93 |
+
# out = blend(degenerate, img, factor)
|
94 |
+
# M = (
|
95 |
+
# np.eye(3) * factor
|
96 |
+
# + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor)
|
97 |
+
# )[np.newaxis, np.newaxis, :]
|
98 |
+
M = (
|
99 |
+
np.float32([
|
100 |
+
[0.886, -0.114, -0.114],
|
101 |
+
[-0.587, 0.413, -0.587],
|
102 |
+
[-0.299, -0.299, 0.701]]) * factor
|
103 |
+
+ np.float32([[0.114], [0.587], [0.299]])
|
104 |
+
)
|
105 |
+
out = np.matmul(img, M).clip(0, 255).astype(np.uint8)
|
106 |
+
return out
|
107 |
+
|
108 |
+
|
109 |
+
def contrast_func(img, factor):
|
110 |
+
"""
|
111 |
+
same output as PIL.ImageEnhance.Contrast
|
112 |
+
"""
|
113 |
+
mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299]))
|
114 |
+
table = np.array([(
|
115 |
+
el - mean) * factor + mean
|
116 |
+
for el in range(256)
|
117 |
+
]).clip(0, 255).astype(np.uint8)
|
118 |
+
out = table[img]
|
119 |
+
return out
|
120 |
+
|
121 |
+
|
122 |
+
def brightness_func(img, factor):
|
123 |
+
'''
|
124 |
+
same output as PIL.ImageEnhance.Contrast
|
125 |
+
'''
|
126 |
+
table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8)
|
127 |
+
out = table[img]
|
128 |
+
return out
|
129 |
+
|
130 |
+
|
131 |
+
def sharpness_func(img, factor):
|
132 |
+
'''
|
133 |
+
The differences the this result and PIL are all on the 4 boundaries, the center
|
134 |
+
areas are same
|
135 |
+
'''
|
136 |
+
kernel = np.ones((3, 3), dtype=np.float32)
|
137 |
+
kernel[1][1] = 5
|
138 |
+
kernel /= 13
|
139 |
+
degenerate = cv2.filter2D(img, -1, kernel)
|
140 |
+
if factor == 0.0:
|
141 |
+
out = degenerate
|
142 |
+
elif factor == 1.0:
|
143 |
+
out = img
|
144 |
+
else:
|
145 |
+
out = img.astype(np.float32)
|
146 |
+
degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :]
|
147 |
+
out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate)
|
148 |
+
out = out.astype(np.uint8)
|
149 |
+
return out
|
150 |
+
|
151 |
+
|
152 |
+
def shear_x_func(img, factor, fill=(0, 0, 0)):
|
153 |
+
H, W = img.shape[0], img.shape[1]
|
154 |
+
M = np.float32([[1, factor, 0], [0, 1, 0]])
|
155 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
|
156 |
+
return out
|
157 |
+
|
158 |
+
|
159 |
+
def translate_x_func(img, offset, fill=(0, 0, 0)):
|
160 |
+
'''
|
161 |
+
same output as PIL.Image.transform
|
162 |
+
'''
|
163 |
+
H, W = img.shape[0], img.shape[1]
|
164 |
+
M = np.float32([[1, 0, -offset], [0, 1, 0]])
|
165 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
|
166 |
+
return out
|
167 |
+
|
168 |
+
|
169 |
+
def translate_y_func(img, offset, fill=(0, 0, 0)):
|
170 |
+
'''
|
171 |
+
same output as PIL.Image.transform
|
172 |
+
'''
|
173 |
+
H, W = img.shape[0], img.shape[1]
|
174 |
+
M = np.float32([[1, 0, 0], [0, 1, -offset]])
|
175 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
|
176 |
+
return out
|
177 |
+
|
178 |
+
|
179 |
+
def posterize_func(img, bits):
|
180 |
+
'''
|
181 |
+
same output as PIL.ImageOps.posterize
|
182 |
+
'''
|
183 |
+
out = np.bitwise_and(img, np.uint8(255 << (8 - bits)))
|
184 |
+
return out
|
185 |
+
|
186 |
+
|
187 |
+
def shear_y_func(img, factor, fill=(0, 0, 0)):
|
188 |
+
H, W = img.shape[0], img.shape[1]
|
189 |
+
M = np.float32([[1, 0, 0], [factor, 1, 0]])
|
190 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
|
191 |
+
return out
|
192 |
+
|
193 |
+
|
194 |
+
def cutout_func(img, pad_size, replace=(0, 0, 0)):
|
195 |
+
replace = np.array(replace, dtype=np.uint8)
|
196 |
+
H, W = img.shape[0], img.shape[1]
|
197 |
+
rh, rw = np.random.random(2)
|
198 |
+
pad_size = pad_size // 2
|
199 |
+
ch, cw = int(rh * H), int(rw * W)
|
200 |
+
x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H)
|
201 |
+
y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W)
|
202 |
+
out = img.copy()
|
203 |
+
out[x1:x2, y1:y2, :] = replace
|
204 |
+
return out
|
205 |
+
|
206 |
+
|
207 |
+
### level to args
|
208 |
+
def enhance_level_to_args(MAX_LEVEL):
|
209 |
+
def level_to_args(level):
|
210 |
+
return ((level / MAX_LEVEL) * 1.8 + 0.1,)
|
211 |
+
return level_to_args
|
212 |
+
|
213 |
+
|
214 |
+
def shear_level_to_args(MAX_LEVEL, replace_value):
|
215 |
+
def level_to_args(level):
|
216 |
+
level = (level / MAX_LEVEL) * 0.3
|
217 |
+
if np.random.random() > 0.5: level = -level
|
218 |
+
return (level, replace_value)
|
219 |
+
|
220 |
+
return level_to_args
|
221 |
+
|
222 |
+
|
223 |
+
def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
|
224 |
+
def level_to_args(level):
|
225 |
+
level = (level / MAX_LEVEL) * float(translate_const)
|
226 |
+
if np.random.random() > 0.5: level = -level
|
227 |
+
return (level, replace_value)
|
228 |
+
|
229 |
+
return level_to_args
|
230 |
+
|
231 |
+
|
232 |
+
def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
|
233 |
+
def level_to_args(level):
|
234 |
+
level = int((level / MAX_LEVEL) * cutout_const)
|
235 |
+
return (level, replace_value)
|
236 |
+
|
237 |
+
return level_to_args
|
238 |
+
|
239 |
+
|
240 |
+
def solarize_level_to_args(MAX_LEVEL):
|
241 |
+
def level_to_args(level):
|
242 |
+
level = int((level / MAX_LEVEL) * 256)
|
243 |
+
return (level, )
|
244 |
+
return level_to_args
|
245 |
+
|
246 |
+
|
247 |
+
def none_level_to_args(level):
|
248 |
+
return ()
|
249 |
+
|
250 |
+
|
251 |
+
def posterize_level_to_args(MAX_LEVEL):
|
252 |
+
def level_to_args(level):
|
253 |
+
level = int((level / MAX_LEVEL) * 4)
|
254 |
+
return (level, )
|
255 |
+
return level_to_args
|
256 |
+
|
257 |
+
|
258 |
+
def rotate_level_to_args(MAX_LEVEL, replace_value):
|
259 |
+
def level_to_args(level):
|
260 |
+
level = (level / MAX_LEVEL) * 30
|
261 |
+
if np.random.random() < 0.5:
|
262 |
+
level = -level
|
263 |
+
return (level, replace_value)
|
264 |
+
|
265 |
+
return level_to_args
|
266 |
+
|
267 |
+
|
268 |
+
def adaptive_find_threshold_max_grad_var(src, aperture_size=3):
|
269 |
+
dx = cv2.Sobel(src, cv2.CV_16S, 1, 0, ksize=aperture_size)
|
270 |
+
dy = cv2.Sobel(src, cv2.CV_16S, 0, 1, ksize=aperture_size)
|
271 |
+
abs_grad_x = cv2.convertScaleAbs(dx)
|
272 |
+
abs_grad_y = cv2.convertScaleAbs(dy)
|
273 |
+
img_dxy = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
|
274 |
+
maxv = np.max(img_dxy)
|
275 |
+
hist_size = int(maxv)
|
276 |
+
hist = cv2.calcHist([img_dxy],[0],None,[hist_size],[0,hist_size])
|
277 |
+
HmaxNum = np.argmax(hist)
|
278 |
+
Emax = 0
|
279 |
+
for i in range(len(hist)):
|
280 |
+
N = hist[i]
|
281 |
+
if N > 0:
|
282 |
+
temp = (i - HmaxNum)*(i - HmaxNum) / N
|
283 |
+
temp = temp if temp < 1.0 else 1.0
|
284 |
+
Emax += temp
|
285 |
+
high = HmaxNum + Emax
|
286 |
+
low = high * 0.3
|
287 |
+
return int(low), int(high)
|
288 |
+
|
289 |
+
# def get_edge_func(img):
|
290 |
+
# # convert grayscale
|
291 |
+
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
292 |
+
# img = cv2.equalizeHist(img)
|
293 |
+
# low, high = adaptive_find_threshold_max_grad_var(img)
|
294 |
+
# # low, high = adaptive_find_threshold_median(img)
|
295 |
+
# # print(low, high)
|
296 |
+
# img_canny = 255 - cv2.Canny(img, low, high)
|
297 |
+
# # 变为3通道
|
298 |
+
# img_canny = cv2.cvtColor(img_canny, cv2.COLOR_GRAY2BGR)
|
299 |
+
# return img_canny
|
300 |
+
|
301 |
+
|
302 |
+
func_dict = {
|
303 |
+
'Identity': identity_func,
|
304 |
+
'AutoContrast': autocontrast_func,
|
305 |
+
'Equalize': equalize_func,
|
306 |
+
'Rotate': rotate_func,
|
307 |
+
'Solarize': solarize_func,
|
308 |
+
'Color': color_func,
|
309 |
+
'Contrast': contrast_func,
|
310 |
+
'Brightness': brightness_func,
|
311 |
+
'Sharpness': sharpness_func,
|
312 |
+
'ShearX': shear_x_func,
|
313 |
+
'TranslateX': translate_x_func,
|
314 |
+
'TranslateY': translate_y_func,
|
315 |
+
'Posterize': posterize_func,
|
316 |
+
'ShearY': shear_y_func,
|
317 |
+
}
|
318 |
+
|
319 |
+
translate_const = 10
|
320 |
+
MAX_LEVEL = 10
|
321 |
+
replace_value = (128, 128, 128)
|
322 |
+
arg_dict = {
|
323 |
+
'Identity': none_level_to_args,
|
324 |
+
'AutoContrast': none_level_to_args,
|
325 |
+
'Equalize': none_level_to_args,
|
326 |
+
'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value),
|
327 |
+
'Solarize': solarize_level_to_args(MAX_LEVEL),
|
328 |
+
'Color': enhance_level_to_args(MAX_LEVEL),
|
329 |
+
'Contrast': enhance_level_to_args(MAX_LEVEL),
|
330 |
+
'Brightness': enhance_level_to_args(MAX_LEVEL),
|
331 |
+
'Sharpness': enhance_level_to_args(MAX_LEVEL),
|
332 |
+
'ShearX': shear_level_to_args(MAX_LEVEL, replace_value),
|
333 |
+
'TranslateX': translate_level_to_args(
|
334 |
+
translate_const, MAX_LEVEL, replace_value
|
335 |
+
),
|
336 |
+
'TranslateY': translate_level_to_args(
|
337 |
+
translate_const, MAX_LEVEL, replace_value
|
338 |
+
),
|
339 |
+
'Posterize': posterize_level_to_args(MAX_LEVEL),
|
340 |
+
'ShearY': shear_level_to_args(MAX_LEVEL, replace_value),
|
341 |
+
}
|
342 |
+
|
343 |
+
|
344 |
+
class RandomAugment(object):
|
345 |
+
|
346 |
+
def __init__(self, N=2, M=10, isPIL=False, augs=[]):
|
347 |
+
self.N = N
|
348 |
+
self.M = M
|
349 |
+
self.isPIL = isPIL
|
350 |
+
if augs:
|
351 |
+
self.augs = augs
|
352 |
+
else:
|
353 |
+
self.augs = list(arg_dict.keys())
|
354 |
+
|
355 |
+
def get_random_ops(self):
|
356 |
+
sampled_ops = np.random.choice(self.augs, self.N)
|
357 |
+
return [(op, 0.5, self.M) for op in sampled_ops]
|
358 |
+
|
359 |
+
def __call__(self, img):
|
360 |
+
if self.isPIL:
|
361 |
+
img = np.array(img)
|
362 |
+
ops = self.get_random_ops()
|
363 |
+
for name, prob, level in ops:
|
364 |
+
if np.random.random() > prob:
|
365 |
+
continue
|
366 |
+
args = arg_dict[name](level)
|
367 |
+
img = func_dict[name](img, *args)
|
368 |
+
return img
|
369 |
+
|
370 |
+
|
371 |
+
if __name__ == '__main__':
|
372 |
+
a = RandomAugment()
|
373 |
+
img = np.random.randn(32, 32, 3)
|
374 |
+
a(img)
|
data/utils.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.distributed as dist
|
7 |
+
|
8 |
+
from models import utils
|
9 |
+
|
10 |
+
def pre_caption(caption,max_words=50):
|
11 |
+
caption = re.sub(
|
12 |
+
r"([.!\"()*#:;~])",
|
13 |
+
' ',
|
14 |
+
caption.lower(),
|
15 |
+
)
|
16 |
+
caption = re.sub(
|
17 |
+
r"\s{2,}",
|
18 |
+
' ',
|
19 |
+
caption,
|
20 |
+
)
|
21 |
+
caption = caption.rstrip('\n')
|
22 |
+
caption = caption.strip(' ')
|
23 |
+
|
24 |
+
#truncate caption
|
25 |
+
caption_words = caption.split(' ')
|
26 |
+
if len(caption_words)>max_words:
|
27 |
+
caption = ' '.join(caption_words[:max_words])
|
28 |
+
|
29 |
+
return caption
|
30 |
+
|
31 |
+
def pre_question(question,max_ques_words=50):
|
32 |
+
question = re.sub(
|
33 |
+
r"([.!\"()*#:;~])",
|
34 |
+
'',
|
35 |
+
question.lower(),
|
36 |
+
)
|
37 |
+
question = question.rstrip(' ')
|
38 |
+
|
39 |
+
#truncate question
|
40 |
+
question_words = question.split(' ')
|
41 |
+
if len(question_words)>max_ques_words:
|
42 |
+
question = ' '.join(question_words[:max_ques_words])
|
43 |
+
|
44 |
+
return question
|
45 |
+
|
46 |
+
|
47 |
+
def save_result(result, result_dir, filename, remove_duplicate=''):
|
48 |
+
result_file = os.path.join(result_dir, '%s_rank%d.json'%(filename,utils.get_rank()))
|
49 |
+
final_result_file = os.path.join(result_dir, '%s.json'%filename)
|
50 |
+
|
51 |
+
json.dump(result,open(result_file,'w'))
|
52 |
+
|
53 |
+
dist.barrier()
|
54 |
+
|
55 |
+
if utils.is_main_process():
|
56 |
+
# combine results from all processes
|
57 |
+
result = []
|
58 |
+
|
59 |
+
for rank in range(utils.get_world_size()):
|
60 |
+
result_file = os.path.join(result_dir, '%s_rank%d.json'%(filename,rank))
|
61 |
+
res = json.load(open(result_file,'r'))
|
62 |
+
result += res
|
63 |
+
|
64 |
+
if remove_duplicate:
|
65 |
+
result_new = []
|
66 |
+
id_list = []
|
67 |
+
for res in result:
|
68 |
+
if res[remove_duplicate] not in id_list:
|
69 |
+
id_list.append(res[remove_duplicate])
|
70 |
+
result_new.append(res)
|
71 |
+
result = result_new
|
72 |
+
|
73 |
+
json.dump(result,open(final_result_file,'w'))
|
74 |
+
print('result file saved to %s'%final_result_file)
|
75 |
+
|
76 |
+
return final_result_file
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
from pycocotools.coco import COCO
|
81 |
+
from pycocoevalcap.eval import COCOEvalCap
|
82 |
+
from torchvision.datasets.utils import download_url
|
83 |
+
|
84 |
+
def coco_caption_eval(coco_gt_root, results_file, split):
|
85 |
+
urls = {'val':'https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json',
|
86 |
+
'test':'https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json'}
|
87 |
+
filenames = {'val':'coco_karpathy_val_gt.json','test':'coco_karpathy_test_gt.json'}
|
88 |
+
|
89 |
+
download_url(urls[split],coco_gt_root)
|
90 |
+
annotation_file = os.path.join(coco_gt_root,filenames[split])
|
91 |
+
|
92 |
+
# create coco object and coco_result object
|
93 |
+
coco = COCO(annotation_file)
|
94 |
+
coco_result = coco.loadRes(results_file)
|
95 |
+
|
96 |
+
# create coco_eval object by taking coco and coco_result
|
97 |
+
coco_eval = COCOEvalCap(coco, coco_result)
|
98 |
+
|
99 |
+
# evaluate on a subset of images by setting
|
100 |
+
# coco_eval.params['image_id'] = coco_result.getImgIds()
|
101 |
+
# please remove this line when evaluating the full validation set
|
102 |
+
# coco_eval.params['image_id'] = coco_result.getImgIds()
|
103 |
+
|
104 |
+
# evaluate results
|
105 |
+
# SPICE will take a few minutes the first time, but speeds up due to caching
|
106 |
+
coco_eval.evaluate()
|
107 |
+
|
108 |
+
# print output evaluation scores
|
109 |
+
for metric, score in coco_eval.eval.items():
|
110 |
+
print(f'{metric}: {score:.3f}')
|
111 |
+
|
112 |
+
return coco_eval
|
eval/pretrain_eval.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import time
|
3 |
+
import datetime
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
import torch.distributed as dist
|
7 |
+
from models import utils
|
8 |
+
|
9 |
+
@torch.no_grad()
|
10 |
+
def evaluation(args, model, data_loader, device, config):
|
11 |
+
# test
|
12 |
+
model.eval()
|
13 |
+
|
14 |
+
metric_logger = utils.MetricLogger(delimiter=" ")
|
15 |
+
header = 'Evaluation:'
|
16 |
+
|
17 |
+
print('Computing features for evaluation...')
|
18 |
+
start_time = time.time()
|
19 |
+
num_tasks = utils.get_world_size()
|
20 |
+
rank = utils.get_rank()
|
21 |
+
|
22 |
+
# ======================================== text feature ======================================== #
|
23 |
+
texts = data_loader.dataset.text
|
24 |
+
num_text = len(texts)
|
25 |
+
text_bs = 256
|
26 |
+
text_ids = []
|
27 |
+
text_embeds = []
|
28 |
+
text_atts = []
|
29 |
+
for i in range(0, num_text, text_bs):
|
30 |
+
text = texts[i: min(num_text, i + text_bs)]
|
31 |
+
text_input = model.tokenizer(text, padding='max_length', truncation=True, max_length=65,
|
32 |
+
return_tensors="pt").to(device)
|
33 |
+
text_feat = model.text_encoder(text_input.input_ids, attention_mask=text_input.attention_mask, mode='text')
|
34 |
+
text_embed = F.normalize(model.text_proj(text_feat.last_hidden_state[:,0,:]), dim=-1)
|
35 |
+
text_embeds.append(text_embed)
|
36 |
+
text_ids.append(text_input.input_ids)
|
37 |
+
text_atts.append(text_input.attention_mask)
|
38 |
+
|
39 |
+
text_embeds = torch.cat(text_embeds, dim=0)
|
40 |
+
text_ids = torch.cat(text_ids, dim=0)
|
41 |
+
text_atts = torch.cat(text_atts, dim=0)
|
42 |
+
|
43 |
+
# ======================================== image&sketch feature ======================================== #
|
44 |
+
image_feats = []
|
45 |
+
image_embeds = []
|
46 |
+
for i, (image, img_id) in enumerate(data_loader):
|
47 |
+
image = image.to(device)
|
48 |
+
image_feat = model.visual_encoder(image).last_hidden_state
|
49 |
+
image_embed = F.normalize(model.vision_proj(image_feat[:,0,:]), dim=-1)
|
50 |
+
|
51 |
+
image_feats.append(image_feat.cpu())
|
52 |
+
image_embeds.append(image_embed)
|
53 |
+
|
54 |
+
image_feats = torch.cat(image_feats, dim=0).to(device)
|
55 |
+
image_embeds = torch.cat(image_embeds, dim=0).to(device)
|
56 |
+
print('Computing features Cost time {}'.format(time.time() - start_time))
|
57 |
+
|
58 |
+
# ======================================== i2t score ======================================== #
|
59 |
+
sims_matrix = image_embeds @ text_embeds.t()
|
60 |
+
score_matrix_i2t = torch.full((len(data_loader.dataset.image), len(texts)), -100.0).to(device)
|
61 |
+
step = sims_matrix.size(0) // num_tasks + 1
|
62 |
+
start = rank * step
|
63 |
+
end = min(sims_matrix.size(0), start + step)
|
64 |
+
|
65 |
+
for i, sims in enumerate(metric_logger.log_every(sims_matrix[start:end], 50, header)):
|
66 |
+
topk_sim, topk_idx = sims.topk(k=config['k_test'], dim=0)
|
67 |
+
|
68 |
+
encoder_output = image_feats[start + i].repeat(config['k_test'], 1, 1).to(device)
|
69 |
+
encoder_att = torch.ones(encoder_output.size()[:-1], dtype=torch.long).to(device)
|
70 |
+
output = model.text_encoder(text_ids[topk_idx],
|
71 |
+
attention_mask=text_atts[topk_idx],
|
72 |
+
encoder_hidden_states=encoder_output,
|
73 |
+
encoder_attention_mask=encoder_att,
|
74 |
+
return_dict=True,
|
75 |
+
)
|
76 |
+
score = model.itm_head(output.last_hidden_state[:, 0, :])[:, 1]
|
77 |
+
score_matrix_i2t[start + i, topk_idx] = score + topk_sim
|
78 |
+
|
79 |
+
# ======================================== t2i score ======================================== #
|
80 |
+
sims_matrix = sims_matrix.t()
|
81 |
+
score_matrix_t2i = torch.full((len(texts), len(data_loader.dataset.image)), -100.0).to(device)
|
82 |
+
|
83 |
+
step = sims_matrix.size(0) // num_tasks + 1
|
84 |
+
start = rank * step
|
85 |
+
end = min(sims_matrix.size(0), start + step)
|
86 |
+
for i, sims in enumerate(metric_logger.log_every(sims_matrix[start:end], 50, header)):
|
87 |
+
topk_sim, topk_idx = sims.topk(k=config['k_test'], dim=0)
|
88 |
+
encoder_output = image_feats[topk_idx].to(device)
|
89 |
+
encoder_att = torch.ones(encoder_output.size()[:-1], dtype=torch.long).to(device)
|
90 |
+
output = model.text_encoder(text_ids[start + i].repeat(config['k_test'], 1),
|
91 |
+
attention_mask=text_atts[start + i].repeat(config['k_test'], 1),
|
92 |
+
encoder_hidden_states=encoder_output,
|
93 |
+
encoder_attention_mask=encoder_att,
|
94 |
+
return_dict=True,
|
95 |
+
)
|
96 |
+
score = model.itm_head(output.last_hidden_state[:, 0, :])[:, 1]
|
97 |
+
score_matrix_t2i[start + i, topk_idx] = topk_sim + score
|
98 |
+
|
99 |
+
if args.distributed:
|
100 |
+
dist.barrier()
|
101 |
+
torch.distributed.all_reduce(score_matrix_i2t, op=torch.distributed.ReduceOp.SUM)
|
102 |
+
torch.distributed.all_reduce(score_matrix_t2i, op=torch.distributed.ReduceOp.SUM)
|
103 |
+
|
104 |
+
total_time = time.time() - start_time
|
105 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
106 |
+
print('Evaluation time {}'.format(total_time_str))
|
107 |
+
|
108 |
+
return score_matrix_i2t.cpu().numpy(), score_matrix_t2i.cpu().numpy()
|
109 |
+
|
110 |
+
|
111 |
+
@torch.no_grad()
|
112 |
+
def itm_eval(scores_i2t, scores_t2i, txt2img, img2txt):
|
113 |
+
# Images->Text
|
114 |
+
ranks = np.zeros(scores_i2t.shape[0])
|
115 |
+
for index, score in enumerate(scores_i2t):
|
116 |
+
inds = np.argsort(score)[::-1]
|
117 |
+
# Score
|
118 |
+
rank = 1e20
|
119 |
+
for i in img2txt[index]:
|
120 |
+
tmp = np.where(inds == i)[0][0]
|
121 |
+
if tmp < rank:
|
122 |
+
rank = tmp
|
123 |
+
ranks[index] = rank
|
124 |
+
|
125 |
+
# Compute metrics
|
126 |
+
tr1 = 100.0 * len(np.where(ranks < 1)[0]) / len(ranks)
|
127 |
+
tr5 = 100.0 * len(np.where(ranks < 5)[0]) / len(ranks)
|
128 |
+
tr10 = 100.0 * len(np.where(ranks < 10)[0]) / len(ranks)
|
129 |
+
|
130 |
+
# Text->Images
|
131 |
+
ranks = np.zeros(scores_t2i.shape[0])
|
132 |
+
|
133 |
+
for index, score in enumerate(scores_t2i):
|
134 |
+
inds = np.argsort(score)[::-1]
|
135 |
+
ranks[index] = np.where(inds == txt2img[index])[0][0]
|
136 |
+
|
137 |
+
# Compute metrics
|
138 |
+
ir1 = 100.0 * len(np.where(ranks < 1)[0]) / len(ranks)
|
139 |
+
ir5 = 100.0 * len(np.where(ranks < 5)[0]) / len(ranks)
|
140 |
+
ir10 = 100.0 * len(np.where(ranks < 10)[0]) / len(ranks)
|
141 |
+
|
142 |
+
tr_mean = (tr1 + tr5 + tr10) / 3
|
143 |
+
ir_mean = (ir1 + ir5 + ir10) / 3
|
144 |
+
r_mean = (tr_mean + ir_mean) / 2
|
145 |
+
|
146 |
+
eval_result = {
|
147 |
+
'txt_r1': tr1,
|
148 |
+
'txt_r5': tr5,
|
149 |
+
'txt_r10': tr10,
|
150 |
+
'txt_r_mean': tr_mean,
|
151 |
+
'img_r1': ir1,
|
152 |
+
'img_r5': ir5,
|
153 |
+
'img_r10': ir10,
|
154 |
+
'img_r_mean': ir_mean,
|
155 |
+
'r_mean': r_mean}
|
156 |
+
return eval_result
|
models/__init__.py
ADDED
File without changes
|
models/fflip.py
ADDED
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
@file fflip.py
|
3 |
+
@brief This file contains the code for the multimodal model. It is a modified version of the CLIP model from the huggingface transformers library.
|
4 |
+
@author yutangli
|
5 |
+
"""
|
6 |
+
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
11 |
+
from transformers.utils import logging
|
12 |
+
from typing import Optional, Union, Tuple
|
13 |
+
from torch import Tensor, device, dtype, nn
|
14 |
+
from transformers import BertTokenizer
|
15 |
+
|
16 |
+
import os
|
17 |
+
from urllib.parse import urlparse
|
18 |
+
from timm.models.hub import download_cached_file
|
19 |
+
|
20 |
+
from transformers.modeling_outputs import (
|
21 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
22 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
23 |
+
CausalLMOutputWithCrossAttentions,
|
24 |
+
MaskedLMOutput,
|
25 |
+
MultipleChoiceModelOutput,
|
26 |
+
NextSentencePredictorOutput,
|
27 |
+
QuestionAnsweringModelOutput,
|
28 |
+
SequenceClassifierOutput,
|
29 |
+
TokenClassifierOutput,
|
30 |
+
)
|
31 |
+
|
32 |
+
from models.mm import (
|
33 |
+
VisionTrainedModel,
|
34 |
+
BertEmbeddings,
|
35 |
+
BertEncoder,
|
36 |
+
BertPreTrainedModel,
|
37 |
+
BertPooler,
|
38 |
+
BertConfig,
|
39 |
+
VisionConfig,
|
40 |
+
VisionTransformer)
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
|
45 |
+
def init_tokenizer():
|
46 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
47 |
+
tokenizer.add_special_tokens({'bos_token':'[DEC]'})
|
48 |
+
tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']})
|
49 |
+
tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0]
|
50 |
+
return tokenizer
|
51 |
+
|
52 |
+
|
53 |
+
class VisionModel(VisionTrainedModel):
|
54 |
+
config_class = VisionConfig
|
55 |
+
main_input_name = "pixel_values"
|
56 |
+
|
57 |
+
def __init__(self, config: VisionConfig):
|
58 |
+
super().__init__(config)
|
59 |
+
self.vision_model = VisionTransformer(config)
|
60 |
+
# Initialize weights and apply final processing
|
61 |
+
self.post_init()
|
62 |
+
|
63 |
+
def get_input_embeddings(self) -> nn.Module:
|
64 |
+
return self.vision_model.embeddings.patch_embedding
|
65 |
+
|
66 |
+
@staticmethod
|
67 |
+
def get_output_channel(model_type):
|
68 |
+
if model_type == 'base':
|
69 |
+
return 768
|
70 |
+
if model_type == 'large':
|
71 |
+
return 1024
|
72 |
+
if model_type == 'huge':
|
73 |
+
return 1280
|
74 |
+
|
75 |
+
@staticmethod
|
76 |
+
def get_default_output_indices(model_type):
|
77 |
+
if model_type == 'base':
|
78 |
+
return [3, 5, 7, 11]
|
79 |
+
if model_type == 'large':
|
80 |
+
return [7, 11, 15, 23]
|
81 |
+
if model_type == 'huge':
|
82 |
+
return [8, 14, 20, 31]
|
83 |
+
|
84 |
+
def forward(
|
85 |
+
self,
|
86 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
87 |
+
output_attentions: Optional[bool] = None,
|
88 |
+
output_hidden_states: Optional[bool] = None,
|
89 |
+
return_dict: Optional[bool] = None,
|
90 |
+
intermediate_hidden_state: Optional[bool] = None
|
91 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
92 |
+
r"""
|
93 |
+
Returns:
|
94 |
+
|
95 |
+
Examples:
|
96 |
+
|
97 |
+
```python
|
98 |
+
>>> from PIL import Image
|
99 |
+
>>> import requests
|
100 |
+
>>> from transformers import AutoProcessor, CLIPVisionModel
|
101 |
+
|
102 |
+
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
103 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
104 |
+
|
105 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
106 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
107 |
+
|
108 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
109 |
+
|
110 |
+
>>> outputs = model(**inputs)
|
111 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
112 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
113 |
+
```"""
|
114 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
115 |
+
|
116 |
+
return self.vision_model(
|
117 |
+
pixel_values=pixel_values,
|
118 |
+
output_attentions=output_attentions,
|
119 |
+
output_hidden_states=output_hidden_states,
|
120 |
+
return_dict=return_dict,
|
121 |
+
intermediate_hidden_state=intermediate_hidden_state
|
122 |
+
)
|
123 |
+
|
124 |
+
|
125 |
+
class BertModel(BertPreTrainedModel):
|
126 |
+
"""
|
127 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
128 |
+
cross-attention is added between the self-attention layers, following the architecture described in `Attention is
|
129 |
+
all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
130 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
131 |
+
argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
|
132 |
+
input to the forward pass.
|
133 |
+
"""
|
134 |
+
|
135 |
+
def __init__(self, config, add_pooling_layer=True):
|
136 |
+
super().__init__(config)
|
137 |
+
self.config = config
|
138 |
+
|
139 |
+
self.embeddings = BertEmbeddings(config)
|
140 |
+
|
141 |
+
self.encoder = BertEncoder(config)
|
142 |
+
|
143 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
144 |
+
|
145 |
+
self.init_weights()
|
146 |
+
|
147 |
+
|
148 |
+
def get_input_embeddings(self):
|
149 |
+
return self.embeddings.word_embeddings
|
150 |
+
|
151 |
+
def set_input_embeddings(self, value):
|
152 |
+
self.embeddings.word_embeddings = value
|
153 |
+
|
154 |
+
def _prune_heads(self, heads_to_prune):
|
155 |
+
"""
|
156 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
157 |
+
class PreTrainedModel
|
158 |
+
"""
|
159 |
+
for layer, heads in heads_to_prune.items():
|
160 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
161 |
+
|
162 |
+
|
163 |
+
def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
|
164 |
+
"""
|
165 |
+
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
|
166 |
+
|
167 |
+
Arguments:
|
168 |
+
attention_mask (:obj:`torch.Tensor`):
|
169 |
+
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
|
170 |
+
input_shape (:obj:`Tuple[int]`):
|
171 |
+
The shape of the input to the model.
|
172 |
+
device: (:obj:`torch.device`):
|
173 |
+
The device of the input to the model.
|
174 |
+
|
175 |
+
Returns:
|
176 |
+
:obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
|
177 |
+
"""
|
178 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
179 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
180 |
+
if attention_mask.dim() == 3:
|
181 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
182 |
+
elif attention_mask.dim() == 2:
|
183 |
+
# Provided a padding mask of dimensions [batch_size, seq_length]
|
184 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
185 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
186 |
+
if is_decoder:
|
187 |
+
batch_size, seq_length = input_shape
|
188 |
+
|
189 |
+
seq_ids = torch.arange(seq_length, device=device)
|
190 |
+
causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
|
191 |
+
# in case past_key_values are used we need to add a prefix ones mask to the causal mask
|
192 |
+
# causal and attention masks must have same type with pytorch version < 1.3
|
193 |
+
causal_mask = causal_mask.to(attention_mask.dtype)
|
194 |
+
|
195 |
+
if causal_mask.shape[1] < attention_mask.shape[1]:
|
196 |
+
prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
|
197 |
+
causal_mask = torch.cat(
|
198 |
+
[
|
199 |
+
torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
|
200 |
+
causal_mask,
|
201 |
+
],
|
202 |
+
axis=-1,
|
203 |
+
)
|
204 |
+
|
205 |
+
extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
|
206 |
+
else:
|
207 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
208 |
+
else:
|
209 |
+
raise ValueError(
|
210 |
+
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
|
211 |
+
input_shape, attention_mask.shape
|
212 |
+
)
|
213 |
+
)
|
214 |
+
|
215 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
216 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
217 |
+
# positions we want to attend and -10000.0 for masked positions.
|
218 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
219 |
+
# effectively the same as removing these entirely.
|
220 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
221 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
222 |
+
return extended_attention_mask
|
223 |
+
|
224 |
+
def forward(
|
225 |
+
self,
|
226 |
+
input_ids=None,
|
227 |
+
attention_mask=None,
|
228 |
+
position_ids=None,
|
229 |
+
head_mask=None,
|
230 |
+
inputs_embeds=None,
|
231 |
+
encoder_embeds=None,
|
232 |
+
encoder_hidden_states=None,
|
233 |
+
encoder_attention_mask=None,
|
234 |
+
past_key_values=None,
|
235 |
+
use_cache=None,
|
236 |
+
output_attentions=None,
|
237 |
+
output_hidden_states=None,
|
238 |
+
return_dict=None,
|
239 |
+
is_decoder=False,
|
240 |
+
mode='multimodal',
|
241 |
+
):
|
242 |
+
r"""
|
243 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
244 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
245 |
+
the model is configured as a decoder.
|
246 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
247 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
248 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
|
249 |
+
- 1 for tokens that are **not masked**,
|
250 |
+
- 0 for tokens that are **masked**.
|
251 |
+
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
252 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
253 |
+
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
|
254 |
+
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
|
255 |
+
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
|
256 |
+
use_cache (:obj:`bool`, `optional`):
|
257 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
258 |
+
decoding (see :obj:`past_key_values`).
|
259 |
+
"""
|
260 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
261 |
+
output_hidden_states = (
|
262 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
263 |
+
)
|
264 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
265 |
+
|
266 |
+
if is_decoder:
|
267 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
268 |
+
else:
|
269 |
+
use_cache = False
|
270 |
+
|
271 |
+
if input_ids is not None and inputs_embeds is not None:
|
272 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
273 |
+
elif input_ids is not None:
|
274 |
+
input_shape = input_ids.size()
|
275 |
+
batch_size, seq_length = input_shape
|
276 |
+
device = input_ids.device
|
277 |
+
elif inputs_embeds is not None:
|
278 |
+
input_shape = inputs_embeds.size()[:-1]
|
279 |
+
batch_size, seq_length = input_shape
|
280 |
+
device = inputs_embeds.device
|
281 |
+
elif encoder_embeds is not None:
|
282 |
+
input_shape = encoder_embeds.size()[:-1]
|
283 |
+
batch_size, seq_length = input_shape
|
284 |
+
device = encoder_embeds.device
|
285 |
+
else:
|
286 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
|
287 |
+
|
288 |
+
# past_key_values_length
|
289 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
290 |
+
|
291 |
+
if attention_mask is None:
|
292 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
293 |
+
|
294 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
295 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
296 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
|
297 |
+
device, is_decoder)
|
298 |
+
|
299 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
300 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
301 |
+
if encoder_hidden_states is not None:
|
302 |
+
if type(encoder_hidden_states) == list:
|
303 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
|
304 |
+
else:
|
305 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
306 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
307 |
+
|
308 |
+
if type(encoder_attention_mask) == list:
|
309 |
+
encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
|
310 |
+
elif encoder_attention_mask is None:
|
311 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
312 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
313 |
+
else:
|
314 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
315 |
+
else:
|
316 |
+
encoder_extended_attention_mask = None
|
317 |
+
|
318 |
+
# Prepare head mask if needed
|
319 |
+
# 1.0 in head_mask indicate we keep the head
|
320 |
+
# attention_probs has shape bsz x n_heads x N x N
|
321 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
322 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
323 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
324 |
+
|
325 |
+
if encoder_embeds is None:
|
326 |
+
embedding_output = self.embeddings(
|
327 |
+
input_ids=input_ids,
|
328 |
+
position_ids=position_ids,
|
329 |
+
inputs_embeds=inputs_embeds,
|
330 |
+
past_key_values_length=past_key_values_length,
|
331 |
+
)
|
332 |
+
else:
|
333 |
+
embedding_output = encoder_embeds
|
334 |
+
|
335 |
+
encoder_outputs = self.encoder(
|
336 |
+
embedding_output,
|
337 |
+
attention_mask=extended_attention_mask,
|
338 |
+
head_mask=head_mask,
|
339 |
+
encoder_hidden_states=encoder_hidden_states,
|
340 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
341 |
+
past_key_values=past_key_values,
|
342 |
+
use_cache=use_cache,
|
343 |
+
output_attentions=output_attentions,
|
344 |
+
output_hidden_states=output_hidden_states,
|
345 |
+
return_dict=return_dict,
|
346 |
+
mode=mode,
|
347 |
+
)
|
348 |
+
sequence_output = encoder_outputs[0]
|
349 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
350 |
+
|
351 |
+
if not return_dict:
|
352 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
353 |
+
|
354 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
355 |
+
last_hidden_state=sequence_output,
|
356 |
+
pooler_output=pooled_output,
|
357 |
+
past_key_values=encoder_outputs.past_key_values,
|
358 |
+
hidden_states=encoder_outputs.hidden_states,
|
359 |
+
attentions=encoder_outputs.attentions,
|
360 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
361 |
+
)
|
362 |
+
|
363 |
+
|
364 |
+
class MMSEG_UPerHead(nn.Module):
|
365 |
+
"""Wraps the UPerHead from mmseg for segmentation.
|
366 |
+
"""
|
367 |
+
|
368 |
+
def __init__(self, num_classes: int,
|
369 |
+
in_channels: list = [384, 384, 384, 384], channels: int = 512):
|
370 |
+
super().__init__()
|
371 |
+
|
372 |
+
from mmseg.models.decode_heads import UPerHead
|
373 |
+
self.head = UPerHead(
|
374 |
+
in_channels=in_channels,
|
375 |
+
in_index=[0, 1, 2, 3],
|
376 |
+
pool_scales=(1, 2, 3, 6),
|
377 |
+
channels=channels,
|
378 |
+
dropout_ratio=0.1,
|
379 |
+
num_classes=num_classes,
|
380 |
+
norm_cfg=dict(type='SyncBN', requires_grad=True),
|
381 |
+
align_corners=False,
|
382 |
+
loss_decode=dict(
|
383 |
+
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
|
384 |
+
|
385 |
+
def forward(self, inputs):
|
386 |
+
return self.head(inputs)
|
387 |
+
|
388 |
+
|
389 |
+
def _make_fpns(vision_patch_size: int, output_channels: int):
|
390 |
+
if vision_patch_size in {16, 14}:
|
391 |
+
fpn1 = nn.Sequential(
|
392 |
+
nn.ConvTranspose2d(output_channels, output_channels,
|
393 |
+
kernel_size=2, stride=2),
|
394 |
+
nn.SyncBatchNorm(output_channels),
|
395 |
+
nn.GELU(),
|
396 |
+
nn.ConvTranspose2d(output_channels, output_channels, kernel_size=2, stride=2))
|
397 |
+
|
398 |
+
fpn2 = nn.ConvTranspose2d(
|
399 |
+
output_channels, output_channels, kernel_size=2, stride=2)
|
400 |
+
fpn3 = nn.Identity()
|
401 |
+
fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
|
402 |
+
return nn.ModuleList([fpn1, fpn2, fpn3, fpn4])
|
403 |
+
|
404 |
+
elif vision_patch_size == 8:
|
405 |
+
fpn1 = nn.Sequential(nn.ConvTranspose2d(
|
406 |
+
output_channels, output_channels, kernel_size=2, stride=2))
|
407 |
+
fpn2 = nn.Identity()
|
408 |
+
fpn3 = nn.MaxPool2d(kernel_size=2, stride=2)
|
409 |
+
fpn4 = nn.MaxPool2d(kernel_size=4, stride=4)
|
410 |
+
return nn.ModuleList([fpn1, fpn2, fpn3, fpn4])
|
411 |
+
else:
|
412 |
+
raise NotImplementedError()
|
413 |
+
|
414 |
+
|
415 |
+
def is_url(url_or_filename):
|
416 |
+
parsed = urlparse(url_or_filename)
|
417 |
+
return parsed.scheme in ("http", "https")
|
418 |
+
|
419 |
+
|
420 |
+
def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder):
|
421 |
+
# interpolate position embedding
|
422 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
423 |
+
num_patches = visual_encoder.vision_model.embeddings.num_patches
|
424 |
+
num_extra_tokens = visual_encoder.vision_model.embeddings.position_embedding.weight.shape[-2] - num_patches
|
425 |
+
# height (== width) for the checkpoint position embedding
|
426 |
+
orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
|
427 |
+
# height (== width) for the new position embedding
|
428 |
+
new_size = int(num_patches ** 0.5)
|
429 |
+
|
430 |
+
if orig_size!=new_size:
|
431 |
+
# class_token and dist_token are kept unchanged
|
432 |
+
extra_tokens = pos_embed_checkpoint[:num_extra_tokens, :]
|
433 |
+
# only the position tokens are interpolated
|
434 |
+
pos_tokens = pos_embed_checkpoint[num_extra_tokens:, :]
|
435 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
|
436 |
+
pos_tokens = torch.nn.functional.interpolate(
|
437 |
+
pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
|
438 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2).squeeze(0)
|
439 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=0)
|
440 |
+
print('reshape position embedding from %d to %d'%(orig_size ** 2, new_size ** 2))
|
441 |
+
return new_pos_embed
|
442 |
+
else:
|
443 |
+
return pos_embed_checkpoint
|
444 |
+
|
445 |
+
|
446 |
+
def load_checkpoint(model,url_or_filename):
|
447 |
+
if is_url(url_or_filename):
|
448 |
+
cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
|
449 |
+
checkpoint = torch.load(cached_file, map_location='cpu')
|
450 |
+
elif os.path.isfile(url_or_filename):
|
451 |
+
checkpoint = torch.load(url_or_filename, map_location='cpu')
|
452 |
+
else:
|
453 |
+
raise RuntimeError('checkpoint url or path is invalid')
|
454 |
+
|
455 |
+
state_dict = checkpoint['model']
|
456 |
+
|
457 |
+
state_dict['visual_encoder.vision_model.embeddings.position_embedding.weight'] = interpolate_pos_embed(state_dict['visual_encoder.vision_model.embeddings.position_embedding.weight'], model.visual_encoder)
|
458 |
+
if hasattr(model, " visual_encoder_m") and 'visual_encoder.vision_model.embeddings.position_embedding.weight' in model.state_dict().keys():
|
459 |
+
state_dict['visual_encoder.vision_model.embeddings.position_embedding.weight'] = interpolate_pos_embed(state_dict['visual_encoder.vision_model.embeddings.position_embedding.weight'],
|
460 |
+
model.visual_encoder_m)
|
461 |
+
for key in model.state_dict().keys():
|
462 |
+
if key in state_dict.keys():
|
463 |
+
if state_dict[key].shape!=model.state_dict()[key].shape:
|
464 |
+
del state_dict[key]
|
465 |
+
|
466 |
+
msg = model.load_state_dict(state_dict,strict=False)
|
467 |
+
print('load checkpoint from %s'%url_or_filename)
|
468 |
+
return model, msg
|
models/fflip_pretrain.py
ADDED
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
* Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
* All rights reserved.
|
4 |
+
* SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
* By Junnan Li
|
7 |
+
'''
|
8 |
+
import transformers
|
9 |
+
transformers.logging.set_verbosity_error()
|
10 |
+
import os
|
11 |
+
from models.fflip import (
|
12 |
+
VisionConfig,
|
13 |
+
VisionModel,
|
14 |
+
BertModel,
|
15 |
+
BertConfig,
|
16 |
+
init_tokenizer,
|
17 |
+
load_checkpoint)
|
18 |
+
|
19 |
+
import torch
|
20 |
+
from torch import nn
|
21 |
+
import torch.nn.functional as F
|
22 |
+
from torch.cuda.amp import GradScaler, autocast
|
23 |
+
|
24 |
+
|
25 |
+
class FFLIP_Pretrain(nn.Module):
|
26 |
+
def __init__(self,
|
27 |
+
config = './configs/',
|
28 |
+
vit = 'base',
|
29 |
+
embed_dim = 256,
|
30 |
+
queue_size = 57600,
|
31 |
+
momentum = 0.995
|
32 |
+
):
|
33 |
+
"""
|
34 |
+
Args:
|
35 |
+
med_config (str): path for the mixture of encoder-decoder model's configuration file
|
36 |
+
image_size (int): input image size
|
37 |
+
vit (str): model size of vision transformer
|
38 |
+
"""
|
39 |
+
super().__init__()
|
40 |
+
if vit == 'base':
|
41 |
+
self.vision_config = VisionConfig().from_json_file(os.path.join(config, 'vision_config.json'))
|
42 |
+
self.visual_encoder = VisionModel.from_pretrained("openai/clip-vit-base-patch16", config = self.vision_config)
|
43 |
+
elif vit == 'large':
|
44 |
+
self.vision_config = VisionConfig().from_json_file(os.path.join(config, 'vision_config.json'))
|
45 |
+
self.visual_encoder = VisionModel.from_pretrained("openai/clip-vit-large-patch14", config = self.vision_config)
|
46 |
+
vision_width = self.visual_encoder.config.hidden_size
|
47 |
+
|
48 |
+
self.tokenizer = init_tokenizer()
|
49 |
+
encoder_config = BertConfig.from_json_file(os.path.join(config, 'bert_config.json'))
|
50 |
+
encoder_config.encoder_width = vision_width
|
51 |
+
self.text_encoder = BertModel.from_pretrained('bert-base-uncased',config=encoder_config, add_pooling_layer=False)
|
52 |
+
self.text_encoder.resize_token_embeddings(len(self.tokenizer))
|
53 |
+
text_width = self.text_encoder.config.hidden_size
|
54 |
+
|
55 |
+
self.vision_proj = nn.Linear(vision_width, embed_dim)
|
56 |
+
self.text_proj = nn.Linear(text_width, embed_dim)
|
57 |
+
|
58 |
+
self.itm_head = nn.Linear(text_width, 2)
|
59 |
+
|
60 |
+
# create momentum encoders
|
61 |
+
self.visual_encoder_m = VisionModel(config = self.vision_config)
|
62 |
+
self.text_encoder_m = BertModel(config=encoder_config, add_pooling_layer=False)
|
63 |
+
self.text_encoder_m.resize_token_embeddings(len(self.tokenizer))
|
64 |
+
self.vision_proj_m = nn.Linear(vision_width, embed_dim)
|
65 |
+
self.text_proj_m = nn.Linear(text_width, embed_dim)
|
66 |
+
|
67 |
+
self.model_pairs = [[self.visual_encoder,self.visual_encoder_m],
|
68 |
+
[self.vision_proj,self.vision_proj_m],
|
69 |
+
[self.text_encoder,self.text_encoder_m],
|
70 |
+
[self.text_proj,self.text_proj_m],
|
71 |
+
]
|
72 |
+
self.copy_params()
|
73 |
+
|
74 |
+
# create the queue
|
75 |
+
self.register_buffer("image_queue", torch.randn(embed_dim, queue_size))
|
76 |
+
self.register_buffer("text_queue", torch.randn(embed_dim, queue_size))
|
77 |
+
self.register_buffer("idx_queue", torch.full((1,queue_size),-100))
|
78 |
+
self.register_buffer("ptr_queue", torch.zeros(1, dtype=torch.long))
|
79 |
+
|
80 |
+
self.image_queue = nn.functional.normalize(self.image_queue, dim=0)
|
81 |
+
self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
|
82 |
+
|
83 |
+
self.queue_size = queue_size
|
84 |
+
self.momentum = momentum
|
85 |
+
self.temp = nn.Parameter(0.07*torch.ones([]))
|
86 |
+
|
87 |
+
|
88 |
+
def forward(self, image, caption, alpha, idx):
|
89 |
+
self.train()
|
90 |
+
with torch.no_grad():
|
91 |
+
self.temp.clamp_(0.001,0.5)
|
92 |
+
|
93 |
+
text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=65,
|
94 |
+
return_tensors="pt").to(image.device)
|
95 |
+
|
96 |
+
with autocast():
|
97 |
+
image_output = self.visual_encoder(image)
|
98 |
+
image_embeds = image_output.last_hidden_state
|
99 |
+
image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
|
100 |
+
image_feat = F.normalize(self.vision_proj(image_output.last_hidden_state[:,0,:]), dim=-1)
|
101 |
+
|
102 |
+
text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
|
103 |
+
return_dict = True, mode = 'text')
|
104 |
+
text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
|
105 |
+
|
106 |
+
idx = idx.view(-1,1)
|
107 |
+
idx_all = torch.cat([idx.t(), self.idx_queue.clone().detach()],dim=1)
|
108 |
+
pos_idx = torch.eq(idx, idx_all).float()
|
109 |
+
|
110 |
+
# get momentum features
|
111 |
+
with torch.no_grad():
|
112 |
+
self._momentum_update()
|
113 |
+
image_output_m = self.visual_encoder_m(image)
|
114 |
+
image_feat_m = F.normalize(self.vision_proj_m(image_output_m.last_hidden_state[:,0,:]), dim=-1)
|
115 |
+
image_feat_all = torch.cat([image_feat_m.t(), self.image_queue.clone().detach()], dim=1)
|
116 |
+
|
117 |
+
text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask,
|
118 |
+
return_dict = True, mode = 'text')
|
119 |
+
text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1)
|
120 |
+
text_feat_all = torch.cat([text_feat_m.t(), self.text_queue.clone().detach()],dim=1)
|
121 |
+
|
122 |
+
# print(sim_t2i_m.shape)
|
123 |
+
sim_i2t_m = image_feat_m @ text_feat_all / self.temp
|
124 |
+
sim_t2i_m = text_feat_m @ image_feat_all / self.temp
|
125 |
+
|
126 |
+
sim_targets = torch.zeros(sim_i2t_m.size()).to(image.device)
|
127 |
+
sim_targets.fill_diagonal_(1)
|
128 |
+
|
129 |
+
sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets
|
130 |
+
sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets
|
131 |
+
|
132 |
+
sim_i2t = image_feat @ text_feat_all / self.temp
|
133 |
+
sim_t2i = text_feat @ image_feat_all / self.temp
|
134 |
+
|
135 |
+
loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean()
|
136 |
+
loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean()
|
137 |
+
|
138 |
+
loss_ita = (loss_i2t + loss_t2i)/2
|
139 |
+
idxs = concat_all_gather(idx)
|
140 |
+
self._dequeue_and_enqueue(image_feat_m, text_feat_m, idxs)
|
141 |
+
|
142 |
+
###============== Image-text Matching ===================###
|
143 |
+
encoder_input_ids = text.input_ids.clone()
|
144 |
+
encoder_input_ids[:,0] = self.tokenizer.enc_token_id
|
145 |
+
|
146 |
+
# forward the positve image-text pair
|
147 |
+
bs = image.size(0)
|
148 |
+
output_pos = self.text_encoder(encoder_input_ids,
|
149 |
+
attention_mask = text.attention_mask,
|
150 |
+
encoder_hidden_states = image_embeds,
|
151 |
+
encoder_attention_mask = image_atts,
|
152 |
+
return_dict = True,
|
153 |
+
)
|
154 |
+
# compute sample similarity
|
155 |
+
with torch.no_grad():
|
156 |
+
mask = torch.eq(idx, idxs.t())
|
157 |
+
|
158 |
+
image_feat_world = concat_all_gather(image_feat)
|
159 |
+
text_feat_world = concat_all_gather(text_feat)
|
160 |
+
|
161 |
+
sim_i2t = image_feat @ text_feat_world.t() / self.temp
|
162 |
+
sim_t2i = text_feat @ image_feat_world.t() / self.temp
|
163 |
+
|
164 |
+
weights_i2t = F.softmax(sim_i2t,dim=1)
|
165 |
+
weights_i2t.masked_fill_(mask, 0)
|
166 |
+
|
167 |
+
weights_t2i = F.softmax(sim_t2i,dim=1)
|
168 |
+
weights_t2i.masked_fill_(mask, 0)
|
169 |
+
|
170 |
+
image_embeds_world = all_gather_with_grad(image_embeds)
|
171 |
+
|
172 |
+
# select a negative image (from all ranks) for each text
|
173 |
+
image_embeds_neg = []
|
174 |
+
for b in range(bs):
|
175 |
+
neg_idx = torch.multinomial(weights_t2i[b], 1).item()
|
176 |
+
image_embeds_neg.append(image_embeds_world[neg_idx])
|
177 |
+
image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
|
178 |
+
|
179 |
+
# select a negative text (from all ranks) for each image
|
180 |
+
input_ids_world = concat_all_gather(encoder_input_ids)
|
181 |
+
att_mask_world = concat_all_gather(text.attention_mask)
|
182 |
+
|
183 |
+
text_ids_neg = []
|
184 |
+
text_atts_neg = []
|
185 |
+
for b in range(bs):
|
186 |
+
neg_idx = torch.multinomial(weights_i2t[b], 1).item()
|
187 |
+
text_ids_neg.append(input_ids_world[neg_idx])
|
188 |
+
text_atts_neg.append(att_mask_world[neg_idx])
|
189 |
+
|
190 |
+
text_ids_neg = torch.stack(text_ids_neg,dim=0)
|
191 |
+
text_atts_neg = torch.stack(text_atts_neg,dim=0)
|
192 |
+
|
193 |
+
text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0)
|
194 |
+
text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0)
|
195 |
+
|
196 |
+
image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0)
|
197 |
+
image_atts_all = torch.cat([image_atts,image_atts],dim=0)
|
198 |
+
|
199 |
+
output_neg = self.text_encoder(text_ids_all,
|
200 |
+
attention_mask = text_atts_all,
|
201 |
+
encoder_hidden_states = image_embeds_all,
|
202 |
+
encoder_attention_mask = image_atts_all,
|
203 |
+
return_dict = True,
|
204 |
+
)
|
205 |
+
|
206 |
+
vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0)
|
207 |
+
vl_output = self.itm_head(vl_embeddings)
|
208 |
+
|
209 |
+
itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)],
|
210 |
+
dim=0).to(image.device)
|
211 |
+
loss_itm = F.cross_entropy(vl_output, itm_labels)
|
212 |
+
|
213 |
+
return loss_ita, loss_itm
|
214 |
+
|
215 |
+
|
216 |
+
|
217 |
+
@torch.no_grad()
|
218 |
+
def copy_params(self):
|
219 |
+
for model_pair in self.model_pairs:
|
220 |
+
for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
|
221 |
+
param_m.data.copy_(param.data) # initialize
|
222 |
+
param_m.requires_grad = False # not update by gradient
|
223 |
+
|
224 |
+
|
225 |
+
@torch.no_grad()
|
226 |
+
def _momentum_update(self):
|
227 |
+
for model_pair in self.model_pairs:
|
228 |
+
for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
|
229 |
+
param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum)
|
230 |
+
|
231 |
+
|
232 |
+
@torch.no_grad()
|
233 |
+
def _dequeue_and_enqueue(self, image_feat, text_feat, idxs):
|
234 |
+
# gather keys before updating queue
|
235 |
+
image_feats = concat_all_gather(image_feat)
|
236 |
+
text_feats = concat_all_gather(text_feat)
|
237 |
+
|
238 |
+
batch_size = image_feats.shape[0]
|
239 |
+
|
240 |
+
ptr = int(self.ptr_queue)
|
241 |
+
assert self.queue_size % batch_size == 0 # for simplicity
|
242 |
+
|
243 |
+
# replace the keys at ptr (dequeue and enqueue)
|
244 |
+
self.image_queue[:, ptr:ptr + batch_size] = image_feats.T
|
245 |
+
self.text_queue[:, ptr:ptr + batch_size] = text_feats.T
|
246 |
+
self.idx_queue[:, ptr:ptr + batch_size] = idxs.T
|
247 |
+
ptr = (ptr + batch_size) % self.queue_size # move pointer
|
248 |
+
|
249 |
+
self.ptr_queue[0] = ptr
|
250 |
+
|
251 |
+
|
252 |
+
|
253 |
+
def fflip_pretrain(pretrained='', **kwargs):
|
254 |
+
model = FFLIP_Pretrain(**kwargs)
|
255 |
+
if pretrained:
|
256 |
+
model, msg = load_checkpoint(model, pretrained)
|
257 |
+
print("missing keys:")
|
258 |
+
print(msg.missing_keys)
|
259 |
+
return model
|
260 |
+
|
261 |
+
|
262 |
+
@torch.no_grad()
|
263 |
+
def concat_all_gather(tensor):
|
264 |
+
"""
|
265 |
+
Performs all_gather operation on the provided tensors.
|
266 |
+
*** Warning ***: torch.distributed.all_gather has no gradient.
|
267 |
+
"""
|
268 |
+
if torch.distributed.is_initialized():
|
269 |
+
tensors_gather = [torch.ones_like(tensor)
|
270 |
+
for _ in range(torch.distributed.get_world_size())]
|
271 |
+
torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
|
272 |
+
|
273 |
+
output = torch.cat(tensors_gather, dim=0)
|
274 |
+
else:
|
275 |
+
output = tensor.clone()
|
276 |
+
|
277 |
+
return output
|
278 |
+
|
279 |
+
|
280 |
+
class GatherLayer(torch.autograd.Function):
|
281 |
+
"""
|
282 |
+
Gather tensors from all workers with support for backward propagation:
|
283 |
+
This implementation does not cut the gradients as torch.distributed.all_gather does.
|
284 |
+
"""
|
285 |
+
|
286 |
+
@staticmethod
|
287 |
+
def forward(ctx, x):
|
288 |
+
output = [torch.zeros_like(x) for _ in range(torch.distributed.get_world_size())]
|
289 |
+
torch.distributed.all_gather(output, x)
|
290 |
+
return tuple(output)
|
291 |
+
|
292 |
+
@staticmethod
|
293 |
+
def backward(ctx, *grads):
|
294 |
+
all_gradients = torch.stack(grads)
|
295 |
+
torch.distributed.all_reduce(all_gradients)
|
296 |
+
return all_gradients[torch.distributed.get_rank()]
|
297 |
+
|
298 |
+
|
299 |
+
def all_gather_with_grad(tensors):
|
300 |
+
"""
|
301 |
+
Performs all_gather operation on the provided tensors.
|
302 |
+
Graph remains connected for backward grad computation.
|
303 |
+
"""
|
304 |
+
# Queue the gathered tensors
|
305 |
+
world_size = 1
|
306 |
+
if torch.distributed.is_initialized():
|
307 |
+
world_size = torch.distributed.get_world_size()
|
308 |
+
# There is no need for reduction in the single-proc case
|
309 |
+
if world_size == 1:
|
310 |
+
return tensors
|
311 |
+
|
312 |
+
tensor_all = GatherLayer.apply(tensors)
|
313 |
+
|
314 |
+
return torch.cat(tensor_all, dim=0)
|
models/mm.py
ADDED
@@ -0,0 +1,1652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
@file mm.py
|
3 |
+
@brief This file contains the code for the multimodal model. It is a modified version of the CLIP model from the huggingface transformers library.
|
4 |
+
@author yutangli
|
5 |
+
"""
|
6 |
+
import torch
|
7 |
+
from torch.nn import CrossEntropyLoss
|
8 |
+
from transformers.configuration_utils import PretrainedConfig
|
9 |
+
from transformers.models.clip.configuration_clip import CLIPConfig
|
10 |
+
from transformers.modeling_utils import PreTrainedModel
|
11 |
+
from transformers.activations import ACT2FN
|
12 |
+
from transformers.utils import logging, ModelOutput
|
13 |
+
from typing import Optional, Union, Tuple, Dict
|
14 |
+
import math
|
15 |
+
from dataclasses import dataclass
|
16 |
+
|
17 |
+
from torch import Tensor, device, dtype, nn
|
18 |
+
|
19 |
+
from transformers.modeling_utils import (
|
20 |
+
PreTrainedModel,
|
21 |
+
apply_chunking_to_forward,
|
22 |
+
find_pruneable_heads_and_indices,
|
23 |
+
prune_linear_layer,
|
24 |
+
)
|
25 |
+
|
26 |
+
from transformers.modeling_outputs import (
|
27 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
28 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
29 |
+
CausalLMOutputWithCrossAttentions,
|
30 |
+
MaskedLMOutput,
|
31 |
+
MultipleChoiceModelOutput,
|
32 |
+
NextSentencePredictorOutput,
|
33 |
+
QuestionAnsweringModelOutput,
|
34 |
+
SequenceClassifierOutput,
|
35 |
+
TokenClassifierOutput,
|
36 |
+
)
|
37 |
+
|
38 |
+
from transformers.models.bert.configuration_bert import BertConfig
|
39 |
+
|
40 |
+
logger = logging.get_logger(__name__)
|
41 |
+
|
42 |
+
|
43 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
44 |
+
def _make_causal_mask(
|
45 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
46 |
+
):
|
47 |
+
"""
|
48 |
+
Make causal mask used for bi-directional self-attention.
|
49 |
+
"""
|
50 |
+
bsz, tgt_len = input_ids_shape
|
51 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
52 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
53 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
54 |
+
mask = mask.to(dtype)
|
55 |
+
|
56 |
+
if past_key_values_length > 0:
|
57 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
58 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
59 |
+
|
60 |
+
|
61 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
62 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
63 |
+
"""
|
64 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
65 |
+
"""
|
66 |
+
bsz, src_len = mask.size()
|
67 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
68 |
+
|
69 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
70 |
+
|
71 |
+
inverted_mask = 1.0 - expanded_mask
|
72 |
+
|
73 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
74 |
+
|
75 |
+
|
76 |
+
@dataclass
|
77 |
+
class BaseModelOutput(ModelOutput):
|
78 |
+
"""
|
79 |
+
Base class for model's outputs, with potential hidden states and attentions.
|
80 |
+
|
81 |
+
Args:
|
82 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
83 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
84 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
85 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
86 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
87 |
+
|
88 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
89 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
90 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
91 |
+
sequence_length)`.
|
92 |
+
|
93 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
94 |
+
heads.
|
95 |
+
"""
|
96 |
+
|
97 |
+
last_hidden_state: torch.FloatTensor = None
|
98 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
99 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
100 |
+
intermediate_hidden_state: Optional[Dict[str, torch.FloatTensor]] = None
|
101 |
+
|
102 |
+
@dataclass
|
103 |
+
class BaseModelOutputWithPooling(ModelOutput):
|
104 |
+
"""
|
105 |
+
Base class for model's outputs that also contains a pooling of the last hidden states.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
109 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
110 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
|
111 |
+
Last layer hidden-state of the first token of the sequence (classification token) after further processing
|
112 |
+
through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
|
113 |
+
the classification token after processing through a linear layer and a tanh activation function. The linear
|
114 |
+
layer weights are trained from the next sentence prediction (classification) objective during pretraining.
|
115 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
116 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
117 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
118 |
+
|
119 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
120 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
121 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
122 |
+
sequence_length)`.
|
123 |
+
|
124 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
125 |
+
heads.
|
126 |
+
"""
|
127 |
+
|
128 |
+
last_hidden_state: torch.FloatTensor = None
|
129 |
+
pooler_output: torch.FloatTensor = None
|
130 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
131 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
132 |
+
intermediate_hidden_state: Optional[Dict[str, torch.FloatTensor]] = None
|
133 |
+
|
134 |
+
|
135 |
+
class BertConfig(PretrainedConfig):
|
136 |
+
r"""
|
137 |
+
This is the configuration class to store the configuration of a [`BertModel`] or a [`TFBertModel`]. It is used to
|
138 |
+
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
|
139 |
+
configuration with the defaults will yield a similar configuration to that of the BERT
|
140 |
+
[bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
|
141 |
+
|
142 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
143 |
+
documentation from [`PretrainedConfig`] for more information.
|
144 |
+
|
145 |
+
|
146 |
+
Args:
|
147 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
148 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
149 |
+
`inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
150 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
151 |
+
Dimensionality of the encoder layers and the pooler layer.
|
152 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
153 |
+
Number of hidden layers in the Transformer encoder.
|
154 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
155 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
156 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
157 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
158 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
159 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
160 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
161 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
162 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
163 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
164 |
+
The dropout ratio for the attention probabilities.
|
165 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
166 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
167 |
+
just in case (e.g., 512 or 1024 or 2048).
|
168 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
169 |
+
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
170 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
171 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
172 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
173 |
+
The epsilon used by the layer normalization layers.
|
174 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
175 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
176 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
177 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
178 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
179 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
180 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
181 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
182 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
183 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
184 |
+
relevant if `config.is_decoder=True`.
|
185 |
+
classifier_dropout (`float`, *optional*):
|
186 |
+
The dropout ratio for the classification head.
|
187 |
+
|
188 |
+
Examples:
|
189 |
+
|
190 |
+
```python
|
191 |
+
>>> from transformers import BertConfig, BertModel
|
192 |
+
|
193 |
+
>>> # Initializing a BERT bert-base-uncased style configuration
|
194 |
+
>>> configuration = BertConfig()
|
195 |
+
|
196 |
+
>>> # Initializing a model (with random weights) from the bert-base-uncased style configuration
|
197 |
+
>>> model = BertModel(configuration)
|
198 |
+
|
199 |
+
>>> # Accessing the model configuration
|
200 |
+
>>> configuration = model.config
|
201 |
+
```"""
|
202 |
+
model_type = "bert"
|
203 |
+
|
204 |
+
def __init__(
|
205 |
+
self,
|
206 |
+
vocab_size=30522,
|
207 |
+
hidden_size=768,
|
208 |
+
num_hidden_layers=12,
|
209 |
+
num_attention_heads=12,
|
210 |
+
intermediate_size=3072,
|
211 |
+
hidden_act="gelu",
|
212 |
+
hidden_dropout_prob=0.1,
|
213 |
+
attention_probs_dropout_prob=0.1,
|
214 |
+
max_position_embeddings=512,
|
215 |
+
type_vocab_size=2,
|
216 |
+
initializer_range=0.02,
|
217 |
+
layer_norm_eps=1e-12,
|
218 |
+
pad_token_id=0,
|
219 |
+
position_embedding_type="absolute",
|
220 |
+
use_cache=True,
|
221 |
+
classifier_dropout=None,
|
222 |
+
**kwargs,
|
223 |
+
):
|
224 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
225 |
+
|
226 |
+
self.vocab_size = vocab_size
|
227 |
+
self.hidden_size = hidden_size
|
228 |
+
self.num_hidden_layers = num_hidden_layers
|
229 |
+
self.num_attention_heads = num_attention_heads
|
230 |
+
self.hidden_act = hidden_act
|
231 |
+
self.intermediate_size = intermediate_size
|
232 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
233 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
234 |
+
self.max_position_embeddings = max_position_embeddings
|
235 |
+
self.type_vocab_size = type_vocab_size
|
236 |
+
self.initializer_range = initializer_range
|
237 |
+
self.layer_norm_eps = layer_norm_eps
|
238 |
+
self.position_embedding_type = position_embedding_type
|
239 |
+
self.use_cache = use_cache
|
240 |
+
self.classifier_dropout = classifier_dropout
|
241 |
+
|
242 |
+
|
243 |
+
class VisionConfig(PretrainedConfig):
|
244 |
+
r"""
|
245 |
+
This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
|
246 |
+
CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
247 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
|
248 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
249 |
+
|
250 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
251 |
+
documentation from [`PretrainedConfig`] for more information.
|
252 |
+
|
253 |
+
Args:
|
254 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
255 |
+
Dimensionality of the encoder layers and the pooler layer.
|
256 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
257 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
258 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
259 |
+
Number of hidden layers in the Transformer encoder.
|
260 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
261 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
262 |
+
image_size (`int`, *optional*, defaults to 224):
|
263 |
+
The size (resolution) of each image.
|
264 |
+
patch_size (`int`, *optional*, defaults to 32):
|
265 |
+
The size (resolution) of each patch.
|
266 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
267 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
268 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
269 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
270 |
+
The epsilon used by the layer normalization layers.
|
271 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
272 |
+
The dropout ratio for the attention probabilities.
|
273 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
274 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
275 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
276 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
277 |
+
testing).
|
278 |
+
|
279 |
+
Example:
|
280 |
+
|
281 |
+
```python
|
282 |
+
>>> from transformers import CLIPVisionConfig, CLIPVisionModel
|
283 |
+
|
284 |
+
>>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
|
285 |
+
>>> configuration = CLIPVisionConfig()
|
286 |
+
|
287 |
+
>>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
288 |
+
>>> model = CLIPVisionModel(configuration)
|
289 |
+
|
290 |
+
>>> # Accessing the model configuration
|
291 |
+
>>> configuration = model.config
|
292 |
+
```"""
|
293 |
+
|
294 |
+
model_type = "clip_vision_model"
|
295 |
+
|
296 |
+
def __init__(
|
297 |
+
self,
|
298 |
+
hidden_size=768,
|
299 |
+
intermediate_size=3072,
|
300 |
+
projection_dim=512,
|
301 |
+
num_hidden_layers=12,
|
302 |
+
num_attention_heads=12,
|
303 |
+
num_channels=3,
|
304 |
+
image_size=224,
|
305 |
+
patch_size=32,
|
306 |
+
hidden_act="quick_gelu",
|
307 |
+
layer_norm_eps=1e-5,
|
308 |
+
attention_dropout=0.0,
|
309 |
+
initializer_range=0.02,
|
310 |
+
initializer_factor=1.0,
|
311 |
+
intermediate_transformer_output = [4, 6, 8],
|
312 |
+
**kwargs,
|
313 |
+
):
|
314 |
+
super().__init__(**kwargs)
|
315 |
+
|
316 |
+
self.hidden_size = hidden_size
|
317 |
+
self.intermediate_size = intermediate_size
|
318 |
+
self.projection_dim = projection_dim
|
319 |
+
self.intermediate_transformer_output = intermediate_transformer_output
|
320 |
+
self.num_hidden_layers = num_hidden_layers
|
321 |
+
self.num_attention_heads = num_attention_heads
|
322 |
+
self.num_channels = num_channels
|
323 |
+
self.patch_size = patch_size
|
324 |
+
self.image_size = image_size
|
325 |
+
self.initializer_range = initializer_range
|
326 |
+
self.initializer_factor = initializer_factor
|
327 |
+
self.attention_dropout = attention_dropout
|
328 |
+
self.layer_norm_eps = layer_norm_eps
|
329 |
+
self.hidden_act = hidden_act
|
330 |
+
|
331 |
+
|
332 |
+
class BertEmbeddings(nn.Module):
|
333 |
+
"""Construct the embeddings from word and position embeddings."""
|
334 |
+
|
335 |
+
def __init__(self, config):
|
336 |
+
super().__init__()
|
337 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
338 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
339 |
+
|
340 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
341 |
+
# any TensorFlow checkpoint file
|
342 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
343 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
344 |
+
|
345 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
346 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
347 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
348 |
+
|
349 |
+
self.config = config
|
350 |
+
|
351 |
+
def forward(
|
352 |
+
self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
353 |
+
):
|
354 |
+
if input_ids is not None:
|
355 |
+
input_shape = input_ids.size()
|
356 |
+
else:
|
357 |
+
input_shape = inputs_embeds.size()[:-1]
|
358 |
+
|
359 |
+
seq_length = input_shape[1]
|
360 |
+
|
361 |
+
if position_ids is None:
|
362 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
363 |
+
|
364 |
+
if inputs_embeds is None:
|
365 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
366 |
+
|
367 |
+
embeddings = inputs_embeds
|
368 |
+
|
369 |
+
if self.position_embedding_type == "absolute":
|
370 |
+
position_embeddings = self.position_embeddings(position_ids)
|
371 |
+
embeddings += position_embeddings
|
372 |
+
embeddings = self.LayerNorm(embeddings)
|
373 |
+
embeddings = self.dropout(embeddings)
|
374 |
+
return embeddings
|
375 |
+
|
376 |
+
|
377 |
+
class VisionEmbeddings(nn.Module):
|
378 |
+
def __init__(self, config: VisionConfig):
|
379 |
+
super().__init__()
|
380 |
+
self.config = config
|
381 |
+
self.embed_dim = config.hidden_size
|
382 |
+
self.image_size = config.image_size
|
383 |
+
self.patch_size = config.patch_size
|
384 |
+
|
385 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
386 |
+
|
387 |
+
self.patch_embedding = nn.Conv2d(
|
388 |
+
in_channels=config.num_channels,
|
389 |
+
out_channels=self.embed_dim,
|
390 |
+
kernel_size=self.patch_size,
|
391 |
+
stride=self.patch_size,
|
392 |
+
bias=False,
|
393 |
+
)
|
394 |
+
|
395 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
396 |
+
self.num_positions = self.num_patches + 1
|
397 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
398 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
|
399 |
+
|
400 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
401 |
+
batch_size = pixel_values.shape[0]
|
402 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
403 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
404 |
+
|
405 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
406 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
407 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
408 |
+
return embeddings
|
409 |
+
|
410 |
+
|
411 |
+
class BertSelfAttention(nn.Module):
|
412 |
+
def __init__(self, config, is_cross_attention):
|
413 |
+
super().__init__()
|
414 |
+
self.config = config
|
415 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
416 |
+
raise ValueError(
|
417 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
418 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads)
|
419 |
+
)
|
420 |
+
|
421 |
+
self.num_attention_heads = config.num_attention_heads
|
422 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
423 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
424 |
+
|
425 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
426 |
+
if is_cross_attention:
|
427 |
+
self.key = nn.Linear(config.encoder_width, self.all_head_size)
|
428 |
+
self.value = nn.Linear(config.encoder_width, self.all_head_size)
|
429 |
+
else:
|
430 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
431 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
432 |
+
|
433 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
434 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
435 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
436 |
+
self.max_position_embeddings = config.max_position_embeddings
|
437 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
438 |
+
self.save_attention = False
|
439 |
+
|
440 |
+
def save_attn_gradients(self, attn_gradients):
|
441 |
+
self.attn_gradients = attn_gradients
|
442 |
+
|
443 |
+
def get_attn_gradients(self):
|
444 |
+
return self.attn_gradients
|
445 |
+
|
446 |
+
def save_attention_map(self, attention_map):
|
447 |
+
self.attention_map = attention_map
|
448 |
+
|
449 |
+
def get_attention_map(self):
|
450 |
+
return self.attention_map
|
451 |
+
|
452 |
+
def transpose_for_scores(self, x):
|
453 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
454 |
+
x = x.view(*new_x_shape)
|
455 |
+
return x.permute(0, 2, 1, 3)
|
456 |
+
|
457 |
+
def forward(
|
458 |
+
self,
|
459 |
+
hidden_states,
|
460 |
+
attention_mask=None,
|
461 |
+
head_mask=None,
|
462 |
+
encoder_hidden_states=None,
|
463 |
+
encoder_attention_mask=None,
|
464 |
+
past_key_value=None,
|
465 |
+
output_attentions=False,
|
466 |
+
):
|
467 |
+
mixed_query_layer = self.query(hidden_states)
|
468 |
+
|
469 |
+
# If this is instantiated as a cross-attention module, the keys
|
470 |
+
# and values come from an encoder; the attention mask needs to be
|
471 |
+
# such that the encoder's padding tokens are not attended to.
|
472 |
+
is_cross_attention = encoder_hidden_states is not None
|
473 |
+
|
474 |
+
if is_cross_attention:
|
475 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
476 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
477 |
+
attention_mask = encoder_attention_mask
|
478 |
+
elif past_key_value is not None:
|
479 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
480 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
481 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
482 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
483 |
+
else:
|
484 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
485 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
486 |
+
|
487 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
488 |
+
|
489 |
+
past_key_value = (key_layer, value_layer)
|
490 |
+
|
491 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
492 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
493 |
+
|
494 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
495 |
+
seq_length = hidden_states.size()[1]
|
496 |
+
position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
497 |
+
position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
498 |
+
distance = position_ids_l - position_ids_r
|
499 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
500 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
501 |
+
|
502 |
+
if self.position_embedding_type == "relative_key":
|
503 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
504 |
+
attention_scores = attention_scores + relative_position_scores
|
505 |
+
elif self.position_embedding_type == "relative_key_query":
|
506 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
507 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
508 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
509 |
+
|
510 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
511 |
+
if attention_mask is not None:
|
512 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
513 |
+
attention_scores = attention_scores + attention_mask
|
514 |
+
|
515 |
+
# Normalize the attention scores to probabilities.
|
516 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
517 |
+
|
518 |
+
if is_cross_attention and self.save_attention:
|
519 |
+
self.save_attention_map(attention_probs)
|
520 |
+
attention_probs.register_hook(self.save_attn_gradients)
|
521 |
+
|
522 |
+
# This is actually dropping out entire tokens to attend to, which might
|
523 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
524 |
+
attention_probs_dropped = self.dropout(attention_probs)
|
525 |
+
|
526 |
+
# Mask heads if we want to
|
527 |
+
if head_mask is not None:
|
528 |
+
attention_probs_dropped = attention_probs_dropped * head_mask
|
529 |
+
|
530 |
+
context_layer = torch.matmul(attention_probs_dropped, value_layer)
|
531 |
+
|
532 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
533 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
534 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
535 |
+
|
536 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
537 |
+
|
538 |
+
outputs = outputs + (past_key_value,)
|
539 |
+
return outputs
|
540 |
+
|
541 |
+
|
542 |
+
class BertSelfOutput(nn.Module):
|
543 |
+
def __init__(self, config):
|
544 |
+
super().__init__()
|
545 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
546 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
547 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
548 |
+
|
549 |
+
def forward(self, hidden_states, input_tensor):
|
550 |
+
hidden_states = self.dense(hidden_states)
|
551 |
+
hidden_states = self.dropout(hidden_states)
|
552 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
553 |
+
return hidden_states
|
554 |
+
|
555 |
+
|
556 |
+
class BertAttention(nn.Module):
|
557 |
+
def __init__(self, config, is_cross_attention=False):
|
558 |
+
super().__init__()
|
559 |
+
self.self = BertSelfAttention(config, is_cross_attention)
|
560 |
+
self.output = BertSelfOutput(config)
|
561 |
+
self.pruned_heads = set()
|
562 |
+
|
563 |
+
def prune_heads(self, heads):
|
564 |
+
if len(heads) == 0:
|
565 |
+
return
|
566 |
+
heads, index = find_pruneable_heads_and_indices(
|
567 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
568 |
+
)
|
569 |
+
|
570 |
+
# Prune linear layers
|
571 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
572 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
573 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
574 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
575 |
+
|
576 |
+
# Update hyper params and store pruned heads
|
577 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
578 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
579 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
580 |
+
|
581 |
+
def forward(
|
582 |
+
self,
|
583 |
+
hidden_states,
|
584 |
+
attention_mask=None,
|
585 |
+
head_mask=None,
|
586 |
+
encoder_hidden_states=None,
|
587 |
+
encoder_attention_mask=None,
|
588 |
+
past_key_value=None,
|
589 |
+
output_attentions=False,
|
590 |
+
):
|
591 |
+
self_outputs = self.self(
|
592 |
+
hidden_states,
|
593 |
+
attention_mask,
|
594 |
+
head_mask,
|
595 |
+
encoder_hidden_states,
|
596 |
+
encoder_attention_mask,
|
597 |
+
past_key_value,
|
598 |
+
output_attentions,
|
599 |
+
)
|
600 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
601 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
602 |
+
return outputs
|
603 |
+
|
604 |
+
|
605 |
+
class BertIntermediate(nn.Module):
|
606 |
+
def __init__(self, config):
|
607 |
+
super().__init__()
|
608 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
609 |
+
if isinstance(config.hidden_act, str):
|
610 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
611 |
+
else:
|
612 |
+
self.intermediate_act_fn = config.hidden_act
|
613 |
+
|
614 |
+
def forward(self, hidden_states):
|
615 |
+
hidden_states = self.dense(hidden_states)
|
616 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
617 |
+
return hidden_states
|
618 |
+
|
619 |
+
|
620 |
+
class BertOutput(nn.Module):
|
621 |
+
def __init__(self, config):
|
622 |
+
super().__init__()
|
623 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
624 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
625 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
626 |
+
|
627 |
+
def forward(self, hidden_states, input_tensor):
|
628 |
+
hidden_states = self.dense(hidden_states)
|
629 |
+
hidden_states = self.dropout(hidden_states)
|
630 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
631 |
+
return hidden_states
|
632 |
+
|
633 |
+
|
634 |
+
class Attention(nn.Module):
|
635 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
636 |
+
|
637 |
+
def __init__(self, config):
|
638 |
+
super().__init__()
|
639 |
+
self.config = config
|
640 |
+
self.embed_dim = config.hidden_size
|
641 |
+
self.num_heads = config.num_attention_heads
|
642 |
+
self.head_dim = self.embed_dim // self.num_heads
|
643 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
644 |
+
raise ValueError(
|
645 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
646 |
+
f" {self.num_heads})."
|
647 |
+
)
|
648 |
+
self.scale = self.head_dim**-0.5
|
649 |
+
self.dropout = config.attention_dropout
|
650 |
+
|
651 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
652 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
653 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
654 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
655 |
+
|
656 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
657 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
658 |
+
|
659 |
+
def forward(
|
660 |
+
self,
|
661 |
+
hidden_states: torch.Tensor,
|
662 |
+
attention_mask: Optional[torch.Tensor] = None,
|
663 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
664 |
+
output_attentions: Optional[bool] = False,
|
665 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
666 |
+
"""Input shape: Batch x Time x Channel"""
|
667 |
+
|
668 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
669 |
+
|
670 |
+
# get query proj
|
671 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
672 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
673 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
674 |
+
|
675 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
676 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
677 |
+
key_states = key_states.view(*proj_shape)
|
678 |
+
value_states = value_states.view(*proj_shape)
|
679 |
+
|
680 |
+
src_len = key_states.size(1)
|
681 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
682 |
+
|
683 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
684 |
+
raise ValueError(
|
685 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
686 |
+
f" {attn_weights.size()}"
|
687 |
+
)
|
688 |
+
|
689 |
+
# apply the causal_attention_mask first
|
690 |
+
if causal_attention_mask is not None:
|
691 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
692 |
+
raise ValueError(
|
693 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
694 |
+
f" {causal_attention_mask.size()}"
|
695 |
+
)
|
696 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
697 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
698 |
+
|
699 |
+
if attention_mask is not None:
|
700 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
701 |
+
raise ValueError(
|
702 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
703 |
+
)
|
704 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
705 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
706 |
+
|
707 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
708 |
+
|
709 |
+
if output_attentions:
|
710 |
+
# this operation is a bit akward, but it's required to
|
711 |
+
# make sure that attn_weights keeps its gradient.
|
712 |
+
# In order to do so, attn_weights have to reshaped
|
713 |
+
# twice and have to be reused in the following
|
714 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
715 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
716 |
+
else:
|
717 |
+
attn_weights_reshaped = None
|
718 |
+
|
719 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
720 |
+
|
721 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
722 |
+
|
723 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
724 |
+
raise ValueError(
|
725 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
726 |
+
f" {attn_output.size()}"
|
727 |
+
)
|
728 |
+
|
729 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
730 |
+
attn_output = attn_output.transpose(1, 2)
|
731 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
732 |
+
|
733 |
+
attn_output = self.out_proj(attn_output)
|
734 |
+
|
735 |
+
return attn_output, attn_weights_reshaped
|
736 |
+
|
737 |
+
|
738 |
+
class MLP(nn.Module):
|
739 |
+
def __init__(self, config):
|
740 |
+
super().__init__()
|
741 |
+
self.config = config
|
742 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
743 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
744 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
745 |
+
|
746 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
747 |
+
hidden_states = self.fc1(hidden_states)
|
748 |
+
hidden_states = self.activation_fn(hidden_states)
|
749 |
+
hidden_states = self.fc2(hidden_states)
|
750 |
+
return hidden_states
|
751 |
+
|
752 |
+
|
753 |
+
class EncoderLayer(nn.Module):
|
754 |
+
def __init__(self, config: CLIPConfig):
|
755 |
+
super().__init__()
|
756 |
+
self.embed_dim = config.hidden_size
|
757 |
+
self.self_attn = Attention(config)
|
758 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
759 |
+
self.mlp = MLP(config)
|
760 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
761 |
+
|
762 |
+
def forward(
|
763 |
+
self,
|
764 |
+
hidden_states: torch.Tensor,
|
765 |
+
attention_mask: torch.Tensor,
|
766 |
+
causal_attention_mask: torch.Tensor,
|
767 |
+
output_attentions: Optional[bool] = False,
|
768 |
+
) -> Tuple[torch.FloatTensor]:
|
769 |
+
"""
|
770 |
+
Args:
|
771 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
772 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
773 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
774 |
+
`(config.encoder_attention_heads,)`.
|
775 |
+
output_attentions (`bool`, *optional*):
|
776 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
777 |
+
returned tensors for more detail.
|
778 |
+
"""
|
779 |
+
residual = hidden_states
|
780 |
+
|
781 |
+
hidden_states = self.layer_norm1(hidden_states)
|
782 |
+
hidden_states, attn_weights = self.self_attn(
|
783 |
+
hidden_states=hidden_states,
|
784 |
+
attention_mask=attention_mask,
|
785 |
+
causal_attention_mask=causal_attention_mask,
|
786 |
+
output_attentions=output_attentions,
|
787 |
+
)
|
788 |
+
hidden_states = residual + hidden_states
|
789 |
+
|
790 |
+
residual = hidden_states
|
791 |
+
hidden_states = self.layer_norm2(hidden_states)
|
792 |
+
hidden_states = self.mlp(hidden_states)
|
793 |
+
hidden_states = residual + hidden_states
|
794 |
+
|
795 |
+
outputs = (hidden_states,)
|
796 |
+
|
797 |
+
if output_attentions:
|
798 |
+
outputs += (attn_weights,)
|
799 |
+
|
800 |
+
return outputs
|
801 |
+
|
802 |
+
|
803 |
+
class BertLayer(nn.Module):
|
804 |
+
def __init__(self, config, layer_num):
|
805 |
+
super().__init__()
|
806 |
+
self.config = config
|
807 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
808 |
+
self.seq_len_dim = 1
|
809 |
+
self.attention = BertAttention(config)
|
810 |
+
self.layer_num = layer_num
|
811 |
+
if self.config.add_cross_attention:
|
812 |
+
self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention)
|
813 |
+
self.intermediate = BertIntermediate(config)
|
814 |
+
self.output = BertOutput(config)
|
815 |
+
|
816 |
+
def forward(
|
817 |
+
self,
|
818 |
+
hidden_states,
|
819 |
+
attention_mask=None,
|
820 |
+
head_mask=None,
|
821 |
+
encoder_hidden_states=None,
|
822 |
+
encoder_attention_mask=None,
|
823 |
+
past_key_value=None,
|
824 |
+
output_attentions=False,
|
825 |
+
mode=None,
|
826 |
+
):
|
827 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
828 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
829 |
+
self_attention_outputs = self.attention(
|
830 |
+
hidden_states,
|
831 |
+
attention_mask,
|
832 |
+
head_mask,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
past_key_value=self_attn_past_key_value,
|
835 |
+
)
|
836 |
+
attention_output = self_attention_outputs[0]
|
837 |
+
|
838 |
+
outputs = self_attention_outputs[1:-1]
|
839 |
+
present_key_value = self_attention_outputs[-1]
|
840 |
+
|
841 |
+
if mode=='multimodal':
|
842 |
+
assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
|
843 |
+
|
844 |
+
cross_attention_outputs = self.crossattention(
|
845 |
+
attention_output,
|
846 |
+
attention_mask,
|
847 |
+
head_mask,
|
848 |
+
encoder_hidden_states,
|
849 |
+
encoder_attention_mask,
|
850 |
+
output_attentions=output_attentions,
|
851 |
+
)
|
852 |
+
attention_output = cross_attention_outputs[0]
|
853 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
854 |
+
layer_output = apply_chunking_to_forward(
|
855 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
856 |
+
)
|
857 |
+
outputs = (layer_output,) + outputs
|
858 |
+
|
859 |
+
outputs = outputs + (present_key_value,)
|
860 |
+
|
861 |
+
return outputs
|
862 |
+
|
863 |
+
def feed_forward_chunk(self, attention_output):
|
864 |
+
intermediate_output = self.intermediate(attention_output)
|
865 |
+
layer_output = self.output(intermediate_output, attention_output)
|
866 |
+
return layer_output
|
867 |
+
|
868 |
+
|
869 |
+
class VisionEncoder(nn.Module):
|
870 |
+
"""
|
871 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
872 |
+
[`CLIPEncoderLayer`].
|
873 |
+
|
874 |
+
Args:
|
875 |
+
config: CLIPConfig
|
876 |
+
"""
|
877 |
+
|
878 |
+
def __init__(self, config: VisionConfig):
|
879 |
+
super().__init__()
|
880 |
+
self.config = config
|
881 |
+
self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
882 |
+
self.gradient_checkpointing = False
|
883 |
+
|
884 |
+
def forward(
|
885 |
+
self,
|
886 |
+
inputs_embeds,
|
887 |
+
attention_mask: Optional[torch.Tensor] = None,
|
888 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
889 |
+
output_attentions: Optional[bool] = None,
|
890 |
+
output_hidden_states: Optional[bool] = None,
|
891 |
+
return_dict: Optional[bool] = None,
|
892 |
+
intermediate_hidden_state: Optional[bool] = None
|
893 |
+
) -> Union[Tuple, BaseModelOutput]:
|
894 |
+
r"""
|
895 |
+
Args:
|
896 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
897 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
898 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
899 |
+
than the model's internal embedding lookup matrix.
|
900 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
901 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
902 |
+
|
903 |
+
- 1 for tokens that are **not masked**,
|
904 |
+
- 0 for tokens that are **masked**.
|
905 |
+
|
906 |
+
[What are attention masks?](../glossary#attention-mask)
|
907 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
908 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
909 |
+
|
910 |
+
- 1 for tokens that are **not masked**,
|
911 |
+
- 0 for tokens that are **masked**.
|
912 |
+
|
913 |
+
[What are attention masks?](../glossary#attention-mask)
|
914 |
+
output_attentions (`bool`, *optional*):
|
915 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
916 |
+
returned tensors for more detail.
|
917 |
+
output_hidden_states (`bool`, *optional*):
|
918 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
919 |
+
for more detail.
|
920 |
+
return_dict (`bool`, *optional*):
|
921 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
922 |
+
"""
|
923 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
924 |
+
output_hidden_states = (
|
925 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
926 |
+
)
|
927 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
928 |
+
|
929 |
+
encoder_states = () if output_hidden_states else None
|
930 |
+
all_attentions = () if output_attentions else None
|
931 |
+
intermediate_hidden_state = {} if intermediate_hidden_state else None
|
932 |
+
|
933 |
+
hidden_states = inputs_embeds
|
934 |
+
for idx, encoder_layer in enumerate(self.layers):
|
935 |
+
if output_hidden_states:
|
936 |
+
encoder_states = encoder_states + (hidden_states,)
|
937 |
+
if self.gradient_checkpointing and self.training:
|
938 |
+
|
939 |
+
def create_custom_forward(module):
|
940 |
+
def custom_forward(*inputs):
|
941 |
+
return module(*inputs, output_attentions)
|
942 |
+
|
943 |
+
return custom_forward
|
944 |
+
|
945 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
946 |
+
create_custom_forward(encoder_layer),
|
947 |
+
hidden_states,
|
948 |
+
attention_mask,
|
949 |
+
causal_attention_mask,
|
950 |
+
)
|
951 |
+
else:
|
952 |
+
layer_outputs = encoder_layer(
|
953 |
+
hidden_states,
|
954 |
+
attention_mask,
|
955 |
+
causal_attention_mask,
|
956 |
+
output_attentions=output_attentions,
|
957 |
+
)
|
958 |
+
|
959 |
+
hidden_states = layer_outputs[0]
|
960 |
+
|
961 |
+
if intermediate_hidden_state is not None and (idx+1) in self.config.intermediate_transformer_output:
|
962 |
+
key = 'layer_'+str(idx)
|
963 |
+
intermediate_hidden_state[key] = layer_outputs[0]
|
964 |
+
|
965 |
+
if output_attentions:
|
966 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
967 |
+
|
968 |
+
if output_hidden_states:
|
969 |
+
encoder_states = encoder_states + (hidden_states,)
|
970 |
+
|
971 |
+
if not return_dict:
|
972 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
973 |
+
return BaseModelOutput(
|
974 |
+
last_hidden_state=hidden_states, intermediate_hidden_state=intermediate_hidden_state, hidden_states=encoder_states, attentions=all_attentions
|
975 |
+
)
|
976 |
+
|
977 |
+
|
978 |
+
class BertEncoder(nn.Module):
|
979 |
+
def __init__(self, config):
|
980 |
+
super().__init__()
|
981 |
+
self.config = config
|
982 |
+
self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
|
983 |
+
self.gradient_checkpointing = False
|
984 |
+
|
985 |
+
def forward(
|
986 |
+
self,
|
987 |
+
hidden_states,
|
988 |
+
attention_mask=None,
|
989 |
+
head_mask=None,
|
990 |
+
encoder_hidden_states=None,
|
991 |
+
encoder_attention_mask=None,
|
992 |
+
past_key_values=None,
|
993 |
+
use_cache=None,
|
994 |
+
output_attentions=False,
|
995 |
+
output_hidden_states=False,
|
996 |
+
return_dict=True,
|
997 |
+
mode='multimodal',
|
998 |
+
):
|
999 |
+
all_hidden_states = () if output_hidden_states else None
|
1000 |
+
all_self_attentions = () if output_attentions else None
|
1001 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
1002 |
+
|
1003 |
+
next_decoder_cache = () if use_cache else None
|
1004 |
+
|
1005 |
+
for i in range(self.config.num_hidden_layers):
|
1006 |
+
layer_module = self.layer[i]
|
1007 |
+
if output_hidden_states:
|
1008 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1009 |
+
|
1010 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
1011 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
1012 |
+
|
1013 |
+
if self.gradient_checkpointing and self.training:
|
1014 |
+
|
1015 |
+
if use_cache:
|
1016 |
+
logger.warn(
|
1017 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1018 |
+
)
|
1019 |
+
use_cache = False
|
1020 |
+
|
1021 |
+
def create_custom_forward(module):
|
1022 |
+
def custom_forward(*inputs):
|
1023 |
+
return module(*inputs, past_key_value, output_attentions)
|
1024 |
+
|
1025 |
+
return custom_forward
|
1026 |
+
|
1027 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
1028 |
+
create_custom_forward(layer_module),
|
1029 |
+
hidden_states,
|
1030 |
+
attention_mask,
|
1031 |
+
layer_head_mask,
|
1032 |
+
encoder_hidden_states,
|
1033 |
+
encoder_attention_mask,
|
1034 |
+
mode=mode,
|
1035 |
+
)
|
1036 |
+
else:
|
1037 |
+
layer_outputs = layer_module(
|
1038 |
+
hidden_states,
|
1039 |
+
attention_mask,
|
1040 |
+
layer_head_mask,
|
1041 |
+
encoder_hidden_states,
|
1042 |
+
encoder_attention_mask,
|
1043 |
+
past_key_value,
|
1044 |
+
output_attentions,
|
1045 |
+
mode=mode,
|
1046 |
+
)
|
1047 |
+
|
1048 |
+
hidden_states = layer_outputs[0]
|
1049 |
+
if use_cache:
|
1050 |
+
next_decoder_cache += (layer_outputs[-1],)
|
1051 |
+
if output_attentions:
|
1052 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
1053 |
+
|
1054 |
+
if output_hidden_states:
|
1055 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1056 |
+
|
1057 |
+
if not return_dict:
|
1058 |
+
return tuple(
|
1059 |
+
v
|
1060 |
+
for v in [
|
1061 |
+
hidden_states,
|
1062 |
+
next_decoder_cache,
|
1063 |
+
all_hidden_states,
|
1064 |
+
all_self_attentions,
|
1065 |
+
all_cross_attentions,
|
1066 |
+
]
|
1067 |
+
if v is not None
|
1068 |
+
)
|
1069 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
1070 |
+
last_hidden_state=hidden_states,
|
1071 |
+
past_key_values=next_decoder_cache,
|
1072 |
+
hidden_states=all_hidden_states,
|
1073 |
+
attentions=all_self_attentions,
|
1074 |
+
cross_attentions=all_cross_attentions,
|
1075 |
+
)
|
1076 |
+
|
1077 |
+
|
1078 |
+
class VisionTransformer(nn.Module):
|
1079 |
+
def __init__(self, config: VisionConfig):
|
1080 |
+
super().__init__()
|
1081 |
+
self.config = config
|
1082 |
+
embed_dim = config.hidden_size
|
1083 |
+
|
1084 |
+
self.embeddings = VisionEmbeddings(config)
|
1085 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
1086 |
+
self.encoder = VisionEncoder(config)
|
1087 |
+
self.post_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
1088 |
+
|
1089 |
+
def forward(
|
1090 |
+
self,
|
1091 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1092 |
+
output_attentions: Optional[bool] = None,
|
1093 |
+
output_hidden_states: Optional[bool] = None,
|
1094 |
+
return_dict: Optional[bool] = None,
|
1095 |
+
intermediate_hidden_state: Optional[bool] = None
|
1096 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
1097 |
+
r"""
|
1098 |
+
Returns:
|
1099 |
+
|
1100 |
+
"""
|
1101 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1102 |
+
output_hidden_states = (
|
1103 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1104 |
+
)
|
1105 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1106 |
+
|
1107 |
+
if pixel_values is None:
|
1108 |
+
raise ValueError("You have to specify pixel_values")
|
1109 |
+
|
1110 |
+
hidden_states = self.embeddings(pixel_values)
|
1111 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
1112 |
+
|
1113 |
+
encoder_outputs = self.encoder(
|
1114 |
+
inputs_embeds=hidden_states,
|
1115 |
+
output_attentions=output_attentions,
|
1116 |
+
output_hidden_states=output_hidden_states,
|
1117 |
+
return_dict=return_dict,
|
1118 |
+
intermediate_hidden_state=intermediate_hidden_state
|
1119 |
+
)
|
1120 |
+
|
1121 |
+
last_hidden_state = self.post_layrnorm(encoder_outputs[0])
|
1122 |
+
pooled_output = last_hidden_state[:, 0, :]
|
1123 |
+
|
1124 |
+
if not return_dict:
|
1125 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
1126 |
+
|
1127 |
+
return BaseModelOutputWithPooling(
|
1128 |
+
last_hidden_state=last_hidden_state,
|
1129 |
+
pooler_output=pooled_output,
|
1130 |
+
hidden_states=encoder_outputs.hidden_states,
|
1131 |
+
attentions=encoder_outputs.attentions,
|
1132 |
+
intermediate_hidden_state=encoder_outputs.intermediate_hidden_state
|
1133 |
+
)
|
1134 |
+
|
1135 |
+
|
1136 |
+
class BertPooler(nn.Module):
|
1137 |
+
def __init__(self, config):
|
1138 |
+
super().__init__()
|
1139 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
1140 |
+
self.activation = nn.Tanh()
|
1141 |
+
|
1142 |
+
def forward(self, hidden_states):
|
1143 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
1144 |
+
# to the first token.
|
1145 |
+
first_token_tensor = hidden_states[:, 0]
|
1146 |
+
pooled_output = self.dense(first_token_tensor)
|
1147 |
+
pooled_output = self.activation(pooled_output)
|
1148 |
+
return pooled_output
|
1149 |
+
|
1150 |
+
|
1151 |
+
class BertPredictionHeadTransform(nn.Module):
|
1152 |
+
def __init__(self, config):
|
1153 |
+
super().__init__()
|
1154 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
1155 |
+
if isinstance(config.hidden_act, str):
|
1156 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
1157 |
+
else:
|
1158 |
+
self.transform_act_fn = config.hidden_act
|
1159 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1160 |
+
|
1161 |
+
def forward(self, hidden_states):
|
1162 |
+
hidden_states = self.dense(hidden_states)
|
1163 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
1164 |
+
hidden_states = self.LayerNorm(hidden_states)
|
1165 |
+
return hidden_states
|
1166 |
+
|
1167 |
+
|
1168 |
+
class BertLMPredictionHead(nn.Module):
|
1169 |
+
def __init__(self, config):
|
1170 |
+
super().__init__()
|
1171 |
+
self.transform = BertPredictionHeadTransform(config)
|
1172 |
+
|
1173 |
+
# The output weights are the same as the input embeddings, but there is
|
1174 |
+
# an output-only bias for each token.
|
1175 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1176 |
+
|
1177 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
1178 |
+
|
1179 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
1180 |
+
self.decoder.bias = self.bias
|
1181 |
+
|
1182 |
+
def forward(self, hidden_states):
|
1183 |
+
hidden_states = self.transform(hidden_states)
|
1184 |
+
hidden_states = self.decoder(hidden_states)
|
1185 |
+
return hidden_states
|
1186 |
+
|
1187 |
+
|
1188 |
+
class BertOnlyMLMHead(nn.Module):
|
1189 |
+
def __init__(self, config):
|
1190 |
+
super().__init__()
|
1191 |
+
self.predictions = BertLMPredictionHead(config)
|
1192 |
+
|
1193 |
+
def forward(self, sequence_output):
|
1194 |
+
prediction_scores = self.predictions(sequence_output)
|
1195 |
+
return prediction_scores
|
1196 |
+
|
1197 |
+
|
1198 |
+
class VisionTrainedModel(PreTrainedModel):
|
1199 |
+
"""
|
1200 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
1201 |
+
models.
|
1202 |
+
"""
|
1203 |
+
|
1204 |
+
# config_class = CLIPConfig
|
1205 |
+
# base_model_prefix = "clip"
|
1206 |
+
supports_gradient_checkpointing = True
|
1207 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1208 |
+
|
1209 |
+
def _init_weights(self, module):
|
1210 |
+
"""Initialize the weights"""
|
1211 |
+
factor = self.config.initializer_factor
|
1212 |
+
if isinstance(module, VisionEmbeddings):
|
1213 |
+
factor = self.config.initializer_factor
|
1214 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
1215 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
1216 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
1217 |
+
elif isinstance(module, Attention):
|
1218 |
+
factor = self.config.initializer_factor
|
1219 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
1220 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
1221 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
1222 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
1223 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
1224 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
1225 |
+
elif isinstance(module, MLP):
|
1226 |
+
factor = self.config.initializer_factor
|
1227 |
+
in_proj_std = (
|
1228 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
1229 |
+
)
|
1230 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
1231 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
1232 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
1233 |
+
|
1234 |
+
if isinstance(module, nn.LayerNorm):
|
1235 |
+
module.bias.data.zero_()
|
1236 |
+
module.weight.data.fill_(1.0)
|
1237 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
1238 |
+
module.bias.data.zero_()
|
1239 |
+
|
1240 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
1241 |
+
if isinstance(module, VisionEncoder):
|
1242 |
+
module.gradient_checkpointing = value
|
1243 |
+
|
1244 |
+
|
1245 |
+
class BertPreTrainedModel(PreTrainedModel):
|
1246 |
+
"""
|
1247 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
1248 |
+
models.
|
1249 |
+
"""
|
1250 |
+
|
1251 |
+
config_class = BertConfig
|
1252 |
+
base_model_prefix = "bert"
|
1253 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1254 |
+
|
1255 |
+
def _init_weights(self, module):
|
1256 |
+
""" Initialize the weights """
|
1257 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
1258 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
1259 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
1260 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
1261 |
+
elif isinstance(module, nn.LayerNorm):
|
1262 |
+
module.bias.data.zero_()
|
1263 |
+
module.weight.data.fill_(1.0)
|
1264 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
1265 |
+
module.bias.data.zero_()
|
1266 |
+
|
1267 |
+
|
1268 |
+
class BertModel(BertPreTrainedModel):
|
1269 |
+
"""
|
1270 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
1271 |
+
cross-attention is added between the self-attention layers, following the architecture described in `Attention is
|
1272 |
+
all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
1273 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
1274 |
+
argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
|
1275 |
+
input to the forward pass.
|
1276 |
+
"""
|
1277 |
+
|
1278 |
+
def __init__(self, config, add_pooling_layer=True):
|
1279 |
+
super().__init__(config)
|
1280 |
+
self.config = config
|
1281 |
+
|
1282 |
+
self.embeddings = BertEmbeddings(config)
|
1283 |
+
|
1284 |
+
self.encoder = BertEncoder(config)
|
1285 |
+
|
1286 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
1287 |
+
|
1288 |
+
self.init_weights()
|
1289 |
+
|
1290 |
+
|
1291 |
+
def get_input_embeddings(self):
|
1292 |
+
return self.embeddings.word_embeddings
|
1293 |
+
|
1294 |
+
def set_input_embeddings(self, value):
|
1295 |
+
self.embeddings.word_embeddings = value
|
1296 |
+
|
1297 |
+
def _prune_heads(self, heads_to_prune):
|
1298 |
+
"""
|
1299 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1300 |
+
class PreTrainedModel
|
1301 |
+
"""
|
1302 |
+
for layer, heads in heads_to_prune.items():
|
1303 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
1304 |
+
|
1305 |
+
|
1306 |
+
def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
|
1307 |
+
"""
|
1308 |
+
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
|
1309 |
+
|
1310 |
+
Arguments:
|
1311 |
+
attention_mask (:obj:`torch.Tensor`):
|
1312 |
+
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
|
1313 |
+
input_shape (:obj:`Tuple[int]`):
|
1314 |
+
The shape of the input to the model.
|
1315 |
+
device: (:obj:`torch.device`):
|
1316 |
+
The device of the input to the model.
|
1317 |
+
|
1318 |
+
Returns:
|
1319 |
+
:obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
|
1320 |
+
"""
|
1321 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1322 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1323 |
+
if attention_mask.dim() == 3:
|
1324 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
1325 |
+
elif attention_mask.dim() == 2:
|
1326 |
+
# Provided a padding mask of dimensions [batch_size, seq_length]
|
1327 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
1328 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1329 |
+
if is_decoder:
|
1330 |
+
batch_size, seq_length = input_shape
|
1331 |
+
|
1332 |
+
seq_ids = torch.arange(seq_length, device=device)
|
1333 |
+
causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
|
1334 |
+
# in case past_key_values are used we need to add a prefix ones mask to the causal mask
|
1335 |
+
# causal and attention masks must have same type with pytorch version < 1.3
|
1336 |
+
causal_mask = causal_mask.to(attention_mask.dtype)
|
1337 |
+
|
1338 |
+
if causal_mask.shape[1] < attention_mask.shape[1]:
|
1339 |
+
prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
|
1340 |
+
causal_mask = torch.cat(
|
1341 |
+
[
|
1342 |
+
torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
|
1343 |
+
causal_mask,
|
1344 |
+
],
|
1345 |
+
axis=-1,
|
1346 |
+
)
|
1347 |
+
|
1348 |
+
extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
|
1349 |
+
else:
|
1350 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
1351 |
+
else:
|
1352 |
+
raise ValueError(
|
1353 |
+
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
|
1354 |
+
input_shape, attention_mask.shape
|
1355 |
+
)
|
1356 |
+
)
|
1357 |
+
|
1358 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
1359 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
1360 |
+
# positions we want to attend and -10000.0 for masked positions.
|
1361 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
1362 |
+
# effectively the same as removing these entirely.
|
1363 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
1364 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
1365 |
+
return extended_attention_mask
|
1366 |
+
|
1367 |
+
def forward(
|
1368 |
+
self,
|
1369 |
+
input_ids=None,
|
1370 |
+
attention_mask=None,
|
1371 |
+
position_ids=None,
|
1372 |
+
head_mask=None,
|
1373 |
+
inputs_embeds=None,
|
1374 |
+
encoder_embeds=None,
|
1375 |
+
encoder_hidden_states=None,
|
1376 |
+
encoder_attention_mask=None,
|
1377 |
+
past_key_values=None,
|
1378 |
+
use_cache=None,
|
1379 |
+
output_attentions=None,
|
1380 |
+
output_hidden_states=None,
|
1381 |
+
return_dict=None,
|
1382 |
+
is_decoder=False,
|
1383 |
+
mode='multimodal',
|
1384 |
+
):
|
1385 |
+
r"""
|
1386 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
1387 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1388 |
+
the model is configured as a decoder.
|
1389 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1390 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1391 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
|
1392 |
+
- 1 for tokens that are **not masked**,
|
1393 |
+
- 0 for tokens that are **masked**.
|
1394 |
+
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
1395 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1396 |
+
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
|
1397 |
+
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
|
1398 |
+
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
|
1399 |
+
use_cache (:obj:`bool`, `optional`):
|
1400 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
1401 |
+
decoding (see :obj:`past_key_values`).
|
1402 |
+
"""
|
1403 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1404 |
+
output_hidden_states = (
|
1405 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1406 |
+
)
|
1407 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1408 |
+
|
1409 |
+
if is_decoder:
|
1410 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1411 |
+
else:
|
1412 |
+
use_cache = False
|
1413 |
+
|
1414 |
+
if input_ids is not None and inputs_embeds is not None:
|
1415 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1416 |
+
elif input_ids is not None:
|
1417 |
+
input_shape = input_ids.size()
|
1418 |
+
batch_size, seq_length = input_shape
|
1419 |
+
device = input_ids.device
|
1420 |
+
elif inputs_embeds is not None:
|
1421 |
+
input_shape = inputs_embeds.size()[:-1]
|
1422 |
+
batch_size, seq_length = input_shape
|
1423 |
+
device = inputs_embeds.device
|
1424 |
+
elif encoder_embeds is not None:
|
1425 |
+
input_shape = encoder_embeds.size()[:-1]
|
1426 |
+
batch_size, seq_length = input_shape
|
1427 |
+
device = encoder_embeds.device
|
1428 |
+
else:
|
1429 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
|
1430 |
+
|
1431 |
+
# past_key_values_length
|
1432 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
1433 |
+
|
1434 |
+
if attention_mask is None:
|
1435 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
1436 |
+
|
1437 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1438 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1439 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
|
1440 |
+
device, is_decoder)
|
1441 |
+
|
1442 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1443 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1444 |
+
if encoder_hidden_states is not None:
|
1445 |
+
if type(encoder_hidden_states) == list:
|
1446 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
|
1447 |
+
else:
|
1448 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
1449 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1450 |
+
|
1451 |
+
if type(encoder_attention_mask) == list:
|
1452 |
+
encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
|
1453 |
+
elif encoder_attention_mask is None:
|
1454 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
1455 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1456 |
+
else:
|
1457 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1458 |
+
else:
|
1459 |
+
encoder_extended_attention_mask = None
|
1460 |
+
|
1461 |
+
# Prepare head mask if needed
|
1462 |
+
# 1.0 in head_mask indicate we keep the head
|
1463 |
+
# attention_probs has shape bsz x n_heads x N x N
|
1464 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
1465 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
1466 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1467 |
+
|
1468 |
+
if encoder_embeds is None:
|
1469 |
+
embedding_output = self.embeddings(
|
1470 |
+
input_ids=input_ids,
|
1471 |
+
position_ids=position_ids,
|
1472 |
+
inputs_embeds=inputs_embeds,
|
1473 |
+
past_key_values_length=past_key_values_length,
|
1474 |
+
)
|
1475 |
+
else:
|
1476 |
+
embedding_output = encoder_embeds
|
1477 |
+
|
1478 |
+
encoder_outputs = self.encoder(
|
1479 |
+
embedding_output,
|
1480 |
+
attention_mask=extended_attention_mask,
|
1481 |
+
head_mask=head_mask,
|
1482 |
+
encoder_hidden_states=encoder_hidden_states,
|
1483 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1484 |
+
past_key_values=past_key_values,
|
1485 |
+
use_cache=use_cache,
|
1486 |
+
output_attentions=output_attentions,
|
1487 |
+
output_hidden_states=output_hidden_states,
|
1488 |
+
return_dict=return_dict,
|
1489 |
+
mode=mode,
|
1490 |
+
)
|
1491 |
+
sequence_output = encoder_outputs[0]
|
1492 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
1493 |
+
|
1494 |
+
if not return_dict:
|
1495 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
1496 |
+
|
1497 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
1498 |
+
last_hidden_state=sequence_output,
|
1499 |
+
pooler_output=pooled_output,
|
1500 |
+
past_key_values=encoder_outputs.past_key_values,
|
1501 |
+
hidden_states=encoder_outputs.hidden_states,
|
1502 |
+
attentions=encoder_outputs.attentions,
|
1503 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
1504 |
+
)
|
1505 |
+
|
1506 |
+
|
1507 |
+
|
1508 |
+
class BertLMHeadModel(BertPreTrainedModel):
|
1509 |
+
|
1510 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1511 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
1512 |
+
|
1513 |
+
def __init__(self, config):
|
1514 |
+
super().__init__(config)
|
1515 |
+
|
1516 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
1517 |
+
self.cls = BertOnlyMLMHead(config)
|
1518 |
+
|
1519 |
+
self.init_weights()
|
1520 |
+
|
1521 |
+
def get_output_embeddings(self):
|
1522 |
+
return self.cls.predictions.decoder
|
1523 |
+
|
1524 |
+
def set_output_embeddings(self, new_embeddings):
|
1525 |
+
self.cls.predictions.decoder = new_embeddings
|
1526 |
+
|
1527 |
+
def forward(
|
1528 |
+
self,
|
1529 |
+
input_ids=None,
|
1530 |
+
attention_mask=None,
|
1531 |
+
position_ids=None,
|
1532 |
+
head_mask=None,
|
1533 |
+
inputs_embeds=None,
|
1534 |
+
encoder_hidden_states=None,
|
1535 |
+
encoder_attention_mask=None,
|
1536 |
+
labels=None,
|
1537 |
+
past_key_values=None,
|
1538 |
+
use_cache=None,
|
1539 |
+
output_attentions=None,
|
1540 |
+
output_hidden_states=None,
|
1541 |
+
return_dict=None,
|
1542 |
+
return_logits=False,
|
1543 |
+
is_decoder=True,
|
1544 |
+
reduction='mean',
|
1545 |
+
mode='multimodal',
|
1546 |
+
):
|
1547 |
+
r"""
|
1548 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
1549 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1550 |
+
the model is configured as a decoder.
|
1551 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1552 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1553 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
|
1554 |
+
- 1 for tokens that are **not masked**,
|
1555 |
+
- 0 for tokens that are **masked**.
|
1556 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1557 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
1558 |
+
``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
|
1559 |
+
ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
|
1560 |
+
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
1561 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1562 |
+
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
|
1563 |
+
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
|
1564 |
+
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
|
1565 |
+
use_cache (:obj:`bool`, `optional`):
|
1566 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
1567 |
+
decoding (see :obj:`past_key_values`).
|
1568 |
+
Returns:
|
1569 |
+
Example::
|
1570 |
+
>>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
|
1571 |
+
>>> import torch
|
1572 |
+
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
|
1573 |
+
>>> config = BertConfig.from_pretrained("bert-base-cased")
|
1574 |
+
>>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
|
1575 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1576 |
+
>>> outputs = model(**inputs)
|
1577 |
+
>>> prediction_logits = outputs.logits
|
1578 |
+
"""
|
1579 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1580 |
+
if labels is not None:
|
1581 |
+
use_cache = False
|
1582 |
+
|
1583 |
+
outputs = self.bert(
|
1584 |
+
input_ids,
|
1585 |
+
attention_mask=attention_mask,
|
1586 |
+
position_ids=position_ids,
|
1587 |
+
head_mask=head_mask,
|
1588 |
+
inputs_embeds=inputs_embeds,
|
1589 |
+
encoder_hidden_states=encoder_hidden_states,
|
1590 |
+
encoder_attention_mask=encoder_attention_mask,
|
1591 |
+
past_key_values=past_key_values,
|
1592 |
+
use_cache=use_cache,
|
1593 |
+
output_attentions=output_attentions,
|
1594 |
+
output_hidden_states=output_hidden_states,
|
1595 |
+
return_dict=return_dict,
|
1596 |
+
is_decoder=is_decoder,
|
1597 |
+
mode=mode,
|
1598 |
+
)
|
1599 |
+
|
1600 |
+
sequence_output = outputs[0]
|
1601 |
+
prediction_scores = self.cls(sequence_output)
|
1602 |
+
|
1603 |
+
if return_logits:
|
1604 |
+
return prediction_scores[:, :-1, :].contiguous()
|
1605 |
+
|
1606 |
+
lm_loss = None
|
1607 |
+
if labels is not None:
|
1608 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1609 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1610 |
+
labels = labels[:, 1:].contiguous()
|
1611 |
+
loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
|
1612 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1613 |
+
if reduction=='none':
|
1614 |
+
lm_loss = lm_loss.view(prediction_scores.size(0),-1).sum(1)
|
1615 |
+
|
1616 |
+
if not return_dict:
|
1617 |
+
output = (prediction_scores,) + outputs[2:]
|
1618 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1619 |
+
|
1620 |
+
return CausalLMOutputWithCrossAttentions(
|
1621 |
+
loss=lm_loss,
|
1622 |
+
logits=prediction_scores,
|
1623 |
+
past_key_values=outputs.past_key_values,
|
1624 |
+
hidden_states=outputs.hidden_states,
|
1625 |
+
attentions=outputs.attentions,
|
1626 |
+
cross_attentions=outputs.cross_attentions,
|
1627 |
+
)
|
1628 |
+
|
1629 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
|
1630 |
+
input_shape = input_ids.shape
|
1631 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1632 |
+
if attention_mask is None:
|
1633 |
+
attention_mask = input_ids.new_ones(input_shape)
|
1634 |
+
|
1635 |
+
# cut decoder_input_ids if past is used
|
1636 |
+
if past is not None:
|
1637 |
+
input_ids = input_ids[:, -1:]
|
1638 |
+
|
1639 |
+
return {
|
1640 |
+
"input_ids": input_ids,
|
1641 |
+
"attention_mask": attention_mask,
|
1642 |
+
"past_key_values": past,
|
1643 |
+
"encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
|
1644 |
+
"encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
|
1645 |
+
"is_decoder": True,
|
1646 |
+
}
|
1647 |
+
|
1648 |
+
def _reorder_cache(self, past, beam_idx):
|
1649 |
+
reordered_past = ()
|
1650 |
+
for layer_past in past:
|
1651 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
1652 |
+
return reordered_past
|
models/utils.py
ADDED
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple, Union
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
# from .p2i_ops import p2i
|
5 |
+
import math
|
6 |
+
from torch import nn
|
7 |
+
|
8 |
+
|
9 |
+
def resize_embedding(embedding_layer, new_size, num_tokens=1, mode='bicubic'):
|
10 |
+
"""Resize the position embedding in an nn.Embedding layer.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
embedding_layer (nn.Embedding): The embedding layer to resize.
|
14 |
+
new_size (int): The new size for the positional embedding.
|
15 |
+
num_tokens (int): The number of special tokens (e.g., CLS token).
|
16 |
+
mode (str): The interpolation mode.
|
17 |
+
|
18 |
+
Returns:
|
19 |
+
nn.Embedding: A new embedding layer with resized position embedding.
|
20 |
+
"""
|
21 |
+
# Extract weights from the original embedding layer
|
22 |
+
original_weights = embedding_layer.weight.data
|
23 |
+
|
24 |
+
# Resize the weights using the provided function
|
25 |
+
resized_weights = _resize_pe(original_weights, new_size, mode, num_tokens)
|
26 |
+
|
27 |
+
# Create a new embedding layer and initialize it with the resized weights
|
28 |
+
new_embedding_layer = nn.Embedding(resized_weights.size(0), resized_weights.size(1))
|
29 |
+
new_embedding_layer.weight.data = resized_weights
|
30 |
+
|
31 |
+
return new_embedding_layer
|
32 |
+
|
33 |
+
|
34 |
+
def _resize_pe(pe: torch.Tensor, new_size: int, mode: str = 'bicubic', num_tokens: int = 1) -> torch.Tensor:
|
35 |
+
"""Resize positional embeddings.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
pe (torch.Tensor): A tensor with shape (num_tokens + old_size ** 2, width). pe[0, :] is the CLS token.
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
torch.Tensor: A tensor with shape (num_tokens + new_size **2, width).
|
42 |
+
"""
|
43 |
+
l, w = pe.shape
|
44 |
+
old_size = int(math.sqrt(l-num_tokens))
|
45 |
+
assert old_size ** 2 + num_tokens == l
|
46 |
+
return torch.cat([
|
47 |
+
pe[:num_tokens, :],
|
48 |
+
F.interpolate(pe[num_tokens:, :].reshape(1, old_size, old_size, w).permute(0, 3, 1, 2),
|
49 |
+
(new_size, new_size), mode=mode, align_corners=False).view(w, -1).t()], dim=0)
|
50 |
+
|
51 |
+
|
52 |
+
def normalize_points(points: torch.Tensor, h: int, w: int) -> torch.Tensor:
|
53 |
+
""" Normalize coordinates to [0, 1].
|
54 |
+
"""
|
55 |
+
return (points + 0.5) / torch.tensor([[[w, h]]]).to(points)
|
56 |
+
|
57 |
+
def denormalize_points(normalized_points: torch.Tensor, h: int, w: int) -> torch.Tensor:
|
58 |
+
""" Reverse normalize_points.
|
59 |
+
"""
|
60 |
+
return normalized_points * torch.tensor([[[w, h]]]).to(normalized_points) - 0.5
|
61 |
+
|
62 |
+
# def points2heatmap(normalized_points, heatmap_size: Tuple[int, int], kernel_radius: float):
|
63 |
+
# """ Normalized points [b x npoints x 2(XY)] -> heatmaps.
|
64 |
+
# """
|
65 |
+
# batch, npoints, _ = normalized_points.shape
|
66 |
+
# out_h, out_w = heatmap_size
|
67 |
+
|
68 |
+
# points = denormalize_points(normalized_points, out_h, out_w)
|
69 |
+
|
70 |
+
# # (batch x npoints) x 1 x h x w
|
71 |
+
# heatmap = torch.zeros(
|
72 |
+
# batch * npoints, 1, out_h, out_w).to(points)
|
73 |
+
# # (batch x npoints) x 2
|
74 |
+
# points_flatten = points.view(-1, 2)
|
75 |
+
# # (batch x npoints)
|
76 |
+
# batch_inds = torch.arange(
|
77 |
+
# batch * npoints, dtype=torch.int32).cuda()
|
78 |
+
# # (batch x npoints) x 1
|
79 |
+
# points_color = torch.ones(
|
80 |
+
# points_flatten.size(0), 1).to(points_flatten)
|
81 |
+
# # (batch x npoints) x 1 x h x w
|
82 |
+
# heatmap = p2i(points_flatten, points_color, batch_inds=batch_inds, background=heatmap,
|
83 |
+
# kernel_radius=kernel_radius,
|
84 |
+
# kernel_kind_str='gaussian_awing', reduce='max')
|
85 |
+
# # batch x npoints x h x w
|
86 |
+
# heatmap = heatmap.reshape(batch, npoints, out_h, out_w)
|
87 |
+
# return heatmap
|
88 |
+
|
89 |
+
def heatmap2points(heatmap, t_scale: Union[None, float, torch.Tensor] = None):
|
90 |
+
""" Heatmaps -> normalized points [b x npoints x 2(XY)].
|
91 |
+
"""
|
92 |
+
dtype = heatmap.dtype
|
93 |
+
_, _, h, w = heatmap.shape
|
94 |
+
|
95 |
+
# 0 ~ h-1, 0 ~ w-1
|
96 |
+
yy, xx = torch.meshgrid(
|
97 |
+
torch.arange(h).float(),
|
98 |
+
torch.arange(w).float())
|
99 |
+
|
100 |
+
yy = yy.view(1, 1, h, w).to(heatmap)
|
101 |
+
xx = xx.view(1, 1, h, w).to(heatmap)
|
102 |
+
|
103 |
+
if t_scale is not None:
|
104 |
+
heatmap = (heatmap * t_scale).exp()
|
105 |
+
heatmap_sum = torch.clamp(heatmap.sum([2, 3]), min=1e-6)
|
106 |
+
|
107 |
+
yy_coord = (yy * heatmap).sum([2, 3]) / heatmap_sum # b x npoints
|
108 |
+
xx_coord = (xx * heatmap).sum([2, 3]) / heatmap_sum # b x npoints
|
109 |
+
|
110 |
+
points = torch.stack([xx_coord, yy_coord], dim=-1) # b x npoints x 2
|
111 |
+
|
112 |
+
normalized_points = normalize_points(points, h, w)
|
113 |
+
return normalized_points
|
114 |
+
|
115 |
+
|
116 |
+
def _expand_as_rgbs(x):
|
117 |
+
_, c, _, _ = x.shape
|
118 |
+
if c == 3:
|
119 |
+
return [x]
|
120 |
+
|
121 |
+
if c % 3 > 0:
|
122 |
+
x = torch.cat([
|
123 |
+
x, x[:, [-1], :, :].expand(
|
124 |
+
-1, 3 - c % 3, -1, -1)], dim=1)
|
125 |
+
c = x.size(1)
|
126 |
+
assert c % 3 == 0
|
127 |
+
return list(x.split([3] * (c // 3), dim=1))
|
128 |
+
|
129 |
+
|
130 |
+
def _visualize_flags(flags, size, num_flags):
|
131 |
+
batch_size = flags.size(0)
|
132 |
+
flags = flags.to(dtype=torch.uint8)
|
133 |
+
has_what = [flags & torch.full_like(flags, 1 << i)
|
134 |
+
for i in range(num_flags)]
|
135 |
+
# batch x 1 x 1 x 4
|
136 |
+
vis_im = torch.stack(has_what, dim=1).float().view(
|
137 |
+
batch_size, 1, 1, num_flags)
|
138 |
+
vis_im = F.interpolate(vis_im.expand(-1, 3, -1, -1),
|
139 |
+
size=size, mode='nearest')
|
140 |
+
return vis_im
|
141 |
+
|
142 |
+
|
143 |
+
# def visualize_in_row(*data) -> torch.Tensor:
|
144 |
+
# """Visualize data in one row.
|
145 |
+
|
146 |
+
# Args:
|
147 |
+
# *data (list): A list of (value, modal, [v_min, v_max]) tuples.
|
148 |
+
|
149 |
+
# Each tuple defines the following inputs:
|
150 |
+
|
151 |
+
# value (torch.Tensor): The data value to visualize.
|
152 |
+
# modal (str): The modal type string of the data.
|
153 |
+
# Supported data modal types are:
|
154 |
+
|
155 |
+
# * "BHW", "BNHW", "BHWN" for tensors;
|
156 |
+
# * "flags_{K}" for binary flags, with K being the number of bits;
|
157 |
+
# * "points" for points, where `value` is a tensor with shape [B, N, 2].
|
158 |
+
|
159 |
+
# v_min (float): Optional, to normalize value.
|
160 |
+
# v_max (float): Optional, to normalize value.
|
161 |
+
|
162 |
+
# Returns:
|
163 |
+
# torch.Tensor: A tensor with shape b x 3 x h x w.
|
164 |
+
# """
|
165 |
+
# batch = None
|
166 |
+
# size = None
|
167 |
+
# device = None
|
168 |
+
|
169 |
+
# row = []
|
170 |
+
# for v in data:
|
171 |
+
# assert isinstance(v, (tuple, list))
|
172 |
+
# if len(v) == 2:
|
173 |
+
# value, modal = v
|
174 |
+
# v_min, v_max = 0.0, 1.0
|
175 |
+
# elif len(v) == 4:
|
176 |
+
# value, modal, v_min, v_max = v
|
177 |
+
# else:
|
178 |
+
# raise RuntimeError(
|
179 |
+
# 'Input either (value, modal) or (value, modal, v_min, v_max)')
|
180 |
+
|
181 |
+
# if value is None:
|
182 |
+
# assert batch is not None
|
183 |
+
# assert size is not None
|
184 |
+
# assert device is not None
|
185 |
+
# value = torch.rand(batch, 1, size[0], size[1], device=device)
|
186 |
+
# modal = 'BNHW'
|
187 |
+
# v_min, v_max = 0.0, 1.0
|
188 |
+
|
189 |
+
# if modal == 'BHW':
|
190 |
+
# assert isinstance(value, torch.Tensor)
|
191 |
+
# value = value.detach().float()
|
192 |
+
|
193 |
+
# batch = value.size(0)
|
194 |
+
# size = value.shape[1:]
|
195 |
+
# device = value.device
|
196 |
+
|
197 |
+
# value = (value - v_min) / (v_max - v_min)
|
198 |
+
# row.append(value.unsqueeze(
|
199 |
+
# 1).expand(-1, 3, -1, -1))
|
200 |
+
|
201 |
+
# elif modal == 'BNHW':
|
202 |
+
# assert isinstance(value, torch.Tensor)
|
203 |
+
# value = value.detach().float()
|
204 |
+
|
205 |
+
# batch = value.size(0)
|
206 |
+
# size = value.shape[2:]
|
207 |
+
# device = value.device
|
208 |
+
|
209 |
+
# value = (value - v_min) / (v_max - v_min)
|
210 |
+
# row += _expand_as_rgbs(value)
|
211 |
+
|
212 |
+
# elif modal == 'BHWN':
|
213 |
+
# assert isinstance(value, torch.Tensor)
|
214 |
+
# value = value.detach().float().permute(0, 3, 1, 2)
|
215 |
+
|
216 |
+
# batch = value.size(0)
|
217 |
+
# size = value.shape[2:]
|
218 |
+
# device = value.device
|
219 |
+
|
220 |
+
# value = (value - v_min) / (v_max - v_min)
|
221 |
+
# row += _expand_as_rgbs(value)
|
222 |
+
|
223 |
+
# elif modal.startswith('flags_'):
|
224 |
+
# assert isinstance(value, torch.Tensor)
|
225 |
+
# value = value.detach().float()
|
226 |
+
|
227 |
+
# batch = value.size(0)
|
228 |
+
# device = value.device
|
229 |
+
|
230 |
+
# num_flags = int(modal.split('_')[1])
|
231 |
+
# assert size is not None
|
232 |
+
# row.append(_visualize_flags(value, size, num_flags))
|
233 |
+
|
234 |
+
# elif modal == 'points':
|
235 |
+
# points, background = value
|
236 |
+
|
237 |
+
# if background is None:
|
238 |
+
# background = torch.rand(
|
239 |
+
# batch, 1, size[0], size[1], device=device)
|
240 |
+
# else:
|
241 |
+
# assert isinstance(background, torch.Tensor)
|
242 |
+
# background = background.detach().float()
|
243 |
+
# background = (background - v_min) / (v_max - v_min)
|
244 |
+
|
245 |
+
# if points is None:
|
246 |
+
# canvas = background
|
247 |
+
# else:
|
248 |
+
# assert isinstance(points, torch.Tensor)
|
249 |
+
# points = points.detach().float()
|
250 |
+
# points = denormalize_points(
|
251 |
+
# points, background.size(2), background.size(3))
|
252 |
+
|
253 |
+
# npoints = points.size(1)
|
254 |
+
# batch = background.size(0)
|
255 |
+
# assert points.size(0) == batch
|
256 |
+
# channels = background.size(1)
|
257 |
+
|
258 |
+
# points = points.reshape(npoints * batch, 2)
|
259 |
+
|
260 |
+
# point_colors = torch.ones(
|
261 |
+
# npoints * batch, channels, dtype=background.dtype, device=background.device)
|
262 |
+
# batch_inds = torch.arange(batch).unsqueeze(1).expand(-1, npoints).reshape(
|
263 |
+
# npoints * batch).to(dtype=torch.int32, device=background.device)
|
264 |
+
# canvas = p2i(points, point_colors, batch_inds, background, 5)
|
265 |
+
|
266 |
+
# row.append(canvas)
|
267 |
+
|
268 |
+
# return torch.cat(row, dim=-1)
|
269 |
+
|
270 |
+
|
271 |
+
import math
|
272 |
+
def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr):
|
273 |
+
"""Decay the learning rate"""
|
274 |
+
lr = (init_lr - min_lr) * 0.5 * (1. + math.cos(math.pi * epoch / max_epoch)) + min_lr
|
275 |
+
for param_group in optimizer.param_groups:
|
276 |
+
param_group['lr'] = lr
|
277 |
+
|
278 |
+
def warmup_lr_schedule(optimizer, step, max_step, init_lr, max_lr):
|
279 |
+
"""Warmup the learning rate"""
|
280 |
+
lr = min(max_lr, init_lr + (max_lr - init_lr) * step / max_step)
|
281 |
+
for param_group in optimizer.param_groups:
|
282 |
+
param_group['lr'] = lr
|
283 |
+
|
284 |
+
def step_lr_schedule(optimizer, epoch, init_lr, min_lr, decay_rate):
|
285 |
+
"""Decay the learning rate"""
|
286 |
+
lr = max(min_lr, init_lr * (decay_rate**epoch))
|
287 |
+
for param_group in optimizer.param_groups:
|
288 |
+
param_group['lr'] = lr
|
289 |
+
|
290 |
+
import numpy as np
|
291 |
+
import io
|
292 |
+
import os
|
293 |
+
import time
|
294 |
+
from collections import defaultdict, deque
|
295 |
+
import datetime
|
296 |
+
|
297 |
+
import torch
|
298 |
+
import torch.distributed as dist
|
299 |
+
|
300 |
+
class SmoothedValue(object):
|
301 |
+
"""Track a series of values and provide access to smoothed values over a
|
302 |
+
window or the global series average.
|
303 |
+
"""
|
304 |
+
|
305 |
+
def __init__(self, window_size=20, fmt=None):
|
306 |
+
if fmt is None:
|
307 |
+
fmt = "{median:.4f} ({global_avg:.4f})"
|
308 |
+
self.deque = deque(maxlen=window_size)
|
309 |
+
self.total = 0.0
|
310 |
+
self.count = 0
|
311 |
+
self.fmt = fmt
|
312 |
+
|
313 |
+
def update(self, value, n=1):
|
314 |
+
self.deque.append(value)
|
315 |
+
self.count += n
|
316 |
+
self.total += value * n
|
317 |
+
|
318 |
+
def synchronize_between_processes(self):
|
319 |
+
"""
|
320 |
+
Warning: does not synchronize the deque!
|
321 |
+
"""
|
322 |
+
if not is_dist_avail_and_initialized():
|
323 |
+
return
|
324 |
+
t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
|
325 |
+
dist.barrier()
|
326 |
+
dist.all_reduce(t)
|
327 |
+
t = t.tolist()
|
328 |
+
self.count = int(t[0])
|
329 |
+
self.total = t[1]
|
330 |
+
|
331 |
+
@property
|
332 |
+
def median(self):
|
333 |
+
d = torch.tensor(list(self.deque))
|
334 |
+
return d.median().item()
|
335 |
+
|
336 |
+
@property
|
337 |
+
def avg(self):
|
338 |
+
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
339 |
+
return d.mean().item()
|
340 |
+
|
341 |
+
@property
|
342 |
+
def global_avg(self):
|
343 |
+
return self.total / self.count
|
344 |
+
|
345 |
+
@property
|
346 |
+
def max(self):
|
347 |
+
return max(self.deque)
|
348 |
+
|
349 |
+
@property
|
350 |
+
def value(self):
|
351 |
+
return self.deque[-1]
|
352 |
+
|
353 |
+
def __str__(self):
|
354 |
+
return self.fmt.format(
|
355 |
+
median=self.median,
|
356 |
+
avg=self.avg,
|
357 |
+
global_avg=self.global_avg,
|
358 |
+
max=self.max,
|
359 |
+
value=self.value)
|
360 |
+
|
361 |
+
|
362 |
+
class MetricLogger(object):
|
363 |
+
def __init__(self, delimiter="\t"):
|
364 |
+
self.meters = defaultdict(SmoothedValue)
|
365 |
+
self.delimiter = delimiter
|
366 |
+
|
367 |
+
def update(self, **kwargs):
|
368 |
+
for k, v in kwargs.items():
|
369 |
+
if isinstance(v, torch.Tensor):
|
370 |
+
v = v.item()
|
371 |
+
assert isinstance(v, (float, int))
|
372 |
+
self.meters[k].update(v)
|
373 |
+
|
374 |
+
def __getattr__(self, attr):
|
375 |
+
if attr in self.meters:
|
376 |
+
return self.meters[attr]
|
377 |
+
if attr in self.__dict__:
|
378 |
+
return self.__dict__[attr]
|
379 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(
|
380 |
+
type(self).__name__, attr))
|
381 |
+
|
382 |
+
def __str__(self):
|
383 |
+
loss_str = []
|
384 |
+
for name, meter in self.meters.items():
|
385 |
+
loss_str.append(
|
386 |
+
"{}: {}".format(name, str(meter))
|
387 |
+
)
|
388 |
+
return self.delimiter.join(loss_str)
|
389 |
+
|
390 |
+
def global_avg(self):
|
391 |
+
loss_str = []
|
392 |
+
for name, meter in self.meters.items():
|
393 |
+
loss_str.append(
|
394 |
+
"{}: {:.4f}".format(name, meter.global_avg)
|
395 |
+
)
|
396 |
+
return self.delimiter.join(loss_str)
|
397 |
+
|
398 |
+
def synchronize_between_processes(self):
|
399 |
+
for meter in self.meters.values():
|
400 |
+
meter.synchronize_between_processes()
|
401 |
+
|
402 |
+
def add_meter(self, name, meter):
|
403 |
+
self.meters[name] = meter
|
404 |
+
|
405 |
+
def log_every(self, iterable, print_freq, header=None):
|
406 |
+
i = 0
|
407 |
+
if not header:
|
408 |
+
header = ''
|
409 |
+
start_time = time.time()
|
410 |
+
end = time.time()
|
411 |
+
iter_time = SmoothedValue(fmt='{avg:.4f}')
|
412 |
+
data_time = SmoothedValue(fmt='{avg:.4f}')
|
413 |
+
space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
|
414 |
+
log_msg = [
|
415 |
+
header,
|
416 |
+
'[{0' + space_fmt + '}/{1}]',
|
417 |
+
'eta: {eta}',
|
418 |
+
'{meters}',
|
419 |
+
'time: {time}',
|
420 |
+
'data: {data}'
|
421 |
+
]
|
422 |
+
if torch.cuda.is_available():
|
423 |
+
log_msg.append('max mem: {memory:.0f}')
|
424 |
+
log_msg = self.delimiter.join(log_msg)
|
425 |
+
MB = 1024.0 * 1024.0
|
426 |
+
for obj in iterable:
|
427 |
+
data_time.update(time.time() - end)
|
428 |
+
yield obj
|
429 |
+
iter_time.update(time.time() - end)
|
430 |
+
if i % print_freq == 0 or i == len(iterable) - 1:
|
431 |
+
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
432 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
433 |
+
if torch.cuda.is_available():
|
434 |
+
print(log_msg.format(
|
435 |
+
i, len(iterable), eta=eta_string,
|
436 |
+
meters=str(self),
|
437 |
+
time=str(iter_time), data=str(data_time),
|
438 |
+
memory=torch.cuda.max_memory_allocated() / MB))
|
439 |
+
else:
|
440 |
+
print(log_msg.format(
|
441 |
+
i, len(iterable), eta=eta_string,
|
442 |
+
meters=str(self),
|
443 |
+
time=str(iter_time), data=str(data_time)))
|
444 |
+
i += 1
|
445 |
+
end = time.time()
|
446 |
+
total_time = time.time() - start_time
|
447 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
448 |
+
print('{} Total time: {} ({:.4f} s / it)'.format(
|
449 |
+
header, total_time_str, total_time / len(iterable)))
|
450 |
+
|
451 |
+
|
452 |
+
class AttrDict(dict):
|
453 |
+
def __init__(self, *args, **kwargs):
|
454 |
+
super(AttrDict, self).__init__(*args, **kwargs)
|
455 |
+
self.__dict__ = self
|
456 |
+
|
457 |
+
|
458 |
+
def compute_acc(logits, label, reduction='mean'):
|
459 |
+
ret = (torch.argmax(logits, dim=1) == label).float()
|
460 |
+
if reduction == 'none':
|
461 |
+
return ret.detach()
|
462 |
+
elif reduction == 'mean':
|
463 |
+
return ret.mean().item()
|
464 |
+
|
465 |
+
def compute_n_params(model, return_str=True):
|
466 |
+
tot = 0
|
467 |
+
for p in model.parameters():
|
468 |
+
w = 1
|
469 |
+
for x in p.shape:
|
470 |
+
w *= x
|
471 |
+
tot += w
|
472 |
+
if return_str:
|
473 |
+
if tot >= 1e6:
|
474 |
+
return '{:.1f}M'.format(tot / 1e6)
|
475 |
+
else:
|
476 |
+
return '{:.1f}K'.format(tot / 1e3)
|
477 |
+
else:
|
478 |
+
return tot
|
479 |
+
|
480 |
+
def setup_for_distributed(is_master):
|
481 |
+
"""
|
482 |
+
This function disables printing when not in master process
|
483 |
+
"""
|
484 |
+
import builtins as __builtin__
|
485 |
+
builtin_print = __builtin__.print
|
486 |
+
|
487 |
+
def print(*args, **kwargs):
|
488 |
+
force = kwargs.pop('force', False)
|
489 |
+
if is_master or force:
|
490 |
+
builtin_print(*args, **kwargs)
|
491 |
+
|
492 |
+
__builtin__.print = print
|
493 |
+
|
494 |
+
|
495 |
+
def is_dist_avail_and_initialized():
|
496 |
+
if not dist.is_available():
|
497 |
+
return False
|
498 |
+
if not dist.is_initialized():
|
499 |
+
return False
|
500 |
+
return True
|
501 |
+
|
502 |
+
|
503 |
+
def get_world_size():
|
504 |
+
if not is_dist_avail_and_initialized():
|
505 |
+
return 1
|
506 |
+
return dist.get_world_size()
|
507 |
+
|
508 |
+
|
509 |
+
def get_rank():
|
510 |
+
if not is_dist_avail_and_initialized():
|
511 |
+
return 0
|
512 |
+
return dist.get_rank()
|
513 |
+
|
514 |
+
|
515 |
+
def is_main_process():
|
516 |
+
return get_rank() == 0
|
517 |
+
|
518 |
+
|
519 |
+
def save_on_master(*args, **kwargs):
|
520 |
+
if is_main_process():
|
521 |
+
torch.save(*args, **kwargs)
|
522 |
+
|
523 |
+
|
524 |
+
def init_distributed_mode(args):
|
525 |
+
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
|
526 |
+
args.rank = int(os.environ["RANK"])
|
527 |
+
args.world_size = int(os.environ['WORLD_SIZE'])
|
528 |
+
args.gpu = int(os.environ['LOCAL_RANK'])
|
529 |
+
elif 'SLURM_PROCID' in os.environ:
|
530 |
+
args.rank = int(os.environ['SLURM_PROCID'])
|
531 |
+
args.gpu = args.rank % torch.cuda.device_count()
|
532 |
+
else:
|
533 |
+
print('Not using distributed mode')
|
534 |
+
args.distributed = False
|
535 |
+
return
|
536 |
+
|
537 |
+
args.distributed = True
|
538 |
+
|
539 |
+
torch.cuda.set_device(args.gpu)
|
540 |
+
args.dist_backend = 'nccl'
|
541 |
+
print('| distributed init (rank {}, word {}): {}'.format(
|
542 |
+
args.rank, args.world_size, args.dist_url), flush=True)
|
543 |
+
torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
|
544 |
+
world_size=args.world_size, rank=args.rank)
|
545 |
+
torch.distributed.barrier()
|
546 |
+
setup_for_distributed(args.rank == 0)
|
547 |
+
|
548 |
+
|
pretrain.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
* Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
* All rights reserved.
|
4 |
+
* SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
* By Junnan Li
|
7 |
+
'''
|
8 |
+
import argparse
|
9 |
+
import os
|
10 |
+
from ruamel.yaml import YAML
|
11 |
+
import numpy as np
|
12 |
+
import random
|
13 |
+
import time
|
14 |
+
import datetime
|
15 |
+
import json
|
16 |
+
from pathlib import Path
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
import torch.nn.functional as F
|
20 |
+
import torch.backends.cudnn as cudnn
|
21 |
+
import torch.distributed as dist
|
22 |
+
from torch.cuda.amp import GradScaler, autocast
|
23 |
+
from models.fflip_pretrain import fflip_pretrain
|
24 |
+
from models import utils
|
25 |
+
from eval.pretrain_eval import evaluation, itm_eval
|
26 |
+
from models.utils import warmup_lr_schedule, step_lr_schedule
|
27 |
+
from data import create_dataset, create_sampler, create_loader
|
28 |
+
import sys
|
29 |
+
|
30 |
+
|
31 |
+
def train(model, data_loader, optimizer, epoch, device, config):
|
32 |
+
# train
|
33 |
+
model.train()
|
34 |
+
|
35 |
+
metric_logger = utils.MetricLogger(delimiter=" ")
|
36 |
+
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
|
37 |
+
metric_logger.add_meter('loss_ita', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
|
38 |
+
metric_logger.add_meter('loss_itm', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
|
39 |
+
|
40 |
+
header = 'Train Epoch: [{}]'.format(epoch)
|
41 |
+
print_freq = 50
|
42 |
+
# 混合精度训练配置
|
43 |
+
scaler = GradScaler()
|
44 |
+
|
45 |
+
for i, (image, caption, idx) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
46 |
+
if epoch==0:
|
47 |
+
warmup_lr_schedule(optimizer, i, config['warmup_steps'], config['warmup_lr'], config['init_lr'])
|
48 |
+
image = image.to(device, non_blocking=True)
|
49 |
+
idx = idx.to(device,non_blocking=True)
|
50 |
+
|
51 |
+
optimizer.zero_grad()
|
52 |
+
|
53 |
+
# ramp up alpha in the first 2 epochs
|
54 |
+
alpha = config['alpha']*min(1,(epoch*len(data_loader)+i)/(2*len(data_loader)))
|
55 |
+
|
56 |
+
loss_ita, loss_itm = model(image, caption, alpha = alpha, idx=idx)
|
57 |
+
loss = loss_ita + loss_itm
|
58 |
+
|
59 |
+
# loss.backward()
|
60 |
+
# optimizer.step()
|
61 |
+
# mixed precision training
|
62 |
+
scaler.scale(loss).backward()
|
63 |
+
scaler.step(optimizer)
|
64 |
+
scaler.update()
|
65 |
+
|
66 |
+
metric_logger.update(loss_ita=loss_ita.item())
|
67 |
+
metric_logger.update(loss_itm=loss_itm.item())
|
68 |
+
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
69 |
+
|
70 |
+
|
71 |
+
# gather the stats from all processes
|
72 |
+
metric_logger.synchronize_between_processes()
|
73 |
+
print("Averaged stats:", metric_logger.global_avg())
|
74 |
+
return {k: "{:.3f}".format(meter.global_avg) for k, meter in metric_logger.meters.items()}
|
75 |
+
|
76 |
+
|
77 |
+
def main(args, config):
|
78 |
+
utils.init_distributed_mode(args)
|
79 |
+
|
80 |
+
device = torch.device(args.device)
|
81 |
+
|
82 |
+
# fix the seed for reproducibility
|
83 |
+
seed = args.seed + utils.get_rank()
|
84 |
+
torch.manual_seed(seed)
|
85 |
+
np.random.seed(seed)
|
86 |
+
random.seed(seed)
|
87 |
+
cudnn.benchmark = True
|
88 |
+
|
89 |
+
#### Dataset ####
|
90 |
+
print("Creating dataset")
|
91 |
+
train_dataset, test_dataset = create_dataset(config['dataset'], config)
|
92 |
+
|
93 |
+
if args.distributed:
|
94 |
+
num_tasks = utils.get_world_size()
|
95 |
+
global_rank = utils.get_rank()
|
96 |
+
samplers = create_sampler([train_dataset], [True], num_tasks, global_rank) + [None]
|
97 |
+
else:
|
98 |
+
samplers = [None, None]
|
99 |
+
|
100 |
+
train_loader, test_loader = create_loader([train_dataset, test_dataset], samplers,
|
101 |
+
batch_size=[config['batch_size_train']] + [config['batch_size_test']],
|
102 |
+
num_workers=[8, 8],
|
103 |
+
is_trains=[True, False],
|
104 |
+
collate_fns=[None, None])
|
105 |
+
#### Model ####
|
106 |
+
print("Creating model")
|
107 |
+
model = fflip_pretrain(pretrained=config['pretrained'], config=config['config'], vit=config['vit'], queue_size=config['queue_size'])
|
108 |
+
|
109 |
+
model = model.to(device)
|
110 |
+
|
111 |
+
optimizer = torch.optim.AdamW(params=model.parameters(), lr=config['init_lr'], weight_decay=config['weight_decay'])
|
112 |
+
|
113 |
+
start_epoch = 0
|
114 |
+
if args.checkpoint:
|
115 |
+
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
116 |
+
state_dict = checkpoint['model']
|
117 |
+
model.load_state_dict(state_dict)
|
118 |
+
|
119 |
+
optimizer.load_state_dict(checkpoint['optimizer'])
|
120 |
+
start_epoch = checkpoint['epoch']
|
121 |
+
print('resume checkpoint from %s'%args.checkpoint)
|
122 |
+
|
123 |
+
model_without_ddp = model
|
124 |
+
if args.distributed:
|
125 |
+
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
|
126 |
+
model_without_ddp = model.module
|
127 |
+
|
128 |
+
best = 0
|
129 |
+
best_epoch = 0
|
130 |
+
|
131 |
+
print("Start training")
|
132 |
+
start_time = time.time()
|
133 |
+
for epoch in range(start_epoch, config['max_epoch']):
|
134 |
+
if not args.evaluate:
|
135 |
+
if args.distributed:
|
136 |
+
train_loader.sampler.set_epoch(epoch)
|
137 |
+
step_lr_schedule(optimizer, epoch, config['init_lr'], config['min_lr'], config['lr_decay_rate'])
|
138 |
+
|
139 |
+
train_stats = train(model, train_loader, optimizer, epoch, device, config)
|
140 |
+
|
141 |
+
score_test_i2t, score_test_t2i = evaluation(args, model_without_ddp, test_loader, device, config)
|
142 |
+
|
143 |
+
if utils.is_main_process():
|
144 |
+
test_result = itm_eval(score_test_i2t, score_test_t2i, test_loader.dataset.txt2img,
|
145 |
+
test_loader.dataset.img2txt)
|
146 |
+
print(test_result)
|
147 |
+
if args.evaluate:
|
148 |
+
log_stats = {**{f'test_{k}': v for k, v in test_result.items()}}
|
149 |
+
with open(os.path.join(args.output_dir, "evaluate_log.txt"), "a") as f:
|
150 |
+
f.write(json.dumps(log_stats) + "\n")
|
151 |
+
else:
|
152 |
+
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
|
153 |
+
**{f'test_{k}': v for k, v in test_result.items()},
|
154 |
+
'epoch': epoch,
|
155 |
+
'best_epoch': best_epoch,
|
156 |
+
}
|
157 |
+
with open(os.path.join(args.output_dir, "train_log.txt"), "a") as f:
|
158 |
+
f.write(json.dumps(log_stats) + "\n")
|
159 |
+
|
160 |
+
save_obj = {
|
161 |
+
'model': model_without_ddp.state_dict(),
|
162 |
+
'optimizer': optimizer.state_dict(),
|
163 |
+
'config': config,
|
164 |
+
'epoch': epoch,
|
165 |
+
}
|
166 |
+
torch.save(save_obj, os.path.join(args.output_dir, 'checkpoint_%02d.pth'%epoch))
|
167 |
+
|
168 |
+
if test_result['r_mean'] > best:
|
169 |
+
torch.save(save_obj, os.path.join(args.output_dir, 'checkpoint_best.pth'))
|
170 |
+
best = test_result['r_mean']
|
171 |
+
best_epoch = epoch
|
172 |
+
|
173 |
+
if args.distributed:
|
174 |
+
dist.barrier()
|
175 |
+
|
176 |
+
total_time = time.time() - start_time
|
177 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
178 |
+
print('Training time {}'.format(total_time_str))
|
179 |
+
|
180 |
+
|
181 |
+
if __name__ == '__main__':
|
182 |
+
|
183 |
+
parser = argparse.ArgumentParser()
|
184 |
+
parser.add_argument('--config', default='./configs/pretrain.yaml')
|
185 |
+
parser.add_argument('--output_dir', default='./outputs')
|
186 |
+
parser.add_argument('--checkpoint', default='')
|
187 |
+
parser.add_argument('--evaluate', type=bool, default=False)
|
188 |
+
parser.add_argument('--device', default='cuda')
|
189 |
+
parser.add_argument('--seed', default=42, type=int)
|
190 |
+
parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes')
|
191 |
+
parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
|
192 |
+
parser.add_argument('--distributed', default=False, type=bool, help='whether to use distributed mode to training')
|
193 |
+
args = parser.parse_args()
|
194 |
+
|
195 |
+
yaml = YAML(typ='safe')
|
196 |
+
config = yaml.load(open(args.config, 'r'))
|
197 |
+
|
198 |
+
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
199 |
+
|
200 |
+
yaml.dump(config, open(os.path.join(args.output_dir, 'config.yaml'), 'w'))
|
201 |
+
|
202 |
+
main(args, config)
|
utils.py
ADDED
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr):
|
3 |
+
"""Decay the learning rate"""
|
4 |
+
lr = (init_lr - min_lr) * 0.5 * (1. + math.cos(math.pi * epoch / max_epoch)) + min_lr
|
5 |
+
for param_group in optimizer.param_groups:
|
6 |
+
param_group['lr'] = lr
|
7 |
+
|
8 |
+
def warmup_lr_schedule(optimizer, step, max_step, init_lr, max_lr):
|
9 |
+
"""Warmup the learning rate"""
|
10 |
+
lr = min(max_lr, init_lr + (max_lr - init_lr) * step / max_step)
|
11 |
+
for param_group in optimizer.param_groups:
|
12 |
+
param_group['lr'] = lr
|
13 |
+
|
14 |
+
def step_lr_schedule(optimizer, epoch, init_lr, min_lr, decay_rate):
|
15 |
+
"""Decay the learning rate"""
|
16 |
+
lr = max(min_lr, init_lr * (decay_rate**epoch))
|
17 |
+
for param_group in optimizer.param_groups:
|
18 |
+
param_group['lr'] = lr
|
19 |
+
|
20 |
+
import numpy as np
|
21 |
+
import io
|
22 |
+
import os
|
23 |
+
import time
|
24 |
+
from collections import defaultdict, deque
|
25 |
+
import datetime
|
26 |
+
|
27 |
+
import torch
|
28 |
+
import torch.distributed as dist
|
29 |
+
|
30 |
+
class SmoothedValue(object):
|
31 |
+
"""Track a series of values and provide access to smoothed values over a
|
32 |
+
window or the global series average.
|
33 |
+
"""
|
34 |
+
|
35 |
+
def __init__(self, window_size=20, fmt=None):
|
36 |
+
if fmt is None:
|
37 |
+
fmt = "{median:.4f} ({global_avg:.4f})"
|
38 |
+
self.deque = deque(maxlen=window_size)
|
39 |
+
self.total = 0.0
|
40 |
+
self.count = 0
|
41 |
+
self.fmt = fmt
|
42 |
+
|
43 |
+
def update(self, value, n=1):
|
44 |
+
self.deque.append(value)
|
45 |
+
self.count += n
|
46 |
+
self.total += value * n
|
47 |
+
|
48 |
+
def synchronize_between_processes(self):
|
49 |
+
"""
|
50 |
+
Warning: does not synchronize the deque!
|
51 |
+
"""
|
52 |
+
if not is_dist_avail_and_initialized():
|
53 |
+
return
|
54 |
+
t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
|
55 |
+
dist.barrier()
|
56 |
+
dist.all_reduce(t)
|
57 |
+
t = t.tolist()
|
58 |
+
self.count = int(t[0])
|
59 |
+
self.total = t[1]
|
60 |
+
|
61 |
+
@property
|
62 |
+
def median(self):
|
63 |
+
d = torch.tensor(list(self.deque))
|
64 |
+
return d.median().item()
|
65 |
+
|
66 |
+
@property
|
67 |
+
def avg(self):
|
68 |
+
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
69 |
+
return d.mean().item()
|
70 |
+
|
71 |
+
@property
|
72 |
+
def global_avg(self):
|
73 |
+
return self.total / self.count
|
74 |
+
|
75 |
+
@property
|
76 |
+
def max(self):
|
77 |
+
return max(self.deque)
|
78 |
+
|
79 |
+
@property
|
80 |
+
def value(self):
|
81 |
+
return self.deque[-1]
|
82 |
+
|
83 |
+
def __str__(self):
|
84 |
+
return self.fmt.format(
|
85 |
+
median=self.median,
|
86 |
+
avg=self.avg,
|
87 |
+
global_avg=self.global_avg,
|
88 |
+
max=self.max,
|
89 |
+
value=self.value)
|
90 |
+
|
91 |
+
|
92 |
+
class MetricLogger(object):
|
93 |
+
def __init__(self, delimiter="\t"):
|
94 |
+
self.meters = defaultdict(SmoothedValue)
|
95 |
+
self.delimiter = delimiter
|
96 |
+
|
97 |
+
def update(self, **kwargs):
|
98 |
+
for k, v in kwargs.items():
|
99 |
+
if isinstance(v, torch.Tensor):
|
100 |
+
v = v.item()
|
101 |
+
assert isinstance(v, (float, int))
|
102 |
+
self.meters[k].update(v)
|
103 |
+
|
104 |
+
def __getattr__(self, attr):
|
105 |
+
if attr in self.meters:
|
106 |
+
return self.meters[attr]
|
107 |
+
if attr in self.__dict__:
|
108 |
+
return self.__dict__[attr]
|
109 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(
|
110 |
+
type(self).__name__, attr))
|
111 |
+
|
112 |
+
def __str__(self):
|
113 |
+
loss_str = []
|
114 |
+
for name, meter in self.meters.items():
|
115 |
+
loss_str.append(
|
116 |
+
"{}: {}".format(name, str(meter))
|
117 |
+
)
|
118 |
+
return self.delimiter.join(loss_str)
|
119 |
+
|
120 |
+
def global_avg(self):
|
121 |
+
loss_str = []
|
122 |
+
for name, meter in self.meters.items():
|
123 |
+
loss_str.append(
|
124 |
+
"{}: {:.4f}".format(name, meter.global_avg)
|
125 |
+
)
|
126 |
+
return self.delimiter.join(loss_str)
|
127 |
+
|
128 |
+
def synchronize_between_processes(self):
|
129 |
+
for meter in self.meters.values():
|
130 |
+
meter.synchronize_between_processes()
|
131 |
+
|
132 |
+
def add_meter(self, name, meter):
|
133 |
+
self.meters[name] = meter
|
134 |
+
|
135 |
+
def log_every(self, iterable, print_freq, header=None):
|
136 |
+
i = 0
|
137 |
+
if not header:
|
138 |
+
header = ''
|
139 |
+
start_time = time.time()
|
140 |
+
end = time.time()
|
141 |
+
iter_time = SmoothedValue(fmt='{avg:.4f}')
|
142 |
+
data_time = SmoothedValue(fmt='{avg:.4f}')
|
143 |
+
space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
|
144 |
+
log_msg = [
|
145 |
+
header,
|
146 |
+
'[{0' + space_fmt + '}/{1}]',
|
147 |
+
'eta: {eta}',
|
148 |
+
'{meters}',
|
149 |
+
'time: {time}',
|
150 |
+
'data: {data}'
|
151 |
+
]
|
152 |
+
if torch.cuda.is_available():
|
153 |
+
log_msg.append('max mem: {memory:.0f}')
|
154 |
+
log_msg = self.delimiter.join(log_msg)
|
155 |
+
MB = 1024.0 * 1024.0
|
156 |
+
for obj in iterable:
|
157 |
+
data_time.update(time.time() - end)
|
158 |
+
yield obj
|
159 |
+
iter_time.update(time.time() - end)
|
160 |
+
if i % print_freq == 0 or i == len(iterable) - 1:
|
161 |
+
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
162 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
163 |
+
if torch.cuda.is_available():
|
164 |
+
print(log_msg.format(
|
165 |
+
i, len(iterable), eta=eta_string,
|
166 |
+
meters=str(self),
|
167 |
+
time=str(iter_time), data=str(data_time),
|
168 |
+
memory=torch.cuda.max_memory_allocated() / MB))
|
169 |
+
else:
|
170 |
+
print(log_msg.format(
|
171 |
+
i, len(iterable), eta=eta_string,
|
172 |
+
meters=str(self),
|
173 |
+
time=str(iter_time), data=str(data_time)))
|
174 |
+
i += 1
|
175 |
+
end = time.time()
|
176 |
+
total_time = time.time() - start_time
|
177 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
178 |
+
print('{} Total time: {} ({:.4f} s / it)'.format(
|
179 |
+
header, total_time_str, total_time / len(iterable)))
|
180 |
+
|
181 |
+
|
182 |
+
class AttrDict(dict):
|
183 |
+
def __init__(self, *args, **kwargs):
|
184 |
+
super(AttrDict, self).__init__(*args, **kwargs)
|
185 |
+
self.__dict__ = self
|
186 |
+
|
187 |
+
|
188 |
+
def compute_acc(logits, label, reduction='mean'):
|
189 |
+
ret = (torch.argmax(logits, dim=1) == label).float()
|
190 |
+
if reduction == 'none':
|
191 |
+
return ret.detach()
|
192 |
+
elif reduction == 'mean':
|
193 |
+
return ret.mean().item()
|
194 |
+
|
195 |
+
def compute_n_params(model, return_str=True):
|
196 |
+
tot = 0
|
197 |
+
for p in model.parameters():
|
198 |
+
w = 1
|
199 |
+
for x in p.shape:
|
200 |
+
w *= x
|
201 |
+
tot += w
|
202 |
+
if return_str:
|
203 |
+
if tot >= 1e6:
|
204 |
+
return '{:.1f}M'.format(tot / 1e6)
|
205 |
+
else:
|
206 |
+
return '{:.1f}K'.format(tot / 1e3)
|
207 |
+
else:
|
208 |
+
return tot
|
209 |
+
|
210 |
+
def setup_for_distributed(is_master):
|
211 |
+
"""
|
212 |
+
This function disables printing when not in master process
|
213 |
+
"""
|
214 |
+
import builtins as __builtin__
|
215 |
+
builtin_print = __builtin__.print
|
216 |
+
|
217 |
+
def print(*args, **kwargs):
|
218 |
+
force = kwargs.pop('force', False)
|
219 |
+
if is_master or force:
|
220 |
+
builtin_print(*args, **kwargs)
|
221 |
+
|
222 |
+
__builtin__.print = print
|
223 |
+
|
224 |
+
|
225 |
+
def is_dist_avail_and_initialized():
|
226 |
+
if not dist.is_available():
|
227 |
+
return False
|
228 |
+
if not dist.is_initialized():
|
229 |
+
return False
|
230 |
+
return True
|
231 |
+
|
232 |
+
|
233 |
+
def get_world_size():
|
234 |
+
if not is_dist_avail_and_initialized():
|
235 |
+
return 1
|
236 |
+
return dist.get_world_size()
|
237 |
+
|
238 |
+
|
239 |
+
def get_rank():
|
240 |
+
if not is_dist_avail_and_initialized():
|
241 |
+
return 0
|
242 |
+
return dist.get_rank()
|
243 |
+
|
244 |
+
|
245 |
+
def is_main_process():
|
246 |
+
return get_rank() == 0
|
247 |
+
|
248 |
+
|
249 |
+
def save_on_master(*args, **kwargs):
|
250 |
+
if is_main_process():
|
251 |
+
torch.save(*args, **kwargs)
|
252 |
+
|
253 |
+
|
254 |
+
def init_distributed_mode(args):
|
255 |
+
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
|
256 |
+
args.rank = int(os.environ["RANK"])
|
257 |
+
args.world_size = int(os.environ['WORLD_SIZE'])
|
258 |
+
args.gpu = int(os.environ['LOCAL_RANK'])
|
259 |
+
elif 'SLURM_PROCID' in os.environ:
|
260 |
+
args.rank = int(os.environ['SLURM_PROCID'])
|
261 |
+
args.gpu = args.rank % torch.cuda.device_count()
|
262 |
+
else:
|
263 |
+
print('Not using distributed mode')
|
264 |
+
args.distributed = False
|
265 |
+
return
|
266 |
+
|
267 |
+
args.distributed = True
|
268 |
+
|
269 |
+
torch.cuda.set_device(args.gpu)
|
270 |
+
args.dist_backend = 'nccl'
|
271 |
+
print('| distributed init (rank {}, word {}): {}'.format(
|
272 |
+
args.rank, args.world_size, args.dist_url), flush=True)
|
273 |
+
torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
|
274 |
+
world_size=args.world_size, rank=args.rank)
|
275 |
+
torch.distributed.barrier()
|
276 |
+
setup_for_distributed(args.rank == 0)
|
277 |
+
|
278 |
+
|