prompt_parser.py 16 KB

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