prompt_parser.py 16 KB

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