img2img.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. """make variations of input image"""
  2. import argparse, os, sys, glob
  3. import PIL
  4. import torch
  5. import numpy as np
  6. from omegaconf import OmegaConf
  7. from PIL import Image
  8. from tqdm import tqdm, trange
  9. from itertools import islice
  10. from einops import rearrange, repeat
  11. from torchvision.utils import make_grid
  12. from torch import autocast
  13. from contextlib import nullcontext
  14. import time
  15. from pytorch_lightning import seed_everything
  16. from ldm.util import instantiate_from_config
  17. from ldm.models.diffusion.ddim import DDIMSampler
  18. from ldm.models.diffusion.plms import PLMSSampler
  19. def chunk(it, size):
  20. it = iter(it)
  21. return iter(lambda: tuple(islice(it, size)), ())
  22. def load_model_from_config(config, ckpt, verbose=False):
  23. print(f"Loading model from {ckpt}")
  24. pl_sd = torch.load(ckpt, map_location="cpu")
  25. if "global_step" in pl_sd:
  26. print(f"Global Step: {pl_sd['global_step']}")
  27. sd = pl_sd["state_dict"]
  28. model = instantiate_from_config(config.model)
  29. m, u = model.load_state_dict(sd, strict=False)
  30. if len(m) > 0 and verbose:
  31. print("missing keys:")
  32. print(m)
  33. if len(u) > 0 and verbose:
  34. print("unexpected keys:")
  35. print(u)
  36. if torch.cuda.is_available():
  37. model.cuda()
  38. model.eval()
  39. return model
  40. def load_img(path):
  41. image = Image.open(path).convert("RGB")
  42. w, h = image.size
  43. print(f"loaded input image of size ({w}, {h}) from {path}")
  44. w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
  45. image = image.resize((w, h), resample=PIL.Image.LANCZOS)
  46. image = np.array(image).astype(np.float32) / 255.0
  47. image = image[None].transpose(0, 3, 1, 2)
  48. image = torch.from_numpy(image)
  49. return 2.*image - 1.
  50. def main():
  51. parser = argparse.ArgumentParser()
  52. parser.add_argument(
  53. "--prompt",
  54. type=str,
  55. nargs="?",
  56. default="a painting of a virus monster playing guitar",
  57. help="the prompt to render"
  58. )
  59. parser.add_argument(
  60. "--init-img",
  61. type=str,
  62. nargs="?",
  63. help="path to the input image"
  64. )
  65. parser.add_argument(
  66. "--outdir",
  67. type=str,
  68. nargs="?",
  69. help="dir to write results to",
  70. default="outputs/img2img-samples"
  71. )
  72. parser.add_argument(
  73. "--skip_grid",
  74. action='store_true',
  75. help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
  76. )
  77. parser.add_argument(
  78. "--skip_save",
  79. action='store_true',
  80. help="do not save indiviual samples. For speed measurements.",
  81. )
  82. parser.add_argument(
  83. "--ddim_steps",
  84. type=int,
  85. default=50,
  86. help="number of ddim sampling steps",
  87. )
  88. parser.add_argument(
  89. "--plms",
  90. action='store_true',
  91. help="use plms sampling",
  92. )
  93. parser.add_argument(
  94. "--fixed_code",
  95. action='store_true',
  96. help="if enabled, uses the same starting code across all samples ",
  97. )
  98. parser.add_argument(
  99. "--ddim_eta",
  100. type=float,
  101. default=0.0,
  102. help="ddim eta (eta=0.0 corresponds to deterministic sampling",
  103. )
  104. parser.add_argument(
  105. "--n_iter",
  106. type=int,
  107. default=1,
  108. help="sample this often",
  109. )
  110. parser.add_argument(
  111. "--C",
  112. type=int,
  113. default=4,
  114. help="latent channels",
  115. )
  116. parser.add_argument(
  117. "--f",
  118. type=int,
  119. default=8,
  120. help="downsampling factor, most often 8 or 16",
  121. )
  122. parser.add_argument(
  123. "--n_samples",
  124. type=int,
  125. default=2,
  126. help="how many samples to produce for each given prompt. A.k.a batch size",
  127. )
  128. parser.add_argument(
  129. "--n_rows",
  130. type=int,
  131. default=0,
  132. help="rows in the grid (default: n_samples)",
  133. )
  134. parser.add_argument(
  135. "--scale",
  136. type=float,
  137. default=5.0,
  138. help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))",
  139. )
  140. parser.add_argument(
  141. "--strength",
  142. type=float,
  143. default=0.75,
  144. help="strength for noising/unnoising. 1.0 corresponds to full destruction of information in init image",
  145. )
  146. parser.add_argument(
  147. "--from-file",
  148. type=str,
  149. help="if specified, load prompts from this file",
  150. )
  151. parser.add_argument(
  152. "--config",
  153. type=str,
  154. default="configs/stable-diffusion/v1-inference.yaml",
  155. help="path to config which constructs model",
  156. )
  157. parser.add_argument(
  158. "--ckpt",
  159. type=str,
  160. default="models/ldm/stable-diffusion-v1/model.ckpt",
  161. help="path to checkpoint of model",
  162. )
  163. parser.add_argument(
  164. "--seed",
  165. type=int,
  166. default=42,
  167. help="the seed (for reproducible sampling)",
  168. )
  169. parser.add_argument(
  170. "--precision",
  171. type=str,
  172. help="evaluate at this precision",
  173. choices=["full", "autocast"],
  174. default="autocast"
  175. )
  176. opt = parser.parse_args()
  177. seed_everything(opt.seed)
  178. config = OmegaConf.load(f"{opt.config}")
  179. model = load_model_from_config(config, f"{opt.ckpt}")
  180. device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
  181. model = model.to(device)
  182. if opt.plms:
  183. raise NotImplementedError("PLMS sampler not (yet) supported")
  184. sampler = PLMSSampler(model)
  185. else:
  186. sampler = DDIMSampler(model)
  187. os.makedirs(opt.outdir, exist_ok=True)
  188. outpath = opt.outdir
  189. batch_size = opt.n_samples
  190. n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
  191. if not opt.from_file:
  192. prompt = opt.prompt
  193. assert prompt is not None
  194. data = [batch_size * [prompt]]
  195. else:
  196. print(f"reading prompts from {opt.from_file}")
  197. with open(opt.from_file, "r") as f:
  198. data = f.read().splitlines()
  199. data = list(chunk(data, batch_size))
  200. sample_path = os.path.join(outpath, "samples")
  201. os.makedirs(sample_path, exist_ok=True)
  202. base_count = len(os.listdir(sample_path))
  203. grid_count = len(os.listdir(outpath)) - 1
  204. assert os.path.isfile(opt.init_img)
  205. init_image = load_img(opt.init_img).to(device)
  206. init_image = repeat(init_image, '1 ... -> b ...', b=batch_size)
  207. init_latent = model.get_first_stage_encoding(model.encode_first_stage(init_image)) # move to latent space
  208. sampler.make_schedule(ddim_num_steps=opt.ddim_steps, ddim_eta=opt.ddim_eta, verbose=False)
  209. assert 0. <= opt.strength <= 1., 'can only work with strength in [0.0, 1.0]'
  210. t_enc = int(opt.strength * opt.ddim_steps)
  211. print(f"target t_enc is {t_enc} steps")
  212. precision_scope = autocast if opt.precision == "autocast" else nullcontext
  213. with torch.no_grad():
  214. with precision_scope("cuda"):
  215. with model.ema_scope():
  216. tic = time.time()
  217. all_samples = list()
  218. for n in trange(opt.n_iter, desc="Sampling"):
  219. for prompts in tqdm(data, desc="data"):
  220. uc = None
  221. if opt.scale != 1.0:
  222. uc = model.get_learned_conditioning(batch_size * [""])
  223. if isinstance(prompts, tuple):
  224. prompts = list(prompts)
  225. c = model.get_learned_conditioning(prompts)
  226. # encode (scaled latent)
  227. z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device))
  228. # decode it
  229. samples = sampler.decode(z_enc, c, t_enc, unconditional_guidance_scale=opt.scale,
  230. unconditional_conditioning=uc,)
  231. x_samples = model.decode_first_stage(samples)
  232. x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0)
  233. if not opt.skip_save:
  234. for x_sample in x_samples:
  235. x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
  236. Image.fromarray(x_sample.astype(np.uint8)).save(
  237. os.path.join(sample_path, f"{base_count:05}.png"))
  238. base_count += 1
  239. all_samples.append(x_samples)
  240. if not opt.skip_grid:
  241. # additionally, save as grid
  242. grid = torch.stack(all_samples, 0)
  243. grid = rearrange(grid, 'n b c h w -> (n b) c h w')
  244. grid = make_grid(grid, nrow=n_rows)
  245. # to image
  246. grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
  247. Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
  248. grid_count += 1
  249. toc = time.time()
  250. print(f"Your samples are ready and waiting for you here: \n{outpath} \n"
  251. f" \nEnjoy.")
  252. if __name__ == "__main__":
  253. main()