txt2img.py 9.9 KB

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