prompt_parser.py 16.3 KB
Newer Older
A
AUTOMATIC1111 已提交
1 2
from __future__ import annotations

A
AUTOMATIC 已提交
3 4
import re
from collections import namedtuple
5
import lark
A
AUTOMATIC 已提交
6

M
Meerkov 已提交
7
# 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]"
A
AUTOMATIC 已提交
8 9 10 11 12 13 14
# will be represented with prompt_schedule like this (assuming steps=100):
# [25, 'fantasy landscape with a mountain and an oak in foreground shoddy']
# [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy']
# [60, 'fantasy landscape with a lake and an oak in foreground in background masterful']
# [75, 'fantasy landscape with a lake and an oak in background masterful']
# [100, 'fantasy landscape with a lake and a christmas tree in background masterful']

15 16
schedule_parser = lark.Lark(r"""
!start: (prompt | /[][():]/+)*
A
Artem Zagidulin 已提交
17
prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)*
18 19 20
!emphasized: "(" prompt ")"
        | "(" prompt ":" prompt ")"
        | "[" prompt "]"
21
scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER [WHITESPACE] "]"
22
alternate: "[" prompt ("|" [prompt])+ "]"
23
WHITESPACE: /\s+/
A
Artem Zagidulin 已提交
24
plain: /([^\\\[\]():|]|\\.)+/
25 26
%import common.SIGNED_NUMBER -> NUMBER
""")
A
AUTOMATIC 已提交
27

28
def get_learned_conditioning_prompt_schedules(prompts, base_steps, hires_steps=None, use_old_scheduling=False):
D
dan 已提交
29
    """
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
    >>> g("test")
    [[10, 'test']]
    >>> g("a [b:3]")
    [[3, 'a '], [10, 'a b']]
    >>> g("a [b: 3]")
    [[3, 'a '], [10, 'a b']]
    >>> g("a [[[b]]:2]")
    [[2, 'a '], [10, 'a [[b]]']]
    >>> g("[(a:2):3]")
    [[3, ''], [10, '(a:2)']]
    >>> g("a [b : c : 1] d")
    [[1, 'a b  d'], [10, 'a  c  d']]
    >>> g("a[b:[c:d:2]:1]e")
    [[1, 'abe'], [2, 'ace'], [10, 'ade']]
    >>> g("a [unbalanced")
    [[10, 'a [unbalanced']]
    >>> g("a [b:.5] c")
    [[5, 'a  c'], [10, 'a b c']]
    >>> g("a [{b|d{:.5] c")  # not handling this right now
    [[5, 'a  c'], [10, 'a {b|d{ c']]
    >>> g("((a][:b:c [d:3]")
    [[3, '((a][:b:c '], [10, '((a][:b:c d']]
53 54
    >>> g("[a|(b:1.1)]")
    [[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)']]
55 56 57 58
    >>> g("[fe|]male")
    [[1, 'female'], [2, 'male'], [3, 'female'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'female'], [8, 'male'], [9, 'female'], [10, 'male']]
    >>> g("[fe|||]male")
    [[1, 'female'], [2, 'male'], [3, 'male'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'male'], [8, 'male'], [9, 'female'], [10, 'male']]
59 60 61 62 63
    >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10, 10)[0]
    >>> g("a [b:.5] c")
    [[10, 'a b c']]
    >>> g("a [b:1.5] c")
    [[5, 'a  c'], [10, 'a b c']]
64
    """
65

66 67 68 69 70 71 72 73 74
    if hires_steps is None or use_old_scheduling:
        int_offset = 0
        flt_offset = 0
        steps = base_steps
    else:
        int_offset = base_steps
        flt_offset = 1.0
        steps = hires_steps

D
dan 已提交
75
    def collect_steps(steps, tree):
A
AUTOMATIC 已提交
76 77
        res = [steps]

78
        class CollectSteps(lark.Visitor):
D
dan 已提交
79
            def scheduled(self, tree):
80 81 82 83 84 85 86 87 88 89 90 91
                s = tree.children[-2]
                v = float(s)
                if use_old_scheduling:
                    v = v*steps if v<1 else v
                else:
                    if "." in s:
                        v = (v - flt_offset) * steps
                    else:
                        v = (v - int_offset)
                tree.children[-2] = min(steps, int(v))
                if tree.children[-2] >= 1:
                    res.append(tree.children[-2])
A
AUTOMATIC 已提交
92

