import logging import os import torch from tqdm import tqdm from accelerate import Accelerator from accelerate.utils import ProjectConfiguration import torch.utils.data as data from torchvision.transforms import ToTensor,Compose from diffusion_model.stable_diffusion import diffusion from pycocotools.coco import COCO from accelerate import DistributedDataParallelKwargs import h5py from tqdm import tqdm import torch from torch.utils.data.distributed import DistributedSampler from torch.utils.data import Dataset from open_clip.transform import ResizeLongest, _convert_to_rgb from PIL import Image from functools import reduce import torch.nn.functional as F os.environ["NCCL_P2P_DISABLE"] = "1" os.environ["NCCL_IB_DISABLE"] = "1" def save_features_to_h5(group, key, self_att): group.create_dataset( key, data=self_att.cpu().numpy().astype('float16'), dtype='float16', compression='lzf') class SDNormalize(object): def __call__(self, img): return 2.0 * img - 1.0 class COCODataset(Dataset): def __init__(self, input_filename, transforms, image_root): self.coco = COCO(input_filename) logging.info('Done loading data.') self.transforms = transforms self.image_root = image_root self.image_ids = list(self.coco.imgs.keys()) 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 __len__(self): return len(self.image_ids) 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) new_image = self.transforms(old_image) return new_image, image_name if __name__ == '__main__': attention_layers_to_use=[-4, -6] sd_version='v2.1' time_step=45 cache_dir='sd_self_attn_cache' half_precision=True thr=0.1 preprocess =Compose([ResizeLongest(512, fill=0), _convert_to_rgb, ToTensor(), SDNormalize()]) dataset = COCODataset( input_filename='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json', transforms=preprocess, image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017') accelerator = Accelerator(log_with="tensorboard", project_config=ProjectConfiguration( project_dir=".", logging_dir="logs" ), mixed_precision="fp16" if half_precision else "no", # bf16 for A100 kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=True)] # True for full fine-tune ) print("Waiting for everyone!") accelerator.wait_for_everyone() print("All processes synchronized!") with accelerator.main_process_first(): if not os.path.exists(cache_dir): os.mkdir(cache_dir) rank = accelerator.process_index world_size = accelerator.num_processes sampler = DistributedSampler( dataset, num_replicas=world_size, rank=rank, shuffle=False, drop_last=False ) dataloader = data.DataLoader(dataset, batch_size=1, sampler=sampler, shuffle=False, num_workers=4) cache_path = os.path.join(cache_dir,f"rank_{rank}.h5") teacher=diffusion(attention_layers_to_use=attention_layers_to_use,model=sd_version, time_step=time_step, device=accelerator.device,dtype=torch.float16) teacher.eval() with h5py.File(cache_path, 'w') as h5f: # 只有主进程显示 tqdm if rank == 0: batch_iter = tqdm(dataloader, desc=f"Rank {rank} extracting features") else: batch_iter = dataloader for batch in batch_iter: with torch.no_grad(): images, key = batch images = images.to(accelerator.device, dtype=torch.float16 if half_precision else torch.float32) teacher.forward_wo_preprocess(images, "") self_att = torch.cat([teacher.attention_maps[idx] for idx in attention_layers_to_use]).float() # 10,1024 self_att /= torch.amax(self_att, dim=-2, keepdim=True) + 1e-5 self_att = torch.where(self_att < thr, 0, self_att) self_att /= self_att.sum(dim=-1, keepdim=True) + 1e-5 self_att = reduce(torch.matmul, self_att, torch.eye(self_att.shape[-1], device=self_att.device)) save_features_to_h5(h5f, key[0], self_att) print(f"Rank {rank} finished caching to {cache_path}") # accelerate launch --num_processes 8 --mixed_precision fp16 extract_features.py