forked from facebookresearch/mae
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from AlvardBarseghyan/nightowls_custom_cosine
Nightowls custom cosine
- Loading branch information
Showing
6 changed files
with
189 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,3 +6,4 @@ | |
*.jpeg | ||
*.png | ||
*.ipynb | ||
*.txt |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import os | ||
import torch | ||
from pl_train import LightningMAE | ||
|
||
from dataset import MAEDataset | ||
from torchmetrics.functional import pairwise_cosine_similarity as cos_dist | ||
|
||
import models_mae | ||
|
||
|
||
def cosine_distance_torch(x1, x2=None, eps=1e-8): | ||
x2 = x1 if x2 is None else x2 | ||
w1 = x1.norm(p=2, dim=1, keepdim=True) | ||
w2 = w1 if x2 is x1 else x2.norm(p=2, dim=1, keepdim=True) | ||
return torch.mm(x1, x2.t()) / (w1 * w2.t()) #.clamp(min=eps) | ||
|
||
|
||
BATCH_SIZE = 1 | ||
arch='mae_vit_large_patch16' | ||
model_mae = getattr(models_mae, arch)() | ||
|
||
chkpt_dir = '/mnt/2tb/alla/mae/mae_contastive/lightning_logs/version_12/checkpoints/epoch=30-step=31.ckpt' | ||
chkpt_dir_old = '/mnt/2tb/hrant/checkpoints/mae_models/mae_visualize_vit_large.pth' | ||
checkpoint = torch.load(chkpt_dir_old, map_location='cpu') | ||
msg = model_mae.load_state_dict(checkpoint['model'], strict=False) | ||
model_mae = LightningMAE.load_from_checkpoint(chkpt_dir, model=model_mae) | ||
|
||
model_mae.eval() | ||
|
||
root = '/mnt/2tb/hrant/FAIR1M/fair1m_1000/train1000/' | ||
path_ann = os.path.join(root, 'few_shot_8.json') | ||
path_imgs = os.path.join(root, 'images') | ||
dataset = MAEDataset(path_ann, path_imgs, resize_image=True) | ||
dataloader = torch.utils.data.DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=4) | ||
|
||
dl = next(iter(dataloader)) | ||
img = torch.einsum('nhwc->nchw', dl['image']) | ||
img_enc = model_mae(img.float()) | ||
img_enc = img_enc.reshape(-1, img_enc.shape[-1]) | ||
|
||
cos_torchmetrics = cos_dist(img_enc, img_enc) | ||
cos_custom = cosine_distance_torch(img_enc) | ||
|
||
print((cos_torchmetrics.reshape(-1) != cos_custom.reshape(-1)).sum()) | ||
ind = cos_torchmetrics != cos_custom | ||
print(cos_torchmetrics[ind] , cos_custom[ind]) | ||
print((cos_torchmetrics.reshape(-1).abs() - cos_custom.reshape(-1).abs()).sum()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import os | ||
from tqdm import tqdm | ||
import json | ||
from PIL import Image | ||
import pandas as pd | ||
|
||
|
||
nightowls_dir = '/home/ani/nightowls_stage_3/' | ||
|
||
def coco_dict(): | ||
coco_format = {} | ||
coco_format['images'] = [] | ||
coco_format['annotations'] = [] | ||
coco_format['categories'] = [ | ||
{ | ||
'id': 1, | ||
'name': 'pedestrian', | ||
'supercategory': 'pedestrian' | ||
}, | ||
{ | ||
'id': 2, | ||
'name': 'motorbike driver', | ||
'supercategory': 'motorbike driver' | ||
}, | ||
{ | ||
'id': 3, | ||
'name': 'motorbike driver', | ||
'supercategory': 'motorbike driver' | ||
} | ||
] | ||
|
||
return coco_format | ||
|
||
|
||
def nightowls_annotations(label_filename): | ||
annotations = pd.read_csv(label_filename, header=None, sep=' ') | ||
img_boxes = annotations.iloc[:, 1:].values # [x1, y1, x2, y2] | ||
img_labels = annotations.iloc[:, 0].values # label | ||
return img_boxes, img_labels | ||
|
||
|
||
def create_coco(path, img_dir, label_dir): | ||
image_names = os.listdir(os.path.join(path, img_dir)) # returns list of img names without absolute path | ||
image_names = [x for x in image_names if '.png' in x] | ||
max_img_size, min_img_size = -1, 100000000 | ||
nightowls_coco_format = coco_dict() | ||
|
||
for img_id, img_name in tqdm(enumerate(image_names), total=len(image_names)): | ||
img_filename = os.path.join(path, img_dir, img_name) | ||
# print(img_filename) | ||
# if '58c58167bc260130acfebf96' in img_filename: | ||
label_filename = os.path.join(path, label_dir, img_name.replace('.png', '.txt')) | ||
img = Image.open(img_filename) | ||
|
||
width, height = img.size | ||
max_img_size = max(max_img_size, height, width) | ||
min_img_size = min(min_img_size, height, width) | ||
tmp_img_dct = { | ||
'file_name': img_filename, | ||
'height': height, | ||
'width': width, | ||
'id': img_id | ||
} | ||
|
||
nightowls_coco_format['images'].append(tmp_img_dct) | ||
|
||
img_boxes, img_labels = nightowls_annotations(label_filename) | ||
|
||
bbox_id = 0 | ||
for boxes, label in zip(img_boxes, img_labels): | ||
bbox_width, bbox_height = boxes[2] - boxes[0], boxes[3] - boxes[1] | ||
# print(bbox_width, bbox_height) | ||
tmp_annotation_dct = { | ||
'image_id': img_id, | ||
'category_id': int(label), | ||
'bbox': [int(boxes[0]), int(boxes[1]), int(bbox_width), int(bbox_height)], | ||
'id': bbox_id, | ||
'iscrowd': 0, | ||
'area': int(bbox_width * bbox_height) | ||
} | ||
nightowls_coco_format['annotations'].append(tmp_annotation_dct) | ||
bbox_id += 1 | ||
|
||
return nightowls_coco_format, max_img_size, min_img_size | ||
|
||
|
||
if __name__ == "__main__": | ||
nightowls_train, max_, min_ = create_coco(nightowls_dir, './', './') | ||
|
||
with open('./annotations/few_shot_8_nightowls.json', 'w') as no: | ||
json.dump(nightowls_train, no) |