File size: 14,989 Bytes
9bea7a3 |
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 |
import os
import random
import argparse
from pathlib import Path
import json
import itertools
import time
from collections import defaultdict
import torch
import torch.nn.functional as F
import numpy as np
from torchvision import transforms
from PIL import Image
from transformers import CLIPImageProcessor
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import ProjectConfiguration
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection, CLIPTextModelWithProjection
from ip_adapter.ip_adapter_qformer import ImageProjModel, TextProjModel
from ip_adapter.utils import is_torch2_available
if is_torch2_available():
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
else:
from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessor
from diffusers.pipelines.blip_diffusion import Blip2QFormerModel, BlipImageProcessor
from diffusers import StableDiffusionXLPipeline
from ip_adapter import IPAdapterXLQFormer6
from advanced_categories_v4_fix import tag_augmentation, SUBJECTS, KEYWORDS
from torch.utils.data import WeightedRandomSampler
from tqdm import tqdm
from dist_utils import init_dist
import itertools
import logging
import math
from collections import defaultdict
from typing import Optional
from torch.utils.data.sampler import Sampler
from torch import distributed as dist
logger = logging.getLogger(__name__)
# Dataset
class MyDatasetv2(torch.utils.data.Dataset):
def __init__(self, json_file_list, image_root_path_list, tokenizer, tokenizer_2, size=512, layout_w=2, layout_h=2, center_crop=True, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, max_ref_attrs=3):
super().__init__()
self.tokenizer = tokenizer
self.tokenizer_2 = tokenizer_2
self.size = size
self.center_crop = center_crop
self.i_drop_rate = i_drop_rate
self.t_drop_rate = t_drop_rate
self.ti_drop_rate = ti_drop_rate
self.max_ref_attrs = max_ref_attrs
self.layout_w = layout_w
self.layout_h = layout_h
data_filter_all = torch.load('data_filter_full.pth')
self.filter_data = data_filter_all['filter_data']
self.subject2descate = data_filter_all['subject2descate']
self.subject2cate = data_filter_all['subject2cate']
self.descate2subject = data_filter_all['descate2subject']
self.descate2cate = data_filter_all['descate2cate']
assert len(json_file_list) == len(image_root_path_list)
load_from_cache = False
if not load_from_cache:
count_num = 0
prompt2imgfile = defaultdict(dict)
attr2imgfile = defaultdict(list)
all_meta = []
for i in range(len(json_file_list)):
json_file = json_file_list[i]
image_root_path = image_root_path_list[i]
all_meta, attr2imgfile, prompt2imgfile, count_num = self.load_meta(json_file, image_root_path, all_meta=all_meta, \
attr2imgfile=attr2imgfile, prompt2imgfile=prompt2imgfile, count_num=count_num)
print(json_file, count_num)
assert count_num == len(all_meta)
self.data = all_meta
self.attr2imgfile = attr2imgfile
self.prompt2imgfile = prompt2imgfile
cache_data = dict()
cache_data['prompt2imgfile'] = self.prompt2imgfile
cache_data['data'] = self.data
cache_data['attr2imgfile'] = self.attr2imgfile
torch.save(cache_data, 'FiVA_filter_cache_data.pth')
else:
cache_data = torch.load('FiVA_filter_cache_data.pth')
self.prompt2imgfile = cache_data['prompt2imgfile']
self.data = cache_data['data']
self.attr2imgfile = cache_data['attr2imgfile']
self.transform = transforms.Compose([
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
])
self.blip_transform = transforms.Compose([
transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize([0.48145466, 0.4578275, 0.40821073], [0.26862954, 0.26130258, 0.27577711]),
])
def load_meta(self, json_file, image_root_path, num_attr=None, all_meta=None, attr2imgfile=None, prompt2imgfile=None, count_num=0):
meta_data = json.load(open(json_file, 'r'))
for i in range(len(meta_data)):
meta = meta_data[i]
file_name = meta['image_path']
image_file = os.path.join(image_root_path, file_name)
meta['image_file'] = image_file
meta['attr_type'] = []
meta['attr_val'] = []
meta['content_text'] = [meta['features']['subject']]
simple_cate = self.descate2cate[meta['features']['subject']]
is_keep = False
for attr in meta['features']['attributes']:
for key, val in attr.items():
prompt_name = key + "@" + val.strip().split('@')[1]
if prompt_name in self.filter_data:
catmap = self.filter_data[prompt_name]
if simple_cate in catmap and len(catmap[simple_cate]) > 0:
target_cats = catmap[simple_cate]
if prompt_name not in prompt2imgfile:
prompt2imgfile[prompt_name] = dict()
meta['attr_type'].append(key)
meta['attr_val'].append(val)
for target_cat in target_cats:
if target_cat not in prompt2imgfile[prompt_name]:
prompt2imgfile[prompt_name][target_cat] = []
prompt2imgfile[prompt_name][target_cat].append(count_num)
is_keep = True
else:
attr2imgfile[prompt_name].append(count_num)
is_keep = True
meta['attr_type'].append(key)
meta['attr_val'].append(val)
if num_attr is not None and len(meta['attr_type']) not in num_attr:
break
if is_keep:
all_meta.append(meta)
count_num += 1
return all_meta, attr2imgfile, prompt2imgfile, count_num
def select_patch(self, image):
w_id = random.choice([i for i in range(self.layout_w)])
h_id = random.choice([i for i in range(self.layout_h)])
image_h, image_w = image.size
patch_h, patch_w = image_h / self.layout_h, image_w / self.layout_w
top = int(patch_h * h_id)
bottom = int(patch_h * h_id + patch_h)
left = int(patch_w * w_id)
right = int(patch_w * w_id + patch_w)
patch = image.crop((left, top, right, bottom))
return patch
def __getitem__(self, idx):
item = self.data[idx]
if len(item['content_text']) == 0:
print(item)
text = item['content_text'][0]
image_file = item["image_file"]
catename = self.descate2cate[text]
style_image_file_list = []
attr_type_list = []
for attr_type, attr_val in zip(item['attr_type'], item['attr_val']):
prompt_name = attr_type + "@" + attr_val.strip().split('@')[1]
if prompt_name in self.prompt2imgfile:
candidate_metas = self.prompt2imgfile[prompt_name][catename]
else:
candidate_metas = self.attr2imgfile[prompt_name]
assert len(candidate_metas) >= 1
meta_id_ = np.random.choice(candidate_metas, 1)[0]
meta_ = self.data[meta_id_]
file_name_ = meta_['image_file']
style_image_file_list.append(str(file_name_))
attr_type_list.append(attr_type)
# read image
raw_image_all = Image.open(image_file)
raw_image = self.select_patch(raw_image_all)
# original size
original_width, original_height = raw_image.size
original_size = torch.tensor([original_height, original_width])
image_tensor = self.transform(raw_image.convert("RGB"))
# random crop
delta_h = image_tensor.shape[1] - self.size
delta_w = image_tensor.shape[2] - self.size
assert not all([delta_h, delta_w])
if self.center_crop:
top = delta_h // 2
left = delta_w // 2
else:
top = np.random.randint(0, delta_h + 1)
left = np.random.randint(0, delta_w + 1)
image = transforms.functional.crop(
image_tensor, top=top, left=left, height=self.size, width=self.size
)
crop_coords_top_left = torch.tensor([top, left])
clip_image_list = []
style_image_list = []
for i in range(len(style_image_file_list)):
style_image_ = Image.open(style_image_file_list[i])
style_image = self.select_patch(style_image_)
style_image_list.append(style_image)
clip_image_list.append(self.blip_transform(style_image.convert("RGB")).unsqueeze(0))
# drop
drop_image_embed = 0
rand_num = random.random()
if rand_num < self.i_drop_rate:
drop_image_embed = 1
elif rand_num < (self.i_drop_rate + self.t_drop_rate):
text = ""
elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
text = ""
drop_image_embed = 1
# get text and tokenize
text_input_ids = self.tokenizer(
text,
max_length=self.tokenizer.model_max_length,
padding="max_length",
truncation=True,
return_tensors="pt"
).input_ids
text_input_ids_2 = self.tokenizer_2(
text,
max_length=self.tokenizer_2.model_max_length,
padding="max_length",
truncation=True,
return_tensors="pt"
).input_ids
if len(clip_image_list) < self.max_ref_attrs:
zero_image = torch.zeros_like(clip_image_list[0])
zero_attr_type = ""
zero_attr_list = [0] * len(clip_image_list)
for i in range(self.max_ref_attrs - len(clip_image_list)):
clip_image_list.append(zero_image)
attr_type_list.append(zero_attr_type)
zero_attr_list.append(1)
else:
zero_attr_list = [0] * self.max_ref_atntrs
# shuffle the order of attrs
rand_inds = [i for i in range(self.max_ref_attrs)]
random.shuffle(rand_inds)
clip_image_list = [clip_image_list[i] for i in rand_inds]
attr_type_list = [attr_type_list[i] for i in rand_inds]
zero_attr_list = [zero_attr_list[i] for i in rand_inds]
return {
"image": image,
"text_input_ids": text_input_ids,
"text_input_ids_2": text_input_ids_2,
"attr_type_list": attr_type_list,
"clip_image_list": clip_image_list,
"drop_image_embed": drop_image_embed,
"original_size": original_size,
"crop_coords_top_left": crop_coords_top_left,
"target_size": torch.tensor([self.size, self.size]),
"zero_attr_list": zero_attr_list
}
def get_balance_sampler(self, repeat_thresh=0.2):
def repeat_factors_from_category_frequency(dataset_dicts, repeat_thresh=0.2, sqrt=True):
"""
Compute (fractional) per-image repeat factors based on category frequency.
The repeat factor for an image is a function of the frequency of the rarest
category labeled in that image. The "frequency of category c" in [0, 1] is defined
as the fraction of images in the training set (without repeats) in which category c
appears.
See :paper:`lvis` (>= v2) Appendix B.2.
Args:
dataset_dicts (list[dict]): annotations in Detectron2 dataset format.
repeat_thresh (float): frequency threshold below which data is repeated.
If the frequency is half of `repeat_thresh`, the image will be
repeated twice.
sqrt (bool): if True, apply :func:`math.sqrt` to the repeat factor.
Returns:
torch.Tensor:
the i-th element is the repeat factor for the dataset image at index i.
"""
# 1. For each category c, compute the fraction of images that contain it: f(c)
category_freq = defaultdict(int)
for dataset_dict in dataset_dicts: # For each image (without repeats)
attr_types = dataset_dict['attr_type']
for attr_type in attr_types:
category_freq[attr_type] += 1
num_images = len(dataset_dicts)
for k, v in category_freq.items():
category_freq[k] = v / num_images
# 2. For each category c, compute the category-level repeat factor:
# r(c) = max(1, sqrt(t / f(c)))
category_rep = {
attr_type: max(
1.0,
(math.sqrt(repeat_thresh / cat_freq) if sqrt else (repeat_thresh / cat_freq)),
)
for attr_type, cat_freq in category_freq.items()
}
for attr_type in sorted(category_rep.keys()):
logger.info(
f"Attr type {attr_type}: freq={category_freq[attr_type]:.2f}, rep={category_rep[attr_type]:.2f}"
)
print(f"Attr type {attr_type}: freq={category_freq[attr_type]:.2f}, rep={category_rep[attr_type]:.2f}")
# 3. For each image I, compute the image-level repeat factor:
# r(I) = max_{c in I} r(c)
rep_factors = []
for dataset_dict in dataset_dicts:
attr_types = dataset_dict['attr_type']
rep_factor = max({category_rep[attr_type] for attr_type in attr_types}, default=1.0)
rep_factors.append(rep_factor)
return torch.tensor(rep_factors, dtype=torch.float32)
balance_factors = repeat_factors_from_category_frequency(self.data, repeat_thresh=repeat_thresh)
balance_sampler = WeightedRandomSampler(balance_factors, len(balance_factors), replacement=True)
return balance_sampler
def __len__(self):
return len(self.data)
|