txt2img.py 11 KB

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