knn2img.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import argparse, os, sys, glob
  2. import clip
  3. import torch
  4. import torch.nn as nn
  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. import scann
  13. import time
  14. from multiprocessing import cpu_count
  15. from ldm.util import instantiate_from_config, parallel_data_prefetch
  16. from ldm.models.diffusion.ddim import DDIMSampler
  17. from ldm.models.diffusion.plms import PLMSSampler
  18. from ldm.modules.encoders.modules import FrozenClipImageEmbedder, FrozenCLIPTextEmbedder
  19. DATABASES = [
  20. "openimages",
  21. "artbench-art_nouveau",
  22. "artbench-baroque",
  23. "artbench-expressionism",
  24. "artbench-impressionism",
  25. "artbench-post_impressionism",
  26. "artbench-realism",
  27. "artbench-romanticism",
  28. "artbench-renaissance",
  29. "artbench-surrealism",
  30. "artbench-ukiyo_e",
  31. ]
  32. def chunk(it, size):
  33. it = iter(it)
  34. return iter(lambda: tuple(islice(it, size)), ())
  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. if torch.cuda.is_available():
  50. model.cuda()
  51. model.eval()
  52. return model
  53. class Searcher(object):
  54. def __init__(self, database, retriever_version='ViT-L/14'):
  55. assert database in DATABASES
  56. # self.database = self.load_database(database)
  57. self.database_name = database
  58. self.searcher_savedir = f'data/rdm/searchers/{self.database_name}'
  59. self.database_path = f'data/rdm/retrieval_databases/{self.database_name}'
  60. self.retriever = self.load_retriever(version=retriever_version)
  61. self.database = {'embedding': [],
  62. 'img_id': [],
  63. 'patch_coords': []}
  64. self.load_database()
  65. self.load_searcher()
  66. def train_searcher(self, k,
  67. metric='dot_product',
  68. searcher_savedir=None):
  69. print('Start training searcher')
  70. searcher = scann.scann_ops_pybind.builder(self.database['embedding'] /
  71. np.linalg.norm(self.database['embedding'], axis=1)[:, np.newaxis],
  72. k, metric)
  73. self.searcher = searcher.score_brute_force().build()
  74. print('Finish training searcher')
  75. if searcher_savedir is not None:
  76. print(f'Save trained searcher under "{searcher_savedir}"')
  77. os.makedirs(searcher_savedir, exist_ok=True)
  78. self.searcher.serialize(searcher_savedir)
  79. def load_single_file(self, saved_embeddings):
  80. compressed = np.load(saved_embeddings)
  81. self.database = {key: compressed[key] for key in compressed.files}
  82. print('Finished loading of clip embeddings.')
  83. def load_multi_files(self, data_archive):
  84. out_data = {key: [] for key in self.database}
  85. for d in tqdm(data_archive, desc=f'Loading datapool from {len(data_archive)} individual files.'):
  86. for key in d.files:
  87. out_data[key].append(d[key])
  88. return out_data
  89. def load_database(self):
  90. print(f'Load saved patch embedding from "{self.database_path}"')
  91. file_content = glob.glob(os.path.join(self.database_path, '*.npz'))
  92. if len(file_content) == 1:
  93. self.load_single_file(file_content[0])
  94. elif len(file_content) > 1:
  95. data = [np.load(f) for f in file_content]
  96. prefetched_data = parallel_data_prefetch(self.load_multi_files, data,
  97. n_proc=min(len(data), cpu_count()), target_data_type='dict')
  98. self.database = {key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in
  99. self.database}
  100. else:
  101. raise ValueError(f'No npz-files in specified path "{self.database_path}" is this directory existing?')
  102. print(f'Finished loading of retrieval database of length {self.database["embedding"].shape[0]}.')
  103. def load_retriever(self, version='ViT-L/14', ):
  104. model = FrozenClipImageEmbedder(model=version)
  105. if torch.cuda.is_available():
  106. model.cuda()
  107. model.eval()
  108. return model
  109. def load_searcher(self):
  110. print(f'load searcher for database {self.database_name} from {self.searcher_savedir}')
  111. self.searcher = scann.scann_ops_pybind.load_searcher(self.searcher_savedir)
  112. print('Finished loading searcher.')
  113. def search(self, x, k):
  114. if self.searcher is None and self.database['embedding'].shape[0] < 2e4:
  115. self.train_searcher(k) # quickly fit searcher on the fly for small databases
  116. assert self.searcher is not None, 'Cannot search with uninitialized searcher'
  117. if isinstance(x, torch.Tensor):
  118. x = x.detach().cpu().numpy()
  119. if len(x.shape) == 3:
  120. x = x[:, 0]
  121. query_embeddings = x / np.linalg.norm(x, axis=1)[:, np.newaxis]
  122. start = time.time()
  123. nns, distances = self.searcher.search_batched(query_embeddings, final_num_neighbors=k)
  124. end = time.time()
  125. out_embeddings = self.database['embedding'][nns]
  126. out_img_ids = self.database['img_id'][nns]
  127. out_pc = self.database['patch_coords'][nns]
  128. out = {'nn_embeddings': out_embeddings / np.linalg.norm(out_embeddings, axis=-1)[..., np.newaxis],
  129. 'img_ids': out_img_ids,
  130. 'patch_coords': out_pc,
  131. 'queries': x,
  132. 'exec_time': end - start,
  133. 'nns': nns,
  134. 'q_embeddings': query_embeddings}
  135. return out
  136. def __call__(self, x, n):
  137. return self.search(x, n)
  138. if __name__ == "__main__":
  139. parser = argparse.ArgumentParser()
  140. # TODO: add n_neighbors and modes (text-only, text-image-retrieval, image-image retrieval etc)
  141. # TODO: add 'image variation' mode when knn=0 but a single image is given instead of a text prompt?
  142. parser.add_argument(
  143. "--prompt",
  144. type=str,
  145. nargs="?",
  146. default="a painting of a virus monster playing guitar",
  147. help="the prompt to render"
  148. )
  149. parser.add_argument(
  150. "--outdir",
  151. type=str,
  152. nargs="?",
  153. help="dir to write results to",
  154. default="outputs/txt2img-samples"
  155. )
  156. parser.add_argument(
  157. "--skip_grid",
  158. action='store_true',
  159. help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
  160. )
  161. parser.add_argument(
  162. "--ddim_steps",
  163. type=int,
  164. default=50,
  165. help="number of ddim sampling steps",
  166. )
  167. parser.add_argument(
  168. "--n_repeat",
  169. type=int,
  170. default=1,
  171. help="number of repeats in CLIP latent space",
  172. )
  173. parser.add_argument(
  174. "--plms",
  175. action='store_true',
  176. help="use plms sampling",
  177. )
  178. parser.add_argument(
  179. "--ddim_eta",
  180. type=float,
  181. default=0.0,
  182. help="ddim eta (eta=0.0 corresponds to deterministic sampling",
  183. )
  184. parser.add_argument(
  185. "--n_iter",
  186. type=int,
  187. default=1,
  188. help="sample this often",
  189. )
  190. parser.add_argument(
  191. "--H",
  192. type=int,
  193. default=768,
  194. help="image height, in pixel space",
  195. )
  196. parser.add_argument(
  197. "--W",
  198. type=int,
  199. default=768,
  200. help="image width, in pixel space",
  201. )
  202. parser.add_argument(
  203. "--n_samples",
  204. type=int,
  205. default=3,
  206. help="how many samples to produce for each given prompt. A.k.a batch size",
  207. )
  208. parser.add_argument(
  209. "--n_rows",
  210. type=int,
  211. default=0,
  212. help="rows in the grid (default: n_samples)",
  213. )
  214. parser.add_argument(
  215. "--scale",
  216. type=float,
  217. default=5.0,
  218. help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))",
  219. )
  220. parser.add_argument(
  221. "--from-file",
  222. type=str,
  223. help="if specified, load prompts from this file",
  224. )
  225. parser.add_argument(
  226. "--config",
  227. type=str,
  228. default="configs/retrieval-augmented-diffusion/768x768.yaml",
  229. help="path to config which constructs model",
  230. )
  231. parser.add_argument(
  232. "--ckpt",
  233. type=str,
  234. default="models/rdm/rdm768x768/model.ckpt",
  235. help="path to checkpoint of model",
  236. )
  237. parser.add_argument(
  238. "--clip_type",
  239. type=str,
  240. default="ViT-L/14",
  241. help="which CLIP model to use for retrieval and NN encoding",
  242. )
  243. parser.add_argument(
  244. "--database",
  245. type=str,
  246. default='artbench-surrealism',
  247. choices=DATABASES,
  248. help="The database used for the search, only applied when --use_neighbors=True",
  249. )
  250. parser.add_argument(
  251. "--use_neighbors",
  252. default=False,
  253. action='store_true',
  254. help="Include neighbors in addition to text prompt for conditioning",
  255. )
  256. parser.add_argument(
  257. "--knn",
  258. default=10,
  259. type=int,
  260. help="The number of included neighbors, only applied when --use_neighbors=True",
  261. )
  262. opt = parser.parse_args()
  263. config = OmegaConf.load(f"{opt.config}")
  264. model = load_model_from_config(config, f"{opt.ckpt}")
  265. device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
  266. model = model.to(device)
  267. clip_text_encoder = FrozenCLIPTextEmbedder(opt.clip_type).to(device)
  268. if opt.plms:
  269. sampler = PLMSSampler(model)
  270. else:
  271. sampler = DDIMSampler(model)
  272. os.makedirs(opt.outdir, exist_ok=True)
  273. outpath = opt.outdir
  274. batch_size = opt.n_samples
  275. n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
  276. if not opt.from_file:
  277. prompt = opt.prompt
  278. assert prompt is not None
  279. data = [batch_size * [prompt]]
  280. else:
  281. print(f"reading prompts from {opt.from_file}")
  282. with open(opt.from_file, "r") as f:
  283. data = f.read().splitlines()
  284. data = list(chunk(data, batch_size))
  285. sample_path = os.path.join(outpath, "samples")
  286. os.makedirs(sample_path, exist_ok=True)
  287. base_count = len(os.listdir(sample_path))
  288. grid_count = len(os.listdir(outpath)) - 1
  289. print(f"sampling scale for cfg is {opt.scale:.2f}")
  290. searcher = None
  291. if opt.use_neighbors:
  292. searcher = Searcher(opt.database)
  293. with torch.no_grad():
  294. with model.ema_scope():
  295. for n in trange(opt.n_iter, desc="Sampling"):
  296. all_samples = list()
  297. for prompts in tqdm(data, desc="data"):
  298. print("sampling prompts:", prompts)
  299. if isinstance(prompts, tuple):
  300. prompts = list(prompts)
  301. c = clip_text_encoder.encode(prompts)
  302. uc = None
  303. if searcher is not None:
  304. nn_dict = searcher(c, opt.knn)
  305. nn_embeddings = torch.from_numpy(nn_dict['nn_embeddings'])
  306. if torch.cuda.is_available():
  307. nn_embeddings = nn_embeddings.cuda()
  308. c = torch.cat([c, nn_embeddings], dim=1)
  309. if opt.scale != 1.0:
  310. uc = torch.zeros_like(c)
  311. if isinstance(prompts, tuple):
  312. prompts = list(prompts)
  313. shape = [16, opt.H // 16, opt.W // 16] # note: currently hardcoded for f16 model
  314. samples_ddim, _ = sampler.sample(S=opt.ddim_steps,
  315. conditioning=c,
  316. batch_size=c.shape[0],
  317. shape=shape,
  318. verbose=False,
  319. unconditional_guidance_scale=opt.scale,
  320. unconditional_conditioning=uc,
  321. eta=opt.ddim_eta,
  322. )
  323. x_samples_ddim = model.decode_first_stage(samples_ddim)
  324. x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
  325. for x_sample in x_samples_ddim:
  326. x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
  327. Image.fromarray(x_sample.astype(np.uint8)).save(
  328. os.path.join(sample_path, f"{base_count:05}.png"))
  329. base_count += 1
  330. all_samples.append(x_samples_ddim)
  331. if not opt.skip_grid:
  332. # additionally, save as grid
  333. grid = torch.stack(all_samples, 0)
  334. grid = rearrange(grid, 'n b c h w -> (n b) c h w')
  335. grid = make_grid(grid, nrow=n_rows)
  336. # to image
  337. grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
  338. Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
  339. grid_count += 1
  340. print(f"Your samples are ready and waiting for you here: \n{outpath} \nEnjoy.")