img2img.py 9.0 KB

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