notebook_helpers.py 9.9 KB

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