prompt_parser.py 13 KB

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