txt2img.py 8.8 KB

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