| 10 | |
| 11 | |
| 12 | class ImageLogger(Callback): |
| 13 | def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps=True, |
| 14 | rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False, |
| 15 | log_images_kwargs=None): |
| 16 | super().__init__() |
| 17 | self.rescale = rescale |
| 18 | self.batch_freq = batch_frequency |
| 19 | self.max_images = max_images |
| 20 | if not increase_log_steps: |
| 21 | self.log_steps = [self.batch_freq] |
| 22 | self.clamp = clamp |
| 23 | self.disabled = disabled |
| 24 | self.log_on_batch_idx = log_on_batch_idx |
| 25 | self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {} |
| 26 | self.log_first_step = log_first_step |
| 27 | |
| 28 | @rank_zero_only |
| 29 | def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx): |
| 30 | root = os.path.join(save_dir, "image_log", split) |
| 31 | # root = os.path.join(save_dir, "image_log", split+"_titan") |
| 32 | path_image = {} |
| 33 | for k in images: |
| 34 | grid = torchvision.utils.make_grid(images[k], nrow=4) |
| 35 | if self.rescale: |
| 36 | grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w |
| 37 | grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1) |
| 38 | grid = grid.numpy() |
| 39 | grid = (grid * 255).astype(np.uint8) |
| 40 | filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx) |
| 41 | path = os.path.join(root, filename) |
| 42 | os.makedirs(os.path.split(path)[0], exist_ok=True) |
| 43 | grid = Image.fromarray(grid) |
| 44 | grid.save(path) |
| 45 | path_image[k] = grid |
| 46 | grid_control = path_image["control_mask"] |
| 47 | grid_samples = path_image["samples_cfg_scale_9.00_mask"] |
| 48 | blended_filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format("blended", global_step, current_epoch, batch_idx) |
| 49 | blended_path = os.path.join(root, blended_filename) |
| 50 | blended_image = Image.blend(grid_control, grid_samples, alpha=0.5) |
| 51 | blended_image.save(blended_path) |
| 52 | |
| 53 | def log_img(self, pl_module, batch, batch_idx, split="train"): |
| 54 | check_idx = batch_idx # if self.log_on_batch_idx else pl_module.global_step |
| 55 | if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0 |
| 56 | hasattr(pl_module, "log_images") and |
| 57 | callable(pl_module.log_images) and |
| 58 | self.max_images > 0): |
| 59 | logger = type(pl_module.logger) |
| 60 | |
| 61 | is_train = pl_module.training |
| 62 | if is_train: |
| 63 | pl_module.eval() |
| 64 | |
| 65 | with torch.no_grad(): |
| 66 | images = pl_module.log_images(batch, split=split, **self.log_images_kwargs) |
| 67 | |
| 68 | path_image = {} |
| 69 | for k in images: |
nothing calls this directly
no outgoing calls
no test coverage detected