prompt_parser.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. from __future__ import annotations
  2. import re
  3. from collections import namedtuple
  4. from typing import List
  5. import lark
  6. # a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][ in background:0.25] [shoddy:masterful:0.5]"
  7. # will be represented with prompt_schedule like this (assuming steps=100):
  8. # [25, 'fantasy landscape with a mountain and an oak in foreground shoddy']
  9. # [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy']
  10. # [60, 'fantasy landscape with a lake and an oak in foreground in background masterful']
  11. # [75, 'fantasy landscape with a lake and an oak in background masterful']
  12. # [100, 'fantasy landscape with a lake and a christmas tree in background masterful']
  13. schedule_parser = lark.Lark(r"""
  14. !start: (prompt | /[][():]/+)*
  15. prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)*
  16. !emphasized: "(" prompt ")"
  17. | "(" prompt ":" prompt ")"
  18. | "[" prompt "]"
  19. scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER "]"
  20. alternate: "[" prompt ("|" prompt)+ "]"
  21. WHITESPACE: /\s+/
  22. plain: /([^\\\[\]():|]|\\.)+/
  23. %import common.SIGNED_NUMBER -> NUMBER
  24. """)
  25. def get_learned_conditioning_prompt_schedules(prompts, steps):
  26. """
  27. >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
  28. >>> g("test")
  29. [[10, 'test']]
  30. >>> g("a [b:3]")
  31. [[3, 'a '], [10, 'a b']]
  32. >>> g("a [b: 3]")
  33. [[3, 'a '], [10, 'a b']]
  34. >>> g("a [[[b]]:2]")
  35. [[2, 'a '], [10, 'a [[b]]']]
  36. >>> g("[(a:2):3]")
  37. [[3, ''], [10, '(a:2)']]
  38. >>> g("a [b : c : 1] d")
  39. [[1, 'a b d'], [10, 'a c d']]
  40. >>> g("a[b:[c:d:2]:1]e")
  41. [[1, 'abe'], [2, 'ace'], [10, 'ade']]
  42. >>> g("a [unbalanced")
  43. [[10, 'a [unbalanced']]
  44. >>> g("a [b:.5] c")
  45. [[5, 'a c'], [10, 'a b c']]
  46. >>> g("a [{b|d{:.5] c") # not handling this right now
  47. [[5, 'a c'], [10, 'a {b|d{ c']]
  48. >>> g("((a][:b:c [d:3]")
  49. [[3, '((a][:b:c '], [10, '((a][:b:c d']]
  50. >>> g("[a|(b:1.1)]")
  51. [[1, 'a'], [2, '(b:1.1)'], [3, 'a'], [4, '(b:1.1)'], [5, 'a'], [6, '(b:1.1)'], [7, 'a'], [8, '(b:1.1)'], [9, 'a'], [10, '(b:1.1)']]
  52. """
  53. def collect_steps(steps, tree):
  54. res = [steps]
  55. class CollectSteps(lark.Visitor):
  56. def scheduled(self, tree):
  57. tree.children[-1] = float(tree.children[-1])
  58. if tree.children[-1] < 1:
  59. tree.children[-1] *= steps
  60. tree.children[-1] = min(steps, int(tree.children[-1]))
  61. res.append(tree.children[-1])
  62. def alternate(self, tree):
  63. res.extend(range(1, steps+1))
  64. CollectSteps().visit(tree)
  65. return sorted(set(res))
  66. def at_step(step, tree):
  67. class AtStep(lark.Transformer):
  68. def scheduled(self, args):
  69. before, after, _, when = args
  70. yield before or () if step <= when else after
  71. def alternate(self, args):
  72. yield next(args[(step - 1)%len(args)])
  73. def start(self, args):
  74. def flatten(x):
  75. if type(x) == str:
  76. yield x
  77. else:
  78. for gen in x:
  79. yield from flatten(gen)
  80. return ''.join(flatten(args))
  81. def plain(self, args):
  82. yield args[0].value
  83. def __default__(self, data, children, meta):
  84. for child in children:
  85. yield child
  86. return AtStep().transform(tree)
  87. def get_schedule(prompt):
  88. try:
  89. tree = schedule_parser.parse(prompt)
  90. except lark.exceptions.LarkError:
  91. if 0:
  92. import traceback
  93. traceback.print_exc()
  94. return [[steps, prompt]]
  95. return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
  96. promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
  97. return [promptdict[prompt] for prompt in prompts]
  98. ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
  99. class SdConditioning(list):
  100. """
  101. A list with prompts for stable diffusion's conditioner model.
  102. Can also specify width and height of created image - SDXL needs it.
  103. """
  104. def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None):
  105. super().__init__()
  106. self.extend(prompts)
  107. if copy_from is None:
  108. copy_from = prompts
  109. self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False)
  110. self.width = width or getattr(copy_from, 'width', None)
  111. self.height = height or getattr(copy_from, 'height', None)
  112. def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps):
  113. """converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning, specifying the comdition (cond),
  114. and the sampling step at which this condition is to be replaced by the next one.
  115. Input:
  116. (model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20)
  117. Output:
  118. [
  119. [
  120. ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0523, ..., -0.4901, -0.3066, 0.0674], ..., [ 0.3317, -0.5102, -0.4066, ..., 0.4119, -0.7647, -1.0160]], device='cuda:0'))
  121. ],
  122. [
  123. ScheduledPromptConditioning(end_at_step=5, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.0192, 0.3867, -0.4644, ..., 0.1135, -0.3696, -0.4625]], device='cuda:0')),
  124. ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.7352, -0.4356, -0.7888, ..., 0.6994, -0.4312, -1.2593]], device='cuda:0'))
  125. ]
  126. ]
  127. """
  128. res = []
  129. prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps)
  130. cache = {}
  131. for prompt, prompt_schedule in zip(prompts, prompt_schedules):
  132. cached = cache.get(prompt, None)
  133. if cached is not None:
  134. res.append(cached)
  135. continue
  136. texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts)
  137. conds = model.get_learned_conditioning(texts)
  138. cond_schedule = []
  139. for i, (end_at_step, _) in enumerate(prompt_schedule):
  140. if isinstance(conds, dict):
  141. cond = {k: v[i] for k, v in conds.items()}
  142. else:
  143. cond = conds[i]
  144. cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond))
  145. cache[prompt] = cond_schedule
  146. res.append(cond_schedule)
  147. return res
  148. re_AND = re.compile(r"\bAND\b")
  149. re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
  150. def get_multicond_prompt_list(prompts: SdConditioning | list[str]):
  151. res_indexes = []
  152. prompt_indexes = {}
  153. prompt_flat_list = SdConditioning(prompts)
  154. prompt_flat_list.clear()
  155. for prompt in prompts:
  156. subprompts = re_AND.split(prompt)
  157. indexes = []
  158. for subprompt in subprompts:
  159. match = re_weight.search(subprompt)
  160. text, weight = match.groups() if match is not None else (subprompt, 1.0)
  161. weight = float(weight) if weight is not None else 1.0
  162. index = prompt_indexes.get(text, None)
  163. if index is None:
  164. index = len(prompt_flat_list)
  165. prompt_flat_list.append(text)
  166. prompt_indexes[text] = index
  167. indexes.append((index, weight))
  168. res_indexes.append(indexes)
  169. return res_indexes, prompt_flat_list, prompt_indexes
  170. class ComposableScheduledPromptConditioning:
  171. def __init__(self, schedules, weight=1.0):
  172. self.schedules: List[ScheduledPromptConditioning] = schedules
  173. self.weight: float = weight
  174. class MulticondLearnedConditioning:
  175. def __init__(self, shape, batch):
  176. self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS
  177. self.batch: List[List[ComposableScheduledPromptConditioning]] = batch
  178. def get_multicond_learned_conditioning(model, prompts, steps) -> MulticondLearnedConditioning:
  179. """same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt.
  180. For each prompt, the list is obtained by splitting the prompt using the AND separator.
  181. https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/
  182. """
  183. res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts)
  184. learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps)
  185. res = []
  186. for indexes in res_indexes:
  187. res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes])
  188. return MulticondLearnedConditioning(shape=(len(prompts),), batch=res)
  189. class DictWithShape(dict):
  190. def __init__(self, x, shape):
  191. super().__init__()
  192. self.update(x)
  193. @property
  194. def shape(self):
  195. return self["crossattn"].shape
  196. def reconstruct_cond_batch(c: List[List[ScheduledPromptConditioning]], current_step):
  197. param = c[0][0].cond
  198. is_dict = isinstance(param, dict)
  199. if is_dict:
  200. dict_cond = param
  201. res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()}
  202. res = DictWithShape(res, (len(c),) + dict_cond['crossattn'].shape)
  203. else:
  204. res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype)
  205. for i, cond_schedule in enumerate(c):
  206. target_index = 0
  207. for current, entry in enumerate(cond_schedule):
  208. if current_step <= entry.end_at_step:
  209. target_index = current
  210. break
  211. if is_dict:
  212. for k, param in cond_schedule[target_index].cond.items():
  213. res[k][i] = param
  214. else:
  215. res[i] = cond_schedule[target_index].cond
  216. return res
  217. def stack_conds(tensors):
  218. # if prompts have wildly different lengths above the limit we'll get tensors of different shapes
  219. # and won't be able to torch.stack them. So this fixes that.
  220. token_count = max([x.shape[0] for x in tensors])
  221. for i in range(len(tensors)):
  222. if tensors[i].shape[0] != token_count:
  223. last_vector = tensors[i][-1:]
  224. last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1])
  225. tensors[i] = torch.vstack([tensors[i], last_vector_repeated])
  226. return torch.stack(tensors)
  227. def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
  228. param = c.batch[0][0].schedules[0].cond
  229. tensors = []
  230. conds_list = []
  231. for composable_prompts in c.batch:
  232. conds_for_batch = []
  233. for composable_prompt in composable_prompts:
  234. target_index = 0
  235. for current, entry in enumerate(composable_prompt.schedules):
  236. if current_step <= entry.end_at_step:
  237. target_index = current
  238. break
  239. conds_for_batch.append((len(tensors), composable_prompt.weight))
  240. tensors.append(composable_prompt.schedules[target_index].cond)
  241. conds_list.append(conds_for_batch)
  242. if isinstance(tensors[0], dict):
  243. keys = list(tensors[0].keys())
  244. stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys}
  245. stacked = DictWithShape(stacked, stacked['crossattn'].shape)
  246. else:
  247. stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype)
  248. return conds_list, stacked
  249. re_attention = re.compile(r"""
  250. \\\(|
  251. \\\)|
  252. \\\[|
  253. \\]|
  254. \\\\|
  255. \\|
  256. \(|
  257. \[|
  258. :([+-]?[.\d]+)\)|
  259. \)|
  260. ]|
  261. [^\\()\[\]:]+|
  262. :
  263. """, re.X)
  264. re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
  265. def parse_prompt_attention(text):
  266. """
  267. Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
  268. Accepted tokens are:
  269. (abc) - increases attention to abc by a multiplier of 1.1
  270. (abc:3.12) - increases attention to abc by a multiplier of 3.12
  271. [abc] - decreases attention to abc by a multiplier of 1.1
  272. \( - literal character '('
  273. \[ - literal character '['
  274. \) - literal character ')'
  275. \] - literal character ']'
  276. \\ - literal character '\'
  277. anything else - just text
  278. >>> parse_prompt_attention('normal text')
  279. [['normal text', 1.0]]
  280. >>> parse_prompt_attention('an (important) word')
  281. [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
  282. >>> parse_prompt_attention('(unbalanced')
  283. [['unbalanced', 1.1]]
  284. >>> parse_prompt_attention('\(literal\]')
  285. [['(literal]', 1.0]]
  286. >>> parse_prompt_attention('(unnecessary)(parens)')
  287. [['unnecessaryparens', 1.1]]
  288. >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
  289. [['a ', 1.0],
  290. ['house', 1.5730000000000004],
  291. [' ', 1.1],
  292. ['on', 1.0],
  293. [' a ', 1.1],
  294. ['hill', 0.55],
  295. [', sun, ', 1.1],
  296. ['sky', 1.4641000000000006],
  297. ['.', 1.1]]
  298. """
  299. res = []
  300. round_brackets = []
  301. square_brackets = []
  302. round_bracket_multiplier = 1.1
  303. square_bracket_multiplier = 1 / 1.1
  304. def multiply_range(start_position, multiplier):
  305. for p in range(start_position, len(res)):
  306. res[p][1] *= multiplier
  307. for m in re_attention.finditer(text):
  308. text = m.group(0)
  309. weight = m.group(1)
  310. if text.startswith('\\'):
  311. res.append([text[1:], 1.0])
  312. elif text == '(':
  313. round_brackets.append(len(res))
  314. elif text == '[':
  315. square_brackets.append(len(res))
  316. elif weight is not None and round_brackets:
  317. multiply_range(round_brackets.pop(), float(weight))
  318. elif text == ')' and round_brackets:
  319. multiply_range(round_brackets.pop(), round_bracket_multiplier)
  320. elif text == ']' and square_brackets:
  321. multiply_range(square_brackets.pop(), square_bracket_multiplier)
  322. else:
  323. parts = re.split(re_break, text)
  324. for i, part in enumerate(parts):
  325. if i > 0:
  326. res.append(["BREAK", -1])
  327. res.append([part, 1.0])
  328. for pos in round_brackets:
  329. multiply_range(pos, round_bracket_multiplier)
  330. for pos in square_brackets:
  331. multiply_range(pos, square_bracket_multiplier)
  332. if len(res) == 0:
  333. res = [["", 1.0]]
  334. # merge runs of identical weights
  335. i = 0
  336. while i + 1 < len(res):
  337. if res[i][1] == res[i + 1][1]:
  338. res[i][0] += res[i + 1][0]
  339. res.pop(i + 1)
  340. else:
  341. i += 1
  342. return res
  343. if __name__ == "__main__":
  344. import doctest
  345. doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
  346. else:
  347. import torch # doctest faster