File size: 13,650 Bytes
32b542e |
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 |
import os
import copy
import pickle
from PIL import Image
import torch
from torchvision import transforms
import random
from torchvision.transforms.transforms import ToTensor
from tqdm import tqdm
import numpy as np
from uniperceiver.config import configurable
from uniperceiver.functional import read_np, dict_as_tensor, boxes_to_locfeats
from ..build import DATASETS_REGISTRY
import glob
import json
from collections import defaultdict
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
import pyarrow as pa
from uniperceiver.utils import comm
__all__ = ["ImageNetDataset", "ImageNet22KDataset"]
def load_pkl_file(filepath):
return pickle.load(open(filepath, 'rb'), encoding='bytes') if len(filepath) > 0 else None
@DATASETS_REGISTRY.register()
class ImageNetDataset:
@configurable
def __init__(
self,
stage: str,
anno_file: str,
s3_path: str,
feats_folder: str,
class_names: list,
use_ceph: bool,
tcs_conf_path,
data_percentage,
task_info,
target_set,
cfg,
):
self.stage = stage
self.ann_file = anno_file
self.feats_folder = feats_folder
self.class_names = class_names if (class_names is not None) else None
self.data_percentage = data_percentage
self.initialized = False
self.cfg = cfg
self.task_info = task_info
self.target_set = target_set
# for index_maping
self.idx2info = dict()
self.use_ceph = use_ceph
if self.use_ceph:
self.feats_folder = s3_path
print('debug info for imagenet{} {}'.format(self.ann_file, self.feats_folder))
from uniperceiver.datasets import TCSLoader
self.tcs_loader = TCSLoader(tcs_conf_path)
self.transform = build_transform(is_train=(self.stage == 'train'),
input_size=cfg.MODEL.IMG_INPUT_SIZE)
_temp_list =self.load_data(self.cfg)
self.datalist = pa.array(_temp_list)
if comm.is_main_process():
import sys
print("ImageNet1K Pretrain Dataset:")
print('!!! length of _temp_list: ', len(_temp_list))
print('!!! size of _temp_list: ', sys.getsizeof(_temp_list))
print('!!! size of pa database: ', sys.getsizeof(self.datalist))
del _temp_list
@classmethod
def from_config(cls, cfg, stage: str = "train"):
if 'SLURM_PROCID' in os.environ:
tcs_conf_path = cfg.DATALOADER.get("TCS_CONF_PATH", "slurm_tools/petreloss.config")
else:
# dev machine
tcs_conf_path = "slurm_tools/petreloss_local.config"
ann_files = {
"train": os.path.join(cfg.DATALOADER.ANNO_FOLDER, "train.txt"),
"val": os.path.join(cfg.DATALOADER.ANNO_FOLDER, "val.txt"),
"test": os.path.join(cfg.DATALOADER.ANNO_FOLDER, "test.txt")
}
task_info = {
'task_type' : cfg.DATASETS.TASK_TYPE,
'dataset_name' : cfg.DATASETS.DATASET_NAME,
'batch_size' : cfg.DATALOADER.TRAIN_BATCH_SIZE if stage == 'train' else cfg.DATALOADER.TEST_BATCH_SIZE,
'sampling_weight': cfg.DATALOADER.SAMPLING_WEIGHT
}
ret = {
"cfg" : cfg,
"stage" : stage,
"anno_file" : ann_files[stage],
"feats_folder" : cfg.DATALOADER.FEATS_FOLDER,
's3_path' : cfg.DATALOADER.S3_PATH,
"class_names" : load_pkl_file(cfg.DATALOADER.CLASS_NAME_FILE) if cfg.DATALOADER.CLASS_NAME_FILE else None,
"use_ceph" : getattr(cfg.DATALOADER, 'USE_CEPH', False),
"tcs_conf_path" : tcs_conf_path,
"data_percentage": cfg.DATALOADER.DATA_PERCENTAGE,
"task_info" : task_info,
"target_set" : cfg.DATASETS.TARGET_SET
}
return ret
def _preprocess_datalist(self, datalist):
return datalist
def load_data(self, cfg):
datalist = []
# local file reading
with open(self.ann_file, 'r') as f:
img_infos = f.readlines()
if self.stage == "train" and self.data_percentage < 1.0:
id2img = dict()
for idx, l in enumerate(img_infos):
name = int(l.replace('\n', '').split(' ')[1])
if name not in id2img:
id2img[name] = list()
id2img[name].append(idx)
self.idx2info[idx] = l.replace('\n', '').split(' ')[0]
datalist = list()
for k, v in id2img.items():
for idx in random.sample(v, k=int(len(v)*self.data_percentage)+1):
datalist.append({
'image_id': idx,
'class_id': k,
"file_path": self.idx2info[idx],
})
else:
datalist = [{
'image_id': idx,
'class_id': int(l.replace('\n', '').split(' ')[1]),
"file_path": l.replace('\n', '').split(' ')[0],
} for idx, l in enumerate(img_infos)]
datalist = self._preprocess_datalist(datalist)
return datalist
def __len__(self):
return len(self.datalist)
def __getitem__(self, index):
for i_try in range(100):
try:
dataset_dict =self.datalist[index].as_py()
image_id = dataset_dict['image_id']
class_id = dataset_dict['class_id']
image_name = dataset_dict['file_path']
# load image
image_path = os.path.join(self.feats_folder, self.stage, image_name)
if self.use_ceph:
img = self.tcs_loader(image_path).convert('RGB')
else:
img = Image.open(image_path).convert("RGB")
except Exception as e:
print(
"Failed to load image from {} with error {} ; trial {}".format(
image_path, e, i_try
)
)
# let's try another one
index = random.randint(0, len(self.datalist) - 1)
continue
img = self.transform(img)
ret = {
'input_sample' : [{
'data' : img,
'invalid_mask': None,
'modality' : 'image',
'data_type': 'input',
'sample_info' : {
'id' : image_id,
'path': image_path
}
}],
'target_sample': [],
'target_idx' : [class_id],
'target_set' : copy.deepcopy(self.target_set),
'task_info' : copy.deepcopy(self.task_info)
}
return ret
@DATASETS_REGISTRY.register()
class ImageNet22KDataset:
@configurable
def __init__(
self,
stage: str,
anno_file: str,
s3_path: str,
feats_folder: str,
use_ceph: bool,
tcs_conf_path: str,
cfg: str,
task_info,
target_set,
):
self.cfg = cfg
self.stage = stage
self.ann_file = anno_file
self.feats_folder = feats_folder
self.task_info = task_info
self.target_set = target_set
self.initialized = False
self.use_ceph = use_ceph
if self.use_ceph:
self.feats_folder = s3_path
print('debug info for imagenet22k {} {}'.format(self.ann_file, self.feats_folder))
from uniperceiver.datasets import TCSLoader
self.tcs_loader = TCSLoader(tcs_conf_path)
self.transform = build_transform(is_train=(self.stage == 'train'),
input_size=cfg.MODEL.IMG_INPUT_SIZE)
_temp_list = self.load_data(self.cfg)
self.datalist = pa.array(_temp_list)
if comm.is_main_process():
import sys
print("ImageNet22K Pretrain Dataset:")
print('!!! length of _temp_list: ', len(_temp_list))
print('!!! size of _temp_list: ', sys.getsizeof(_temp_list))
print('!!! size of pa database: ', sys.getsizeof(self.datalist))
del _temp_list
@classmethod
def from_config(cls, cfg, stage: str = "train"):
ann_files = {
"train": os.path.join(cfg.DATALOADER.ANNO_FOLDER, "imagenet_22k_filelist_short.txt"),
"val": os.path.join(cfg.DATALOADER.ANNO_FOLDER, "imagenet_22k_filelist_short.txt"),
}
if 'SLURM_PROCID' in os.environ:
tcs_conf_path = cfg.DATALOADER.get("TCS_CONF_PATH", "slurm_tools/petreloss.config")
else:
# dev machine
tcs_conf_path = "slurm_tools/petreloss_local.config"
task_info = {
'task_type' : cfg.DATASETS.TASK_TYPE,
'dataset_name' : cfg.DATASETS.DATASET_NAME,
'batch_size' : cfg.DATALOADER.TRAIN_BATCH_SIZE if stage == 'train' else cfg.DATALOADER.TEST_BATCH_SIZE,
'sampling_weight': cfg.DATALOADER.SAMPLING_WEIGHT
}
ret = {
"cfg" : cfg,
"stage" : stage,
"anno_file" : ann_files[stage],
's3_path' : cfg.DATALOADER.S3_PATH,
"feats_folder" : cfg.DATALOADER.FEATS_FOLDER,
"use_ceph" : getattr(cfg.DATALOADER, 'USE_CEPH', False),
"tcs_conf_path": tcs_conf_path,
"task_info" : task_info,
"target_set" : cfg.DATASETS.TARGET_SET
}
return ret
def _preprocess_datalist(self, datalist):
return datalist
def load_data(self, cfg):
datalist = []
# local file reading
with open(self.ann_file, 'r') as f:
img_infos = f.readlines()
datalist = []
for idx, l in enumerate(img_infos):
info_strip = l.replace('\n', '').split(' ')
wn_id = info_strip[0]
class_id = info_strip[2]
file_path = wn_id + '/' + wn_id + '_' + info_strip[1] + '.JPEG' # n01440764/n01440764_10074.JPEG
datalist.append(
{
'image_id': idx,
'file_path': file_path,
'class_id': int(class_id)
}
)
datalist = self._preprocess_datalist(datalist)
return datalist
def __len__(self):
return len(self.datalist)
def __getitem__(self, index):
for i_try in range(100):
try:
dataset_dict =self.datalist[index].as_py()
image_id = dataset_dict['image_id']
class_id = dataset_dict['class_id']
image_name = dataset_dict['file_path']
# load image
image_path = os.path.join(self.feats_folder, image_name)
if self.use_ceph:
img = self.tcs_loader(image_path).convert('RGB')
else:
img = Image.open(image_path).convert("RGB")
except Exception as e:
print(
"Failed to load image from {} with error {} ; trial {}".format(
image_path, e, i_try
)
)
# let's try another one
index = random.randint(0, len(self.datalist) - 1)
continue
img = self.transform(img)
ret = {
'input_sample': [{
'data' : img,
'invalid_mask': None,
'modality' : 'image',
'data_type': 'input',
'sample_info' : {
'id' : image_id,
'path': image_path
}
}],
'target_sample': [],
'target_idx' : [class_id],
'target_set' : copy.deepcopy(self.target_set),
'task_info' : copy.deepcopy(self.task_info)
}
return ret
def build_transform(is_train,
input_size=224,
color_jitter=0.4,
auto_augment='rand-m9-mstd0.5-inc1',
train_interpolation='bicubic',
re_prob=0.25,
re_mode='pixel',
re_count=1
):
if is_train:
# this should always dispatch to transforms_imagenet_train
transform = create_transform(
input_size=input_size,
is_training=True,
color_jitter=color_jitter,
auto_augment=auto_augment,
interpolation=train_interpolation,
re_prob=re_prob,
re_mode=re_mode,
re_count=re_count
)
return transform
t = []
size = int((256 / 224) * input_size)
t.append(
transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(input_size))
t.append(transforms.ToTensor())
t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD))
return transforms.Compose(t)
|