A
Artem Zagidulin 已提交
93
            def alternate(self, tree):
A
AUTOMATIC 已提交
94 95
                res.extend(range(1, steps+1))

D
dan 已提交
96
        CollectSteps().visit(tree)
A
AUTOMATIC 已提交
97
        return sorted(set(res))
98

D
dan 已提交
99
    def at_step(step, tree):
100
        class AtStep(lark.Transformer):
D
dan 已提交
101
            def scheduled(self, args):
102
                before, after, _, when, _ = args
103
                yield before or () if step <= when else after
A
Artem Zagidulin 已提交
104
            def alternate(self, args):
105 106
                args = ["" if not arg else arg for arg in args]
                yield args[(step - 1) % len(args)]
D
dan 已提交
107 108
            def start(self, args):
                def flatten(x):
X
XDOneDude 已提交
109
                    if isinstance(x, str):
D
dan 已提交
110 111 112 113
                        yield x
                    else:
                        for gen in x:
                            yield from flatten(gen)
114
                return ''.join(flatten(args))
D
dan 已提交
115 116 117 118
            def plain(self, args):
                yield args[0].value
            def __default__(self, data, children, meta):
                for child in children:
119
                    yield child
D
dan 已提交
120
        return AtStep().transform(tree)
121

D
dan 已提交
122
    def get_schedule(prompt):
123 124
        try:
            tree = schedule_parser.parse(prompt)
A
AUTOMATIC 已提交
125
        except lark.exceptions.LarkError:
126 127 128 129
            if 0:
                import traceback
                traceback.print_exc()
            return [[steps, prompt]]
D
dan 已提交
130
        return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
131 132 133

    promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
    return [promptdict[prompt] for prompt in prompts]
A
AUTOMATIC 已提交
134 135 136 137 138


ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])


A
AUTOMATIC1111 已提交
139 140 141 142 143
class SdConditioning(list):
    """
    A list with prompts for stable diffusion's conditioner model.
    Can also specify width and height of created image - SDXL needs it.
    """
144
    def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None):
A
AUTOMATIC1111 已提交
145 146
        super().__init__()
        self.extend(prompts)
147 148 149 150 151 152 153 154

        if copy_from is None:
            copy_from = prompts

        self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False)
        self.width = width or getattr(copy_from, 'width', None)
        self.height = height or getattr(copy_from, 'height', None)

A
AUTOMATIC1111 已提交
155 156


157
def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps, hires_steps=None, use_old_scheduling=False):
A
AUTOMATIC 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    """converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning, specifying the comdition (cond),
    and the sampling step at which this condition is to be replaced by the next one.

    Input:
    (model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20)

    Output:
    [
        [
            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'))
        ],
        [
            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')),
            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'))
        ]
    ]
    """
A
AUTOMATIC 已提交
175 176
    res = []

177
    prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps, hires_steps, use_old_scheduling)
A
AUTOMATIC 已提交
178 179 180 181 182 183 184
    cache = {}

    for prompt, prompt_schedule in zip(prompts, prompt_schedules):

        cached = cache.get(prompt, None)
        if cached is not None:
            res.append(cached)
A
AUTOMATIC 已提交
185
            continue
A
AUTOMATIC 已提交
186

187
        texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts)
188
        conds = model.get_learned_conditioning(texts)
A
AUTOMATIC 已提交
189 190

        cond_schedule = []
A
AUTOMATIC 已提交
191
        for i, (end_at_step, _) in enumerate(prompt_schedule):
192 193 194 195 196 197
            if isinstance(conds, dict):
                cond = {k: v[i] for k, v in conds.items()}
            else:
                cond = conds[i]

            cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond))
A
AUTOMATIC 已提交
198 199 200 201

        cache[prompt] = cond_schedule
        res.append(cond_schedule)

A
AUTOMATIC 已提交
202 203 204 205
    return res


re_AND = re.compile(r"\bAND\b")
206
re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
A
AUTOMATIC 已提交
207

A
AUTOMATIC1111 已提交
208 209

def get_multicond_prompt_list(prompts: SdConditioning | list[str]):
A
AUTOMATIC 已提交
210 211 212
    res_indexes = []

    prompt_indexes = {}
A
AUTOMATIC1111 已提交
213 214
    prompt_flat_list = SdConditioning(prompts)
    prompt_flat_list.clear()
