notebook_helpers.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. from torchvision.datasets.utils import download_url
  2. from ldm.util import instantiate_from_config
  3. import torch
  4. import os
  5. # todo ?
  6. from google.colab import files
  7. from IPython.display import Image as ipyimg
  8. import ipywidgets as widgets
  9. from PIL import Image
  10. from numpy import asarray
  11. from einops import rearrange, repeat
  12. import torch, torchvision
  13. from ldm.models.diffusion.ddim import DDIMSampler
  14. from ldm.util import ismap
  15. import time
  16. from omegaconf import OmegaConf
  17. def download_models(mode):
  18. if mode == "superresolution":
  19. # this is the small bsr light model
  20. url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'
  21. url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'
  22. path_conf = 'logs/diffusion/superresolution_bsr/configs/project.yaml'
  23. path_ckpt = 'logs/diffusion/superresolution_bsr/checkpoints/last.ckpt'
  24. download_url(url_conf, path_conf)
  25. download_url(url_ckpt, path_ckpt)
  26. path_conf = path_conf + '/?dl=1' # fix it
  27. path_ckpt = path_ckpt + '/?dl=1' # fix it
  28. return path_conf, path_ckpt
  29. else:
  30. raise NotImplementedError
  31. def load_model_from_config(config, ckpt):
  32. print(f"Loading model from {ckpt}")
  33. pl_sd = torch.load(ckpt, map_location="cpu")
  34. global_step = pl_sd["global_step"]
  35. sd = pl_sd["state_dict"]
  36. model = instantiate_from_config(config.model)
  37. m, u = model.load_state_dict(sd, strict=False)
  38. model.cuda()
  39. model.eval()
  40. return {"model": model}, global_step
  41. def get_model(mode):
  42. path_conf, path_ckpt = download_models(mode)
  43. config = OmegaConf.load(path_conf)
  44. model, step = load_model_from_config(config, path_ckpt)
  45. return model
  46. def get_custom_cond(mode):
  47. dest = "data/example_conditioning"
  48. if mode == "superresolution":
  49. uploaded_img = files.upload()
  50. filename = next(iter(uploaded_img))
  51. name, filetype = filename.split(".") # todo assumes just one dot in name !
  52. os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}")
  53. elif mode == "text_conditional":
  54. w = widgets.Text(value='A cake with cream!', disabled=True)
  55. display(w)
  56. with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f:
  57. f.write(w.value)
  58. elif mode == "class_conditional":
  59. w = widgets.IntSlider(min=0, max=1000)
  60. display(w)
  61. with open(f"{dest}/{mode}/custom.txt", 'w') as f:
  62. f.write(w.value)
  63. else:
  64. raise NotImplementedError(f"cond not implemented for mode{mode}")
  65. def get_cond_options(mode):
  66. path = "data/example_conditioning"
  67. path = os.path.join(path, mode)
  68. onlyfiles = [f for f in sorted(os.listdir(path))]
  69. return path, onlyfiles
  70. def select_cond_path(mode):
  71. path = "data/example_conditioning" # todo
  72. path = os.path.join(path, mode)
  73. onlyfiles = [f for f in sorted(os.listdir(path))]
  74. selected = widgets.RadioButtons(
  75. options=onlyfiles,
  76. description='Select conditioning:',
  77. disabled=False
  78. )
  79. display(selected)
  80. selected_path = os.path.join(path, selected.value)
  81. return selected_path
  82. def get_cond(mode, selected_path):
  83. example = dict()
  84. if mode == "superresolution":
  85. up_f = 4
  86. visualize_cond_img(selected_path)
  87. c = Image.open(selected_path)
  88. c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
  89. c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)
  90. c_up = rearrange(c_up, '1 c h w -> 1 h w c')
  91. c = rearrange(c, '1 c h w -> 1 h w c')
  92. c = 2. * c - 1.
  93. c = c.to(torch.device("cuda"))
  94. example["LR_image"] = c
  95. example["image"] = c_up
  96. return example
  97. def visualize_cond_img(path):
  98. display(ipyimg(filename=path))
  99. def run(model, selected_path, task, custom_steps, resize_enabled=False, classifier_ckpt=None, global_step=None):
  100. example = get_cond(task, selected_path)
  101. save_intermediate_vid = False
  102. n_runs = 1
  103. masked = False
  104. guider = None
  105. ckwargs = None
  106. mode = 'ddim'
  107. ddim_use_x0_pred = False
  108. temperature = 1.
  109. eta = 1.
  110. make_progrow = True
  111. custom_shape = None
  112. height, width = example["image"].shape[1:3]
  113. split_input = height >= 128 and width >= 128
  114. if split_input:
  115. ks = 128
  116. stride = 64
  117. vqf = 4 #
  118. model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
  119. "vqf": vqf,
  120. "patch_distributed_vq": True,
  121. "tie_braker": False,
  122. "clip_max_weight": 0.5,
  123. "clip_min_weight": 0.01,
  124. "clip_max_tie_weight": 0.5,
  125. "clip_min_tie_weight": 0.01}
  126. else:
  127. if hasattr(model, "split_input_params"):
  128. delattr(model, "split_input_params")
  129. invert_mask = False
  130. x_T = None
  131. for n in range(n_runs):
  132. if custom_shape is not None:
  133. x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
  134. x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])
  135. logs = make_convolutional_sample(example, model,
  136. mode=mode, custom_steps=custom_steps,
  137. eta=eta, swap_mode=False , masked=masked,
  138. invert_mask=invert_mask, quantize_x0=False,
  139. custom_schedule=None, decode_interval=10,
  140. resize_enabled=resize_enabled, custom_shape=custom_shape,
  141. temperature=temperature, noise_dropout=0.,
  142. corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,
  143. make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred
  144. )
  145. return logs
  146. @torch.no_grad()
  147. def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
  148. mask=None, x0=None, quantize_x0=False, img_callback=None,
  149. temperature=1., noise_dropout=0., score_corrector=None,
  150. corrector_kwargs=None, x_T=None, log_every_t=None
  151. ):
  152. ddim = DDIMSampler(model)
  153. bs = shape[0] # dont know where this comes from but wayne
  154. shape = shape[1:] # cut batch dim
  155. print(f"Sampling with eta = {eta}; steps: {steps}")
  156. samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
  157. normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
  158. mask=mask, x0=x0, temperature=temperature, verbose=False,
  159. score_corrector=score_corrector,
  160. corrector_kwargs=corrector_kwargs, x_T=x_T)
  161. return samples, intermediates
  162. @torch.no_grad()
  163. def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False,
  164. invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,
  165. resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
  166. corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):
  167. log = dict()
  168. z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
  169. return_first_stage_outputs=True,
  170. force_c_encode=not (hasattr(model, 'split_input_params')
  171. and model.cond_stage_key == 'coordinates_bbox'),
  172. return_original_cond=True)
  173. log_every_t = 1 if save_intermediate_vid else None
  174. if custom_shape is not None:
  175. z = torch.randn(custom_shape)
  176. print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
  177. z0 = None
  178. log["input"] = x
  179. log["reconstruction"] = xrec
  180. if ismap(xc):
  181. log["original_conditioning"] = model.to_rgb(xc)
  182. if hasattr(model, 'cond_stage_key'):
  183. log[model.cond_stage_key] = model.to_rgb(xc)
  184. else:
  185. log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
  186. if model.cond_stage_model:
  187. log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
  188. if model.cond_stage_key =='class_label':
  189. log[model.cond_stage_key] = xc[model.cond_stage_key]
  190. with model.ema_scope("Plotting"):
  191. t0 = time.time()
  192. img_cb = None
  193. sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
  194. eta=eta,
  195. quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,
  196. temperature=temperature, noise_dropout=noise_dropout,
  197. score_corrector=corrector, corrector_kwargs=corrector_kwargs,
  198. x_T=x_T, log_every_t=log_every_t)
  199. t1 = time.time()
  200. if ddim_use_x0_pred:
  201. sample = intermediates['pred_x0'][-1]
  202. x_sample = model.decode_first_stage(sample)
  203. try:
  204. x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
  205. log["sample_noquant"] = x_sample_noquant
  206. log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
  207. except:
  208. pass
  209. log["sample"] = x_sample
  210. log["time"] = t1 - t0
  211. return log