File size: 45,390 Bytes
c50dde6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 | import json
import logging
import os
import random
from dataclasses import dataclass
from multiprocessing import Value
from typing import List
import numpy as np
from training.misc import get_tokenizer
from training.utils import mask2box
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
from open_clip.transform import FixedSizeCrop, _convert_to_rgb, det_image_transform, get_scale
from pycocotools.coco import COCO
from training.coco_api import COCOPanoptic
from panopticapi import utils
from torchvision.transforms import ToTensor, Resize, CenterCrop, Compose
from pycocotools.coco import COCO as COCOAPI
import h5py
# import mmcv
import io
# from mmengine.fileio import get
try:
from petrel_client.client import Client
except:
Client = None
from open_clip.transform import ResizeLongest
class ProposalDistillDataset(Dataset):
def __init__(self, input_filename, transforms, image_root,
crop_size=224,
tokenizer=None, args=None):
logging.debug(f'Loading coco style data from {input_filename}.')
self.coco = COCO(input_filename)
logging.debug('Done loading data.')
self.transforms = transforms
self.tokenize = tokenizer
self.image_root = image_root
self.image_ids = list(self.coco.imgs.keys())
self.max_anns = 20
if not isinstance(crop_size, (tuple, list)):
crop_size = [crop_size, crop_size]
self.crop_size = crop_size
self.args = args
self.min_size = args.min_size
self.max_size = args.max_size
self.ceph_root = args.train_ceph_root
self.use_ceph = (self.ceph_root != "")
self.FILE_CLIENT = None
L = args.det_image_size//args.downsample_factor
if args.use_vfm:
if args.use_vfm == "dino-B-8": # patch 8
vfm_resolution = L * 8
elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14
vfm_resolution = L* 14
elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16
vfm_resolution = L* 16
else:
raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.")
self.vfm_transform = det_image_transform(
vfm_resolution,
is_train=False,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
else:
self.vfm_transform=None
def read_image(self, image_name):
if self.use_ceph:
image_path = os.path.join(self.ceph_root, image_name)
if self.FILE_CLIENT is None:
self.FILE_CLIENT = Client()
try:
img_bytes = self.FILE_CLIENT.get(image_path)
buff = io.BytesIO(img_bytes)
image = Image.open(buff)
except:
print(f"Cannot load {image_path}", flush=True)
return None
else:
image_path = os.path.join(self.image_root, image_name)
try:
image = Image.open(image_path)
except:
print(f"Cannot load {image_path}", flush=True)
return None
width, height = image.size
if width < 10 or height < 10:
print(f"Invalid image, size {image.size}", flush=True)
return None
return image
def __len__(self):
return len(self.image_ids)
def __getitem__(self, idx):
image_id = self.image_ids[idx]
image_info = self.coco.imgs[image_id]
if 'file_name' in image_info:
image_name = image_info['file_name']
else:
assert 'coco_url' in image_info
coco_url = image_info['coco_url'].split('/')
image_name = os.path.join(coco_url[-2], coco_url[-1])
old_image = self.read_image(image_name)
vfm_image=self.vfm_transform(old_image)
if old_image is None:
next_id = random.choice(range(self.__len__()))
return self.__getitem__(next_id)
img_w, img_h = old_image.width, old_image.height
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
anns = self.coco.imgToAnns[image_id]
boxes_template = torch.zeros(self.max_anns, 4 + 1) # xyxy s
texts=[]
image_crops = torch.zeros(self.max_anns, 3, *self.crop_size)
indices = list(range(len(anns)))
random.shuffle(indices)
num_valid_boxes = 0
for i, ann_id in enumerate(indices[:self.max_anns]):
ann = anns[ann_id]
x, y, w, h = ann['bbox']
if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2):
continue
num_valid_boxes += 1
cx, cy = x + w*0.5, y + h*0.5
x0, y0, x1, y1 = \
max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h)
image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops
box_info = torch.tensor([x, y, x + w, y + h, 1.0]) # x, y, x + w, y + h
boxes_template[i] = box_info
if num_valid_boxes == 0:
boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, 1.0]) # avoid empty
image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4)))
_, h, w = new_image.shape
boxes_template[:, :4] *= scale
boxes_template[:, [0, 2]] /= w
boxes_template[:, [1, 3]] /= h
return new_image, boxes_template, image_crops, vfm_image
class GridDistillDataset(Dataset):
def __init__(self,
input_filename,
transforms,
image_root,
max_split=16,
crop_size=224,
pre_transforms=False,
ceph_root="",
args=None):
if os.path.basename(input_filename) in ['lvis_v1_train.json', 'instances_train2017.json']:
# coco style distillation
logging.debug(f'Loading coco style data from {input_filename}.')
self.coco = COCO(input_filename)
logging.debug('Done loading data.')
image_ids = list(self.coco.imgs.keys())
self.style="coco"
if args.use_knn:
with open(args.use_knn, "r") as f:
self.knn = json.load(f)
else:
self.knn=False
elif os.path.basename(input_filename) in ['chat.json','mixed_data.json','llava_v1_5_mix624k.json']:
# llava style distillation
with open(input_filename, 'r') as file:
data = json.load(file)
image_ids = [item["image"] for item in data]
self.style="llava"
else:
raise ValueError(f"Unsupported file format or style for {input_filename}.")
self._init_choices(max_split)
self.transforms = transforms
self.image_root = image_root
self.args = args
train_ratio = args.train_ratio
if train_ratio < 1.0:
num_images = int(len(image_ids) * train_ratio)
random.shuffle(image_ids)
image_ids = image_ids[:num_images]
self.image_ids = image_ids
self.max_anns = args.max_boxes
if not isinstance(crop_size, (tuple, list)):
crop_size = [crop_size, crop_size]
self.crop_size = crop_size
self._init_boxes()
self.ceph_root = ceph_root
self.use_ceph = (ceph_root != "")
self.FILE_CLIENT = None
L = args.det_image_size//args.downsample_factor
if args.use_vfm:
if args.use_vfm == "dino-B-8": # patch 8
vfm_resolution = L * 8
elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14
vfm_resolution = L* 14
elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16
vfm_resolution = L* 16
else:
raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.")
self.vfm_transform = det_image_transform(
vfm_resolution,
is_train=False,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
else:
self.vfm_transform=None
if args.use_vfm in ["sd_dino"]:
self.sd_transform = Compose([ResizeLongest(args.det_image_size),
_convert_to_rgb,
ToTensor(),])
else:
self.sd_transform=None
def read_image(self, image_name):
if self.use_ceph:
image_path = os.path.join(self.ceph_root, image_name)
if self.FILE_CLIENT is None:
self.FILE_CLIENT = Client()
try:
img_bytes = self.FILE_CLIENT.get(image_path)
buff = io.BytesIO(img_bytes)
image = Image.open(buff)
except:
print(f"Cannot load {image_path}", flush=True)
return None
else:
image_path = os.path.join(self.image_root, image_name)
try:
image = Image.open(image_path)
except:
print(f"Cannot load {image_path}", flush=True)
return None
width, height = image.size
if width < 10 or height < 10:
print(f"Invalid image, size {image.size}", flush=True)
return None
return image
def _init_choices(self, M=16):
choices = []
for m in range(1, M+1):
for n in range((m + 1)//2, min(m*2 + 1, M+1)):
choices.append((m, n))
self.choices = choices
def __len__(self):
return len(self.image_ids)
def _init_boxes(self, ):
box_templates = {}
for choice in self.choices:
M, N = choice
grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1),
indexing='xy')
x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1)
x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1)
pseudo_boxes = torch.cat([x0y0s, x1y1s],dim=-1).view(-1, 4)
assert pseudo_boxes.shape[0] == M*N
box_templates[choice] = pseudo_boxes
self.box_templates = box_templates
def _obtain_image_crops(self, image, choice):
image_crops = []
img_w, img_h = image.size
normed_boxes = self.box_templates[choice]
indices = list(range(len(normed_boxes)))
random.shuffle(indices)
indices = indices[:self.max_anns]
boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h])
for idx in indices:
box = boxes[idx]
x0, y0, x1, y1 = box.tolist() # todo expand
if self.args.crop_scale > 1.0:
box_w, box_h = x1 - x0, y1 - y0
cx, cy = (x1 + x0)/2, (y1 + y0)/2
delta_factor = 0.5 * self.args.crop_scale
x0, y0, x1, y1 = max(cx - box_w * delta_factor, 0), max(cy - box_h * delta_factor, 0), \
min(cx + box_w * delta_factor, img_w), min(cy + box_h * delta_factor, img_h)
vanilla_view=self.transforms[1](image.crop((x0, y0, x1, y1)))
image_crops.append(vanilla_view)
return torch.stack(image_crops), boxes[indices]
def _load_target(self, id: int):
return self.coco.loadAnns(self.coco.getAnnIds(id))
def precess_knn_images(self,image_id):
knn_image_ids = self.knn[str(image_id)]
selected_knn_image_id = random.choice(knn_image_ids)
image_info = self.coco.imgs[selected_knn_image_id]
if 'file_name' in image_info:
image_name = image_info['file_name']
else:
assert 'coco_url' in image_info
coco_url = image_info['coco_url'].split('/')
image_name = os.path.join(coco_url[-2], coco_url[-1])
knn_image=self.read_image(image_name)
knn_image_vfm =self.vfm_transform(knn_image)
knn_image_clip = self.transforms[0](knn_image)
return knn_image_vfm, knn_image_clip
def __getitem__(self, idx):
image_id = self.image_ids[idx]
if self.style=="coco":
image_info = self.coco.imgs[image_id]
if 'file_name' in image_info:
image_name = image_info['file_name']
else:
assert 'coco_url' in image_info
coco_url = image_info['coco_url'].split('/')
image_name = os.path.join(coco_url[-2], coco_url[-1])
else:
image_name=image_id
old_image = self.read_image(image_name)
if self.vfm_transform:
vfm_image=self.vfm_transform(old_image)
else:
vfm_image = torch.empty(0)
if self.sd_transform:
sd_image = self.sd_transform(old_image)
else:
sd_image = torch.empty(0)
if old_image is None:
next_id = random.choice(range(self.__len__()))
return self.__getitem__(next_id)
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
boxes_template = torch.zeros(self.max_anns, 4 + 1)
image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size)
image_crops, boxes = self._obtain_image_crops(old_image,random.choice(self.choices))
assert image_crops.shape[0] == boxes.shape[0]
_, h, w = new_image.shape
boxes[:, :4] *= scale
boxes[:, [0, 2]] /= w
boxes[:, [1, 3]] /= h
boxes_template[:boxes.shape[0], :4] = boxes
boxes_template[:boxes.shape[0], 4] = 1.0
image_crops_template[:boxes.shape[0]] = image_crops
if self.knn:
knn_image_vfm, knn_image_clip=self.precess_knn_images(image_id)
if self.sd_transform is not None:
return new_image, boxes_template, image_crops_template, vfm_image, sd_image, knn_image_vfm, knn_image_clip
else:
return new_image, boxes_template, image_crops_template, vfm_image, knn_image_vfm, knn_image_clip
if self.args.precompute_knn:
return new_image, boxes_template, image_crops_template, vfm_image, image_id
if self.sd_transform is not None:
return new_image, boxes_template, image_crops_template, vfm_image, sd_image
else:
return new_image, boxes_template, image_crops_template, vfm_image
class DiFTProposalDistillDataset(Dataset):
def __init__(self, input_filename, transforms, image_root,
crop_size=224,
tokenizer=None, args=None):
logging.debug(f'Loading coco style data from {input_filename}.')
self.coco = COCO(input_filename)
logging.debug('Done loading data.')
self.transforms = transforms
self.tokenize = tokenizer
self.image_root = image_root
self.image_ids = list(self.coco.imgs.keys())
self.max_anns = 20
self.cache_path = args.cache_self_attn
self.cache = None
if not isinstance(crop_size, (tuple, list)):
crop_size = [crop_size, crop_size]
self.crop_size = crop_size
self.args = args
self.min_size = args.min_size
self.max_size = args.max_size
self.ceph_root = args.train_ceph_root
self.use_ceph = (self.ceph_root != "")
self.FILE_CLIENT = None
L = args.det_image_size//args.downsample_factor
if args.use_vfm:
if args.use_vfm == "dino-B-8": # patch 8
vfm_resolution = L * 8
elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14
vfm_resolution = L* 14
elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16
vfm_resolution = L* 16
else:
raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.")
self.vfm_transform = det_image_transform(
vfm_resolution,
is_train=False,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
else:
self.vfm_transform=None
def read_image(self, image_name):
if self.use_ceph:
image_path = os.path.join(self.ceph_root, image_name)
if self.FILE_CLIENT is None:
self.FILE_CLIENT = Client()
try:
img_bytes = self.FILE_CLIENT.get(image_path)
buff = io.BytesIO(img_bytes)
image = Image.open(buff)
except:
print(f"Cannot load {image_path}", flush=True)
return None
else:
image_path = os.path.join(self.image_root, image_name)
try:
image = Image.open(image_path)
except:
print(f"Cannot load {image_path}", flush=True)
return None
width, height = image.size
if width < 10 or height < 10:
print(f"Invalid image, size {image.size}", flush=True)
return None
return image
def __len__(self):
return len(self.image_ids)
def _lazy_open_cache(self):
if self.cache is None:
self.cache = h5py.File(self.cache_path, 'r', swmr=True)
def __getitem__(self, idx):
image_id = self.image_ids[idx]
image_info = self.coco.imgs[image_id]
if 'file_name' in image_info:
image_name = image_info['file_name']
else:
assert 'coco_url' in image_info
coco_url = image_info['coco_url'].split('/')
image_name = os.path.join(coco_url[-2], coco_url[-1])
old_image = self.read_image(image_name)
vfm_image=self.vfm_transform(old_image)
if old_image is None:
next_id = random.choice(range(self.__len__()))
return self.__getitem__(next_id)
img_w, img_h = old_image.width, old_image.height
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
anns = self.coco.imgToAnns[image_id]
boxes_template = torch.zeros(self.max_anns, 4 + 1) # xyxy s
texts=[]
image_crops = torch.zeros(self.max_anns, 3, *self.crop_size)
indices = list(range(len(anns)))
random.shuffle(indices)
num_valid_boxes = 0
for i, ann_id in enumerate(indices[:self.max_anns]):
ann = anns[ann_id]
x, y, w, h = ann['bbox']
if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2):
continue
num_valid_boxes += 1
cx, cy = x + w*0.5, y + h*0.5
x0, y0, x1, y1 = \
max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h)
image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops
box_info = torch.tensor([x, y, x + w, y + h, 1.0]) # x, y, x + w, y + h
boxes_template[i] = box_info
if num_valid_boxes == 0:
boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, 1.0]) # avoid empty
image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4)))
_, h, w = new_image.shape
boxes_template[:, :4] *= scale
boxes_template[:, [0, 2]] /= w
boxes_template[:, [1, 3]] /= h
self._lazy_open_cache()
key = os.path.basename(image_name)
sd_self_attn = torch.from_numpy(self.cache[key][()])
return new_image, boxes_template, image_crops, vfm_image,sd_self_attn
class DiFTGridDistillDataset(Dataset):
def __init__(self,
input_filename,
transforms,
image_root,
max_split=16,
crop_size=224,
args=None):
self.coco = COCO(input_filename)
logging.info('Done loading data.')
self._init_choices(max_split)
self.transforms = transforms
self.image_root = image_root
self.args = args
self.image_ids = list(self.coco.imgs.keys())
self.max_anns = args.max_boxes
self.cache_path = args.cache_self_attn
self.cache = None
if not isinstance(crop_size, (tuple, list)):
crop_size = [crop_size, crop_size]
self.crop_size = crop_size
self._init_boxes()
L = args.det_image_size//args.downsample_factor
if args.use_vfm:
if args.use_vfm == "dino-B-8": # patch 8
vfm_resolution = L * 8
elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14
vfm_resolution = L* 14
elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16
vfm_resolution = L* 16
else:
raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.")
self.vfm_transform = det_image_transform(
vfm_resolution,
is_train=False,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
else:
self.vfm_transform=None
def read_image(self, image_name):
image_path = os.path.join(self.image_root, image_name)
try:
image = Image.open(image_path)
except:
print(f"Cannot load {image_path}", flush=True)
return None
width, height = image.size
if width < 10 or height < 10:
print(f"Invalid image, size {image.size}", flush=True)
return None
return image
def _lazy_open_cache(self):
if self.cache is None:
self.cache = h5py.File(self.cache_path, 'r', swmr=True)
def _init_choices(self, M=16):
choices = []
for m in range(1, M+1):
for n in range((m + 1)//2, min(m*2 + 1, M+1)):
choices.append((m, n))
self.choices = choices
def __len__(self):
return len(self.image_ids)
def _init_boxes(self, ):
box_templates = {}
for choice in self.choices:
M, N = choice
grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1),
indexing='xy')
x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1)
x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1)
pseudo_boxes = torch.cat([x0y0s, x1y1s],dim=-1).view(-1, 4)
assert pseudo_boxes.shape[0] == M*N
box_templates[choice] = pseudo_boxes
self.box_templates = box_templates
def _obtain_image_crops(self, image, choice):
image_crops = []
img_w, img_h = image.size
normed_boxes = self.box_templates[choice]
indices = list(range(len(normed_boxes)))
random.shuffle(indices)
indices = indices[:self.max_anns]
boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h])
for idx in indices:
box = boxes[idx]
x0, y0, x1, y1 = box.tolist() # todo expand
if self.args.crop_scale > 1.0:
box_w, box_h = x1 - x0, y1 - y0
cx, cy = (x1 + x0)/2, (y1 + y0)/2
delta_factor = 0.5 * self.args.crop_scale
x0, y0, x1, y1 = max(cx - box_w * delta_factor, 0), max(cy - box_h * delta_factor, 0), \
min(cx + box_w * delta_factor, img_w), min(cy + box_h * delta_factor, img_h)
vanilla_view=self.transforms[1](image.crop((x0, y0, x1, y1)))
image_crops.append(vanilla_view)
return torch.stack(image_crops), boxes[indices]
def _load_target(self, id: int):
return self.coco.loadAnns(self.coco.getAnnIds(id))
def __getitem__(self, idx):
image_id = self.image_ids[idx]
image_info = self.coco.imgs[image_id]
if 'file_name' in image_info:
image_name = image_info['file_name']
else:
assert 'coco_url' in image_info
coco_url = image_info['coco_url'].split('/')
image_name = os.path.join(coco_url[-2], coco_url[-1])
old_image = self.read_image(image_name)
if self.vfm_transform:
vfm_image=self.vfm_transform(old_image)
else:
vfm_image = torch.empty(0)
if old_image is None:
next_id = random.choice(range(self.__len__()))
return self.__getitem__(next_id)
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
boxes_template = torch.zeros(self.max_anns, 4 + 1)
image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size)
image_crops, boxes = self._obtain_image_crops(old_image,random.choice(self.choices))
assert image_crops.shape[0] == boxes.shape[0]
_, h, w = new_image.shape
boxes[:, :4] *= scale
boxes[:, [0, 2]] /= w
boxes[:, [1, 3]] /= h
boxes_template[:boxes.shape[0], :4] = boxes
boxes_template[:boxes.shape[0], 4] = 1.0
image_crops_template[:boxes.shape[0]] = image_crops
self._lazy_open_cache()
key = os.path.basename(image_name)
sd_self_attn = torch.from_numpy(self.cache[key][()])
return new_image, boxes_template, image_crops_template, vfm_image,sd_self_attn
class COCOPanopticDataset(Dataset):
def __init__(self, input_filename, transforms, image_root, embed_path,
segm_root,
crop_size=224,
tokenizer=None,
downsample_factor=16,
min_size=8,
max_size=1024,
args=None):
logging.debug(f'Loading coco caption style data from {input_filename}.')
self.coco = COCOPanoptic(input_filename)
logging.debug('Done loading data.')
self.transforms = transforms
self.tokenize = tokenizer
self.image_root = image_root
self.embeddings = np.load(embed_path)
self.image_ids = list(self.coco.imgs.keys())
num_annos = [len(anns) for anns in self.coco.imgToAnns.values()]
self.max_anns = min(max(num_annos), 100)
if not isinstance(crop_size, (tuple, list)):
crop_size = [crop_size, crop_size]
self.crop_size = crop_size
self.min_size = 8 # fix for val
self.max_size = 1024
self.segm_root = segm_root
self.downsample_factor = downsample_factor
self.segm_transform = ResizeLongest(max_size=self.transforms[0].transforms[0].max_size // downsample_factor,
fill=0) # downsample to the output size of image encoder
self.args=args
cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()])
self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)}
self.label2cat_id = {label: cat_id for cat_id, label in self.cat_id2label.items()}
def __len__(self):
return len(self.image_ids)
@staticmethod
def _load_segm(segm_path):
segmentation = np.array(
Image.open(segm_path),
dtype=np.uint8
)
# img_bytes = get(segm_path)
# pan_png = mmcv.imfrombytes(
# img_bytes, flag='color', channel_order='rgb').squeeze()
segm_map = utils.rgb2id(segmentation)
return segm_map
def __getitem__(self, idx):
image_id = self.image_ids[idx]
image_info = self.coco.imgs[image_id]
image_name = image_info['file_name']
segm_file = image_info['segm_file']
image_path = os.path.join(self.image_root, image_name)
segm_path = os.path.join(self.segm_root, segm_file)
segm_map = self._load_segm(segm_path)
old_image = Image.open(image_path)
img_w, img_h = old_image.width, old_image.height
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
anns = self.coco.imgToAnns[image_id]
boxes_template = torch.zeros(self.max_anns, 4 + 2 + 1 + 1) # xyxy c valid size, isthing
image_crops = torch.zeros(self.max_anns, 3, *self.crop_size)
gt_masks = torch.zeros(self.max_anns, self.segm_transform.max_size,self.segm_transform.max_size)
masked_image_crops = torch.zeros(self.max_anns, 3, *self.crop_size)
for i, ann in enumerate(anns):
if i == self.max_anns:
break
cat_id = ann['category_id']
is_thing = self.coco.cats[cat_id]['isthing']
if is_thing > 0:
x, y, w, h = ann['bbox']
cx, cy = x + w*0.5, y + h*0.5
x0, y0, x1, y1 = \
max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h)
else:
x0, y0, x1, y1 = mask2box(segm_map == ann['id'])
x, y, w, h = x0, y0, x1 - x0, y1 - y0
if w * h < (self.min_size ** 2) or w * h > (self.max_size ** 2):
continue
image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops
# masked image crop
np_old_image = np.array(old_image)
np_old_image[segm_map != ann['id']] = 114
masked_old_image = Image.fromarray(np_old_image)
masked_image_crops[i] = self.transforms[1](masked_old_image.crop((x0, y0, x1, y1))) # image crops
gt_mask = torch.from_numpy(segm_map == ann['id']).float()
gt_mask = self.segm_transform(gt_mask[None]) > 0.0
cls_label = self.cat_id2label[cat_id]
box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0, w * h, is_thing]) # x, y, x + w, y + h
boxes_template[i] = box_info
gt_masks[i] = gt_mask[0]
_, h, w = new_image.shape
boxes_template[:, :4] *= scale
boxes_template[:, [0, 2]] /= w
boxes_template[:, [1, 3]] /= h
return image_name, new_image, boxes_template, image_crops, gt_masks, masked_image_crops
class COCORegionCLIPDataset(Dataset):
def __init__(self, input_filename, transforms, image_root, args):
logging.debug(f'Loading coco caption style data from {input_filename}.')
self.coco = COCO(input_filename)
logging.debug('Done loading data.')
self.transforms = transforms
self.image_root = image_root
image_ids = list(self.coco.imgToAnns.keys()) # only use images that have anns
train_ratio = args.train_ratio
if train_ratio < 1.0:
num_images = int(len(image_ids) * train_ratio)
random.shuffle(image_ids)
image_ids = image_ids[:num_images]
self.image_ids = image_ids
num_annos = [len(anns) for anns in self.coco.imgToAnns.values()]
self.max_anns = min(max(num_annos), 20)
self.args = args
self.ceph_root = args.train_ceph_root
self.use_ceph = (self.ceph_root != "")
self.FILE_CLIENT = None
cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()])
self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)}
def __len__(self):
return len(self.image_ids)
def read_image(self, image_name):
if self.use_ceph:
image_path = os.path.join(self.ceph_root, image_name)
if self.FILE_CLIENT is None:
self.FILE_CLIENT = Client()
img_bytes = self.FILE_CLIENT.get(image_path)
buff = io.BytesIO(img_bytes)
image = Image.open(buff)
else:
image_path = os.path.join(self.image_root, image_name)
image = Image.open(image_path)
return image
def __getitem__(self, idx):
image_id = self.image_ids[idx]
image_info = self.coco.imgs[image_id]
image_name = image_info['file_name']
# image_path = os.path.join(self.image_root, image_name)
# old_image = Image.open(image_path)
old_image = self.read_image(image_name)
new_image = self.transforms[0](old_image)
scale = get_scale(old_image, new_image)
anns = self.coco.imgToAnns[image_id]
boxes_template = torch.zeros(self.max_anns, 4 + 2) # xyxy cls valid
for i, ann in enumerate(anns):
if i == self.max_anns:
break
cat_id = ann['category_id']
x, y, w, h = ann['bbox']
cls_label = self.cat_id2label[cat_id]
box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0]) # x, y, x + w, y + h
boxes_template[i] = box_info
_, h, w = new_image.shape
boxes_template[:, :4] *= scale
boxes_template[:, [0, 2]] /= w
boxes_template[:, [1, 3]] /= h
return new_image, boxes_template
class COCOCaptionDataset(Dataset):
def __init__(self, input_filename, transforms, image_root,
tokenizer=None, args=None):
logging.debug(f'Loading coco caption style data from {input_filename}.')
with open(input_filename, 'r') as f:
self.images = json.load(f)['images']
logging.debug('Done loading data.')
self.transforms = transforms
self.tokenize = get_tokenizer(args.model)
self.image_root = image_root
self.ceph_root = args.train_ceph_root
self.use_ceph = (self.ceph_root != "")
self.FILE_CLIENT = None
def read_image(self, image_name):
if self.use_ceph:
image_path = os.path.join(self.ceph_root, image_name)
if self.FILE_CLIENT is None:
self.FILE_CLIENT = Client()
try:
img_bytes = self.FILE_CLIENT.get(image_path)
buff = io.BytesIO(img_bytes)
image = Image.open(buff)
except:
print(f"Cannot load {image_path}", flush=True)
return None
else:
image_path = os.path.join(self.image_root, image_name)
try:
image = Image.open(image_path)
except:
print(f"Cannot load {image_path}", flush=True)
return None
width, height = image.size
if width < 10 or height < 10:
print(f"Invalid image, size {image.size}", flush=True)
return None
return image
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
image_info = self.images[idx]
text = random.choice(image_info['captions'])
image_name = image_info['file_name']
image = self.read_image(image_name)
if image is None:
next_id = random.choice(range(self.__len__()))
return self.__getitem__(next_id)
image = self.transforms(image)
text = self.tokenize([text])[0]
return image, text
def get_coco_panoptic_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
input_filename = args.train_data if is_train else args.val_data
if args.image_crop_size>0 :
image_crop_size=args.image_crop_size
else:
if args.model=="EVA02-CLIP-B-16" or args.model=="ViT-B-16" or args.model=="ViT-L-14" or "Tiny" in args.model:
image_crop_size=224
elif args.model=="siglip-so400m-patch14-384":
image_crop_size=384
else:
image_crop_size=336 # ViT-L-14-336 & EVA02-CLIP-L-14-336
assert input_filename
dataset = COCOPanopticDataset(
input_filename,
preprocess_fn,
segm_root=args.val_segm_root,
image_root=args.val_image_root,
embed_path=args.embed_path,
tokenizer=tokenizer,
crop_size=image_crop_size,
min_size=args.min_size,
max_size=args.max_size,
downsample_factor=args.downsample_factor,
args=args,
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
if is_train:
batch_size = args.batch_size
else:
batch_size = min(args.batch_size, 1) # only support bs = 1 for inference
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_proposal_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data # if is_train else args.val_data
assert input_filename
dataset = ProposalDistillDataset(
input_filename,
preprocess_fn,
image_root=args.train_image_root,
tokenizer=tokenizer,
crop_size=args.input_size,
args=args
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
batch_size = args.batch_size
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_grid_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data
assert input_filename
dataset = GridDistillDataset(
input_filename=input_filename,
transforms=preprocess_fn,
image_root=args.train_image_root,
crop_size=args.input_size,
max_split=args.max_split,
ceph_root=args.train_ceph_root,
pre_transforms=args.pre_transforms,
args=args
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
batch_size = args.batch_size
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_dift_grid_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data
assert input_filename
dataset = DiFTGridDistillDataset(
input_filename=input_filename,
transforms=preprocess_fn,
image_root=args.train_image_root,
crop_size=args.input_size,
max_split=args.max_split,
args=args
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
batch_size = args.batch_size
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_region_clip_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data
assert input_filename
dataset = COCORegionCLIPDataset(
input_filename=input_filename,
transforms=preprocess_fn,
image_root=args.train_image_root,
args=args,
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
batch_size = args.batch_size
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_coco_caption_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data
assert input_filename
dataset = COCOCaptionDataset(
input_filename,
preprocess_fn,
image_root=args.train_image_root,
tokenizer=tokenizer,
args=args
)
num_samples = len(dataset)
sampler = DistributedSampler(dataset) if args.distributed and is_train else None
shuffle = is_train and sampler is None
dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_dift_proposal_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None):
assert is_train
input_filename = args.train_data # if is_train else args.val_data
assert input_filename
dataset = DiFTProposalDistillDataset(
input_filename,
preprocess_fn,
image_root=args.train_image_root,
tokenizer=tokenizer,
crop_size=args.input_size,
args=args
)
num_samples = len(dataset)
# TODO: distributed for test
sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None
shuffle = is_train and sampler is None
batch_size = args.batch_size
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
class SharedEpoch:
def __init__(self, epoch: int = 0):
self.shared_epoch = Value('i', epoch)
def set_value(self, epoch):
self.shared_epoch.value = epoch
def get_value(self):
return self.shared_epoch.value
@dataclass
class DataInfo:
dataloader: DataLoader
sampler: DistributedSampler = None
shared_epoch: SharedEpoch = None
def set_epoch(self, epoch):
if self.shared_epoch is not None:
self.shared_epoch.set_value(epoch)
if self.sampler is not None and isinstance(self.sampler, DistributedSampler):
self.sampler.set_epoch(epoch)
def get_dataset_fn(data_path, dataset_type):
if dataset_type == 'coco_panoptic':
return get_coco_panoptic_dataset
elif dataset_type == 'proposals_distill':
return get_proposal_distill_dataset
elif dataset_type == 'grid_distill':
return get_grid_distill_dataset
elif dataset_type == 'dift_grid_distill':
return get_dift_grid_distill_dataset
elif dataset_type == 'dift_proposals_distill':
return get_dift_proposal_distill_dataset
elif dataset_type == 'region_clip':
return get_region_clip_dataset
elif dataset_type == 'coco_caption':
return get_coco_caption_dataset
elif dataset_type == 'ablation_sam':
from training.data_ablation import get_ablation_sam_dataset
return get_ablation_sam_dataset
elif dataset_type == 'ablation_ijepa':
from training.data_ablation import get_ablation_ijepa_dataset
return get_ablation_ijepa_dataset
else:
raise ValueError(f"Unsupported dataset type: {dataset_type}")
def get_data(args, preprocess_fns, epoch=0, tokenizer=None):
preprocess_train, preprocess_val = preprocess_fns
data = {}
if args.train_data:
data["train"] = get_dataset_fn(args.train_data, args.dataset_type)(
args, preprocess_train, is_train=True, epoch=epoch, tokenizer=tokenizer)
if args.val_data:
data["val"] = get_dataset_fn(args.val_data, dataset_type=args.test_type)(
args, preprocess_val, is_train=False, tokenizer=tokenizer)
return data
class SDNormalize(object):
def __call__(self, img):
return 2.0 * img - 1.0 |