A
AUTOMATIC 已提交
215 216 217 218 219 220

    for prompt in prompts:
        subprompts = re_AND.split(prompt)

        indexes = []
        for subprompt in subprompts:
221 222 223
            match = re_weight.search(subprompt)

            text, weight = match.groups() if match is not None else (subprompt, 1.0)
A
AUTOMATIC 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

            weight = float(weight) if weight is not None else 1.0

            index = prompt_indexes.get(text, None)
            if index is None:
                index = len(prompt_flat_list)
                prompt_flat_list.append(text)
                prompt_indexes[text] = index

            indexes.append((index, weight))

        res_indexes.append(indexes)

    return res_indexes, prompt_flat_list, prompt_indexes


class ComposableScheduledPromptConditioning:
    def __init__(self, schedules, weight=1.0):
A
a666 已提交
242
        self.schedules: list[ScheduledPromptConditioning] = schedules
A
AUTOMATIC 已提交
243 244 245 246 247 248
        self.weight: float = weight


class MulticondLearnedConditioning:
    def __init__(self, shape, batch):
        self.shape: tuple = shape  # the shape field is needed to send this object to DDIM/PLMS
A
a666 已提交
249
        self.batch: list[list[ComposableScheduledPromptConditioning]] = batch
A
AUTOMATIC 已提交
250

A
AUTOMATIC1111 已提交
251

252
def get_multicond_learned_conditioning(model, prompts, steps, hires_steps=None, use_old_scheduling=False) -> MulticondLearnedConditioning:
A
AUTOMATIC 已提交
253 254 255 256 257 258 259 260
    """same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt.
    For each prompt, the list is obtained by splitting the prompt using the AND separator.

    https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/
    """

    res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts)

261
    learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps, hires_steps, use_old_scheduling)
A
AUTOMATIC 已提交
262 263 264 265 266 267 268 269

    res = []
    for indexes in res_indexes:
        res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes])

    return MulticondLearnedConditioning(shape=(len(prompts),), batch=res)


270 271 272 273 274 275 276 277 278 279
class DictWithShape(dict):
    def __init__(self, x, shape):
        super().__init__()
        self.update(x)

    @property
    def shape(self):
        return self["crossattn"].shape


A
a666 已提交
280
def reconstruct_cond_batch(c: list[list[ScheduledPromptConditioning]], current_step):
A
AUTOMATIC 已提交
281
    param = c[0][0].cond
282 283 284 285 286 287 288 289 290
    is_dict = isinstance(param, dict)

    if is_dict:
        dict_cond = param
        res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()}
        res = DictWithShape(res, (len(c),) + dict_cond['crossattn'].shape)
    else:
        res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype)

A
AUTOMATIC 已提交
291
    for i, cond_schedule in enumerate(c):
A
AUTOMATIC 已提交
292
        target_index = 0
A
AUTOMATIC 已提交
293 294
        for current, entry in enumerate(cond_schedule):
            if current_step <= entry.end_at_step:
295
                target_index = current
A
AUTOMATIC 已提交
296
                break
297 298 299 300 301 302

        if is_dict:
            for k, param in cond_schedule[target_index].cond.items():
                res[k][i] = param
        else:
            res[i] = cond_schedule[target_index].cond
A
AUTOMATIC 已提交
303

C
C43H66N12O12S2 已提交
304
    return res
A
AUTOMATIC 已提交
305 306


307 308 309 310 311 312 313 314 315 316 317 318 319 320
def stack_conds(tensors):
    # if prompts have wildly different lengths above the limit we'll get tensors of different shapes
    # and won't be able to torch.stack them. So this fixes that.
    token_count = max([x.shape[0] for x in tensors])
    for i in range(len(tensors)):
        if tensors[i].shape[0] != token_count:
            last_vector = tensors[i][-1:]
            last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1])
            tensors[i] = torch.vstack([tensors[i], last_vector_repeated])

    return torch.stack(tensors)



A
AUTOMATIC 已提交
321 322 323 324 325 326
def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
    param = c.batch[0][0].schedules[0].cond

    tensors = []
    conds_list = []

A
AUTOMATIC 已提交
327
    for composable_prompts in c.batch:
A
AUTOMATIC 已提交
328 329
        conds_for_batch = []

A
AUTOMATIC 已提交
330
        for composable_prompt in composable_prompts:
A
AUTOMATIC 已提交
331
            target_index = 0
