prompt_parser.py 13 KB

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