prompt_parser.py 16 KB

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