A
AUTOMATIC 已提交
332 333
            for current, entry in enumerate(composable_prompt.schedules):
                if current_step <= entry.end_at_step:
A
AUTOMATIC 已提交
334 335 336 337 338 339 340 341
                    target_index = current
                    break

            conds_for_batch.append((len(tensors), composable_prompt.weight))
            tensors.append(composable_prompt.schedules[target_index].cond)

        conds_list.append(conds_for_batch)

342 343 344 345 346 347
    if isinstance(tensors[0], dict):
        keys = list(tensors[0].keys())
        stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys}
        stacked = DictWithShape(stacked, stacked['crossattn'].shape)
    else:
        stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype)
A
AUTOMATIC 已提交
348

349
    return conds_list, stacked
A
AUTOMATIC 已提交
350 351


352 353 354 355 356 357 358 359 360
re_attention = re.compile(r"""
\\\(|
\\\)|
\\\[|
\\]|
\\\\|
\\|
\(|
\[|
361
:\s*([+-]?[.\d]+)\s*\)|
362 363 364 365 366 367
\)|
]|
[^\\()\[\]:]+|
:
""", re.X)

368
re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
369 370 371

def parse_prompt_attention(text):
    """
I
Ikko Ashimine 已提交
372
    Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
373 374 375 376 377 378 379 380 381 382 383
    Accepted tokens are:
      (abc) - increases attention to abc by a multiplier of 1.1
      (abc:3.12) - increases attention to abc by a multiplier of 3.12
      [abc] - decreases attention to abc by a multiplier of 1.1
      \( - literal character '('
      \[ - literal character '['
      \) - literal character ')'
      \] - literal character ']'
      \\ - literal character '\'
      anything else - just text

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    >>> parse_prompt_attention('normal text')
    [['normal text', 1.0]]
    >>> parse_prompt_attention('an (important) word')
    [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
    >>> parse_prompt_attention('(unbalanced')
    [['unbalanced', 1.1]]
    >>> parse_prompt_attention('\(literal\]')
    [['(literal]', 1.0]]
    >>> parse_prompt_attention('(unnecessary)(parens)')
    [['unnecessaryparens', 1.1]]
    >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
    [['a ', 1.0],
     ['house', 1.5730000000000004],
     [' ', 1.1],
     ['on', 1.0],
     [' a ', 1.1],
     ['hill', 0.55],
     [', sun, ', 1.1],
     ['sky', 1.4641000000000006],
     ['.', 1.1]]
404
    """
A
AUTOMATIC 已提交
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    res = []
    round_brackets = []
    square_brackets = []

    round_bracket_multiplier = 1.1
    square_bracket_multiplier = 1 / 1.1

    def multiply_range(start_position, multiplier):
        for p in range(start_position, len(res)):
            res[p][1] *= multiplier

    for m in re_attention.finditer(text):
        text = m.group(0)
        weight = m.group(1)

        if text.startswith('\\'):
            res.append([text[1:], 1.0])
        elif text == '(':
            round_brackets.append(len(res))
        elif text == '[':
            square_brackets.append(len(res))
427
        elif weight is not None and round_brackets:
428
            multiply_range(round_brackets.pop(), float(weight))
429
        elif text == ')' and round_brackets:
430
            multiply_range(round_brackets.pop(), round_bracket_multiplier)
431
        elif text == ']' and square_brackets:
432 433
            multiply_range(square_brackets.pop(), square_bracket_multiplier)
        else:
434 435 436 437 438
            parts = re.split(re_break, text)
            for i, part in enumerate(parts):
                if i > 0:
                    res.append(["BREAK", -1])
                res.append([part, 1.0])
439 440 441 442 443 444 445

    for pos in round_brackets:
        multiply_range(pos, round_bracket_multiplier)

    for pos in square_brackets:
        multiply_range(pos, square_bracket_multiplier)

A
AUTOMATIC 已提交
446 447 448
    if len(res) == 0:
        res = [["", 1.0]]

449 450 451 452 453 454 455 456 457
    # merge runs of identical weights
    i = 0
    while i + 1 < len(res):
        if res[i][1] == res[i + 1][1]:
            res[i][0] += res[i + 1][0]
            res.pop(i + 1)
        else:
            i += 1

458
    return res
459 460 461 462 463 464

if __name__ == "__main__":
    import doctest
    doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
else:
    import torch  # doctest faster