rashidvyro commited on
Commit
d8e2f70
·
1 Parent(s): aadb993

Upload 5 files

Browse files
image_processor.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import List, Optional, Union
3
+
4
+ import numpy as np
5
+ import PIL
6
+ import torch
7
+ from PIL import Image
8
+
9
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
10
+ from diffusers.utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
11
+
12
+
13
+ class VaeImageProcessor(ConfigMixin):
14
+ """
15
+ Image Processor for VAE
16
+
17
+ Args:
18
+ do_resize (`bool`, *optional*, defaults to `True`):
19
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
20
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
21
+ VAE scale factor. If `do_resize` is True, the image will be automatically resized to multiples of this
22
+ factor.
23
+ resample (`str`, *optional*, defaults to `lanczos`):
24
+ Resampling filter to use when resizing the image.
25
+ do_normalize (`bool`, *optional*, defaults to `True`):
26
+ Whether to normalize the image to [-1,1]
27
+ """
28
+
29
+ config_name = CONFIG_NAME
30
+
31
+ @register_to_config
32
+ def __init__(
33
+ self,
34
+ do_resize: bool = True,
35
+ vae_scale_factor: int = 8,
36
+ resample: str = "lanczos",
37
+ do_normalize: bool = True,
38
+ ):
39
+ super().__init__()
40
+
41
+ @staticmethod
42
+ def numpy_to_pil(images):
43
+ """
44
+ Convert a numpy image or a batch of images to a PIL image.
45
+ """
46
+ if images.ndim == 3:
47
+ images = images[None, ...]
48
+ images = (images * 255).round().astype("uint8")
49
+ if images.shape[-1] == 1:
50
+ # special case for grayscale (single channel) images
51
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
52
+ else:
53
+ pil_images = [Image.fromarray(image) for image in images]
54
+
55
+ return pil_images
56
+
57
+ @staticmethod
58
+ def numpy_to_pt(images):
59
+ """
60
+ Convert a numpy image to a pytorch tensor
61
+ """
62
+ if images.ndim == 3:
63
+ images = images[..., None]
64
+
65
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
66
+ return images
67
+
68
+ @staticmethod
69
+ def pt_to_numpy(images):
70
+ """
71
+ Convert a pytorch tensor to a numpy image
72
+ """
73
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
74
+ return images
75
+
76
+ @staticmethod
77
+ def normalize(images):
78
+ """
79
+ Normalize an image array to [-1,1]
80
+ """
81
+ return 2.0 * images - 1.0
82
+
83
+ @staticmethod
84
+ def denormalize(images):
85
+ """
86
+ Denormalize an image array to [0,1]
87
+ """
88
+ return (images / 2 + 0.5).clamp(0, 1)
89
+
90
+ def resize(self, images: PIL.Image.Image) -> PIL.Image.Image:
91
+ """
92
+ Resize a PIL image. Both height and width will be downscaled to the next integer multiple of `vae_scale_factor`
93
+ """
94
+ w, h = images.size
95
+ w, h = (x - x % self.config.vae_scale_factor for x in (w, h)) # resize to integer multiple of vae_scale_factor
96
+ images = images.resize((w, h), resample=PIL_INTERPOLATION[self.config.resample])
97
+ return images
98
+
99
+ def preprocess(
100
+ self,
101
+ image: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
102
+ ) -> torch.Tensor:
103
+ """
104
+ Preprocess the image input, accepted formats are PIL images, numpy arrays or pytorch tensors"
105
+ """
106
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
107
+ if isinstance(image, supported_formats):
108
+ image = [image]
109
+ elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
110
+ raise ValueError(
111
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
112
+ )
113
+
114
+ if isinstance(image[0], PIL.Image.Image):
115
+ if self.config.do_resize:
116
+ image = [self.resize(i) for i in image]
117
+ image = [np.array(i).astype(np.float32) / 255.0 for i in image]
118
+ image = np.stack(image, axis=0) # to np
119
+ image = self.numpy_to_pt(image) # to pt
120
+
121
+ elif isinstance(image[0], np.ndarray):
122
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
123
+ image = self.numpy_to_pt(image)
124
+ _, _, height, width = image.shape
125
+ if self.config.do_resize and (
126
+ height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
127
+ ):
128
+ raise ValueError(
129
+ f"Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"
130
+ f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"
131
+ )
132
+
133
+ elif isinstance(image[0], torch.Tensor):
134
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
135
+ _, _, height, width = image.shape
136
+ if self.config.do_resize and (
137
+ height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
138
+ ):
139
+ raise ValueError(
140
+ f"Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"
141
+ f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"
142
+ )
143
+
144
+ # expected range [0,1], normalize to [-1,1]
145
+ do_normalize = self.config.do_normalize
146
+ if image.min() < 0:
147
+ warnings.warn(
148
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
149
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
150
+ FutureWarning,
151
+ )
152
+ do_normalize = False
153
+
154
+ if do_normalize:
155
+ image = self.normalize(image)
156
+
157
+ return image
158
+
159
+ def postprocess(
160
+ self,
161
+ image: torch.FloatTensor,
162
+ output_type: str = "pil",
163
+ do_denormalize: Optional[List[bool]] = None,
164
+ ):
165
+ if not isinstance(image, torch.Tensor):
166
+ raise ValueError(
167
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
168
+ )
169
+ if output_type not in ["latent", "pt", "np", "pil"]:
170
+ deprecation_message = (
171
+ f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
172
+ "`pil`, `np`, `pt`, `latent`"
173
+ )
174
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
175
+ output_type = "np"
176
+
177
+ if output_type == "latent":
178
+ return image
179
+
180
+ if do_denormalize is None:
181
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
182
+
183
+ image = torch.stack(
184
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
185
+ )
186
+
187
+ if output_type == "pt":
188
+ return image
189
+
190
+ image = self.pt_to_numpy(image)
191
+
192
+ if output_type == "np":
193
+ return image
194
+
195
+ if output_type == "pil":
196
+ return self.numpy_to_pil(image)
prompt_parser.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections import namedtuple
3
+ from typing import List
4
+ import lark
5
+
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
+
14
+ schedule_parser = lark.Lark(r"""
15
+ !start: (prompt | /[][():]/+)*
16
+ prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)*
17
+ !emphasized: "(" prompt ")"
18
+ | "(" prompt ":" prompt ")"
19
+ | "[" prompt "]"
20
+ scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER "]"
21
+ alternate: "[" prompt ("|" prompt)+ "]"
22
+ WHITESPACE: /\s+/
23
+ plain: /([^\\\[\]():|]|\\.)+/
24
+ %import common.SIGNED_NUMBER -> NUMBER
25
+ """)
26
+
27
+ def get_learned_conditioning_prompt_schedules(prompts, steps):
28
+ """
29
+ >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
30
+ >>> g("test")
31
+ [[10, 'test']]
32
+ >>> g("a [b:3]")
33
+ [[3, 'a '], [10, 'a b']]
34
+ >>> g("a [b: 3]")
35
+ [[3, 'a '], [10, 'a b']]
36
+ >>> g("a [[[b]]:2]")
37
+ [[2, 'a '], [10, 'a [[b]]']]
38
+ >>> g("[(a:2):3]")
39
+ [[3, ''], [10, '(a:2)']]
40
+ >>> g("a [b : c : 1] d")
41
+ [[1, 'a b d'], [10, 'a c d']]
42
+ >>> g("a[b:[c:d:2]:1]e")
43
+ [[1, 'abe'], [2, 'ace'], [10, 'ade']]
44
+ >>> g("a [unbalanced")
45
+ [[10, 'a [unbalanced']]
46
+ >>> g("a [b:.5] c")
47
+ [[5, 'a c'], [10, 'a b c']]
48
+ >>> g("a [{b|d{:.5] c") # not handling this right now
49
+ [[5, 'a c'], [10, 'a {b|d{ c']]
50
+ >>> g("((a][:b:c [d:3]")
51
+ [[3, '((a][:b:c '], [10, '((a][:b:c d']]
52
+ >>> g("[a|(b:1.1)]")
53
+ [[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)']]
54
+ """
55
+
56
+ def collect_steps(steps, tree):
57
+ l = [steps]
58
+ class CollectSteps(lark.Visitor):
59
+ def scheduled(self, tree):
60
+ tree.children[-1] = float(tree.children[-1])
61
+ if tree.children[-1] < 1:
62
+ tree.children[-1] *= steps
63
+ tree.children[-1] = min(steps, int(tree.children[-1]))
64
+ l.append(tree.children[-1])
65
+ def alternate(self, tree):
66
+ l.extend(range(1, steps+1))
67
+ CollectSteps().visit(tree)
68
+ return sorted(set(l))
69
+
70
+ def at_step(step, tree):
71
+ class AtStep(lark.Transformer):
72
+ def scheduled(self, args):
73
+ before, after, _, when = args
74
+ yield before or () if step <= when else after
75
+ def alternate(self, args):
76
+ yield next(args[(step - 1)%len(args)])
77
+ def start(self, args):
78
+ def flatten(x):
79
+ if type(x) == str:
80
+ yield x
81
+ else:
82
+ for gen in x:
83
+ yield from flatten(gen)
84
+ return ''.join(flatten(args))
85
+ def plain(self, args):
86
+ yield args[0].value
87
+ def __default__(self, data, children, meta):
88
+ for child in children:
89
+ yield child
90
+ return AtStep().transform(tree)
91
+
92
+ def get_schedule(prompt):
93
+ try:
94
+ tree = schedule_parser.parse(prompt)
95
+ except lark.exceptions.LarkError as e:
96
+ if 0:
97
+ import traceback
98
+ traceback.print_exc()
99
+ return [[steps, prompt]]
100
+ return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
101
+
102
+ promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
103
+ return [promptdict[prompt] for prompt in prompts]
104
+
105
+
106
+ ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
107
+
108
+
109
+ def get_learned_conditioning(model, prompts, steps):
110
+ """converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning, specifying the comdition (cond),
111
+ and the sampling step at which this condition is to be replaced by the next one.
112
+
113
+ Input:
114
+ (model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20)
115
+
116
+ Output:
117
+ [
118
+ [
119
+ 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'))
120
+ ],
121
+ [
122
+ 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')),
123
+ 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'))
124
+ ]
125
+ ]
126
+ """
127
+ res = []
128
+
129
+ prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps)
130
+ cache = {}
131
+
132
+ for prompt, prompt_schedule in zip(prompts, prompt_schedules):
133
+
134
+ cached = cache.get(prompt, None)
135
+ if cached is not None:
136
+ res.append(cached)
137
+ continue
138
+
139
+ texts = [x[1] for x in prompt_schedule]
140
+ conds = [model.build_conditioning_tensor(text) for text in texts]
141
+
142
+ cond_schedule = []
143
+ for i, (end_at_step, text) in enumerate(prompt_schedule):
144
+ cond_schedule.append(ScheduledPromptConditioning(end_at_step, conds[i]))
145
+
146
+ cache[prompt] = cond_schedule
147
+ res.append(cond_schedule)
148
+
149
+ return res
150
+
151
+
152
+ re_AND = re.compile(r"\bAND\b")
153
+ re_weight = re.compile(r"^(.*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
154
+
155
+ def get_multicond_prompt_list(prompts):
156
+ res_indexes = []
157
+
158
+ prompt_flat_list = []
159
+ prompt_indexes = {}
160
+
161
+ for prompt in prompts:
162
+ subprompts = re_AND.split(prompt)
163
+
164
+ indexes = []
165
+ for subprompt in subprompts:
166
+ match = re_weight.search(subprompt)
167
+
168
+ text, weight = match.groups() if match is not None else (subprompt, 1.0)
169
+
170
+ weight = float(weight) if weight is not None else 1.0
171
+
172
+ index = prompt_indexes.get(text, None)
173
+ if index is None:
174
+ index = len(prompt_flat_list)
175
+ prompt_flat_list.append(text)
176
+ prompt_indexes[text] = index
177
+
178
+ indexes.append((index, weight))
179
+
180
+ res_indexes.append(indexes)
181
+
182
+ return res_indexes, prompt_flat_list, prompt_indexes
183
+
184
+
185
+ class ComposableScheduledPromptConditioning:
186
+ def __init__(self, schedules, weight=1.0):
187
+ self.schedules: List[ScheduledPromptConditioning] = schedules
188
+ self.weight: float = weight
189
+
190
+
191
+ class MulticondLearnedConditioning:
192
+ def __init__(self, shape, batch):
193
+ self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS
194
+ self.batch: List[List[ComposableScheduledPromptConditioning]] = batch
195
+
196
+ def get_multicond_learned_conditioning(model, prompts, steps) -> MulticondLearnedConditioning:
197
+ """same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt.
198
+ For each prompt, the list is obtained by splitting the prompt using the AND separator.
199
+
200
+ https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/
201
+ """
202
+
203
+ res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts)
204
+
205
+ learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps)
206
+
207
+ res = []
208
+ for indexes in res_indexes:
209
+ res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes])
210
+
211
+ return MulticondLearnedConditioning(shape=(len(prompts),), batch=res)
212
+
213
+
214
+ def reconstruct_cond_batch(c: List[List[ScheduledPromptConditioning]], current_step):
215
+ param = c[0][0].cond
216
+ res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype)
217
+ for i, cond_schedule in enumerate(c):
218
+ target_index = 0
219
+ for current, (end_at, cond) in enumerate(cond_schedule):
220
+ if current_step <= end_at:
221
+ target_index = current
222
+ break
223
+ res[i] = cond_schedule[target_index].cond
224
+
225
+ return res
226
+
227
+
228
+ def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
229
+ param = c.batch[0][0].schedules[0].cond
230
+
231
+ tensors = []
232
+ conds_list = []
233
+
234
+ for batch_no, composable_prompts in enumerate(c.batch):
235
+ conds_for_batch = []
236
+
237
+ for cond_index, composable_prompt in enumerate(composable_prompts):
238
+ target_index = 0
239
+ for current, (end_at, cond) in enumerate(composable_prompt.schedules):
240
+ if current_step <= end_at:
241
+ target_index = current
242
+ break
243
+
244
+ conds_for_batch.append((len(tensors), composable_prompt.weight))
245
+ tensors.append(composable_prompt.schedules[target_index].cond)
246
+
247
+ conds_list.append(conds_for_batch)
248
+
249
+ # if prompts have wildly different lengths above the limit we'll get tensors fo different shapes
250
+ # and won't be able to torch.stack them. So this fixes that.
251
+ token_count = max([x.shape[0] for x in tensors])
252
+ for i in range(len(tensors)):
253
+ if tensors[i].shape[0] != token_count:
254
+ last_vector = tensors[i][-1:]
255
+ last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1])
256
+ tensors[i] = torch.vstack([tensors[i], last_vector_repeated])
257
+
258
+ return conds_list, torch.stack(tensors).to(device=param.device, dtype=param.dtype)
259
+
260
+
261
+ re_attention = re.compile(r"""
262
+ \\\(|
263
+ \\\)|
264
+ \\\[|
265
+ \\]|
266
+ \\\\|
267
+ \\|
268
+ \(|
269
+ \[|
270
+ :([+-]?[.\d]+)\)|
271
+ \)|
272
+ ]|
273
+ [^\\()\[\]:]+|
274
+ :
275
+ """, re.X)
276
+
277
+ re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
278
+
279
+ def parse_prompt_attention(text):
280
+ """
281
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
282
+ Accepted tokens are:
283
+ (abc) - increases attention to abc by a multiplier of 1.1
284
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
285
+ [abc] - decreases attention to abc by a multiplier of 1.1
286
+ \( - literal character '('
287
+ \[ - literal character '['
288
+ \) - literal character ')'
289
+ \] - literal character ']'
290
+ \\ - literal character '\'
291
+ anything else - just text
292
+
293
+ >>> parse_prompt_attention('normal text')
294
+ [['normal text', 1.0]]
295
+ >>> parse_prompt_attention('an (important) word')
296
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
297
+ >>> parse_prompt_attention('(unbalanced')
298
+ [['unbalanced', 1.1]]
299
+ >>> parse_prompt_attention('\(literal\]')
300
+ [['(literal]', 1.0]]
301
+ >>> parse_prompt_attention('(unnecessary)(parens)')
302
+ [['unnecessaryparens', 1.1]]
303
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
304
+ [['a ', 1.0],
305
+ ['house', 1.5730000000000004],
306
+ [' ', 1.1],
307
+ ['on', 1.0],
308
+ [' a ', 1.1],
309
+ ['hill', 0.55],
310
+ [', sun, ', 1.1],
311
+ ['sky', 1.4641000000000006],
312
+ ['.', 1.1]]
313
+ """
314
+
315
+ res = []
316
+ round_brackets = []
317
+ square_brackets = []
318
+
319
+ round_bracket_multiplier = 1.1
320
+ square_bracket_multiplier = 1 / 1.1
321
+
322
+ def multiply_range(start_position, multiplier):
323
+ for p in range(start_position, len(res)):
324
+ res[p][1] *= multiplier
325
+
326
+ for m in re_attention.finditer(text):
327
+ text = m.group(0)
328
+ weight = m.group(1)
329
+
330
+ if text.startswith('\\'):
331
+ res.append([text[1:], 1.0])
332
+ elif text == '(':
333
+ round_brackets.append(len(res))
334
+ elif text == '[':
335
+ square_brackets.append(len(res))
336
+ elif weight is not None and len(round_brackets) > 0:
337
+ multiply_range(round_brackets.pop(), float(weight))
338
+ elif text == ')' and len(round_brackets) > 0:
339
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
340
+ elif text == ']' and len(square_brackets) > 0:
341
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
342
+ else:
343
+ parts = re.split(re_break, text)
344
+ for i, part in enumerate(parts):
345
+ if i > 0:
346
+ res.append(["BREAK", -1])
347
+ res.append([part, 1.0])
348
+
349
+ for pos in round_brackets:
350
+ multiply_range(pos, round_bracket_multiplier)
351
+
352
+ for pos in square_brackets:
353
+ multiply_range(pos, square_bracket_multiplier)
354
+
355
+ if len(res) == 0:
356
+ res = [["", 1.0]]
357
+
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
+
367
+ return res
368
+
369
+ if __name__ == "__main__":
370
+ import doctest
371
+ doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
372
+ else:
373
+ import torch # doctest faster
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compel==1.2.1
2
+ tokenizers==0.13.3
3
+ typing_extensions<4.6.0,>=3.6.6
4
+ diffusers==0.20.2
5
+ torch
6
+ tqdm==4.65.0
7
+ transformers==4.27.1
8
+ cachetools==5.3.1
9
+ dynamicprompts==0.27.0
10
+ numpy==1.24
11
+ lark==1.1.5
12
+ accelerate==0.21.0
stable_diffusion_custom_v4_1.py ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from diffusers import StableDiffusionPipeline
3
+ # from diffusers.schedulers.scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
4
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput, AutoencoderKL, CLIPTextModel, CLIPTokenizer, UNet2DConditionModel, KarrasDiffusionSchedulers, StableDiffusionSafetyChecker, CLIPImageProcessor
5
+ from compel import Compel
6
+ from tokenizer_util import TextualInversionLoaderMixin, MultiTokenCLIPTokenizer
7
+ import torch
8
+ from typing import Any, Callable, Dict, List, Optional, Union
9
+ from dynamicprompts.generators import RandomPromptGenerator
10
+ import time
11
+ from compel import Compel
12
+ from prompt_parser import ScheduledPromptConditioning
13
+ from prompt_parser import get_learned_conditioning_prompt_schedules
14
+ from dynamicprompts.generators import RandomPromptGenerator
15
+ import tqdm
16
+ from cachetools import LRUCache
17
+ from image_processor import VaeImageProcessor
18
+
19
+
20
+ class CustomStableDiffusionPipeline4_1(TextualInversionLoaderMixin, StableDiffusionPipeline):
21
+ def __init__(
22
+ self,
23
+ vae: AutoencoderKL,
24
+ text_encoder: CLIPTextModel,
25
+ tokenizer: CLIPTokenizer,
26
+ unet: UNet2DConditionModel,
27
+ scheduler: KarrasDiffusionSchedulers,
28
+ safety_checker: StableDiffusionSafetyChecker,
29
+ feature_extractor: CLIPImageProcessor,
30
+ requires_safety_checker: bool = True,
31
+ prompt_cache_size: int = 1024,
32
+ prompt_cache_ttl: int = 60 * 2,
33
+ ) -> None:
34
+ super().__init__(vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, scheduler=scheduler,
35
+ safety_checker=safety_checker, feature_extractor=feature_extractor, requires_safety_checker=requires_safety_checker)
36
+
37
+ self.vae_scale_factor = 2 ** (
38
+ len(self.vae.config.block_out_channels) - 1)
39
+ self.image_processor = VaeImageProcessor(
40
+ vae_scale_factor=self.vae_scale_factor)
41
+ self.register_to_config(
42
+ requires_safety_checker=requires_safety_checker)
43
+
44
+ self.compel = Compel(tokenizer=self.tokenizer,
45
+ text_encoder=self.text_encoder, truncate_long_prompts=False)
46
+ self.cache = LRUCache(maxsize=prompt_cache_size)
47
+
48
+ self.cached_uc = [None, None]
49
+ self.cached_c = [None, None]
50
+
51
+ self.prompt_handler = None
52
+
53
+ def build_scheduled_cond(self, prompt, steps, key):
54
+ prompt_schedule = get_learned_conditioning_prompt_schedules([prompt], steps)[
55
+ 0]
56
+
57
+ cached = self.cache.get(key, None)
58
+ if cached is not None:
59
+ return cached
60
+
61
+ texts = [x[1] for x in prompt_schedule]
62
+ conds = [self.compel.build_conditioning_tensor(
63
+ text).to('cpu') for text in texts]
64
+
65
+ cond_schedule = []
66
+ for i, s in enumerate(prompt_schedule):
67
+ cond_schedule.append(ScheduledPromptConditioning(s[0], conds[i]))
68
+
69
+ self.cache[key] = cond_schedule
70
+ return cond_schedule
71
+
72
+ def initialize_magic_prompt_cache(self, pos_prompt_template: str, plain_prompt_template: str, neg_prompt_template: str, num_to_generate: int, steps: int):
73
+ r"""
74
+ Initializes the magic prompt cache for the forward pass.
75
+ Must be called immedaitely after Compel is loaded and embeds are initalized.
76
+ """
77
+ rpg = RandomPromptGenerator(ignore_whitespace=True, seed=555)
78
+ positive_prompts = rpg.generate(
79
+ template=pos_prompt_template, num_images=num_to_generate)
80
+ scheduled_conds = []
81
+ with torch.no_grad():
82
+ cache = {}
83
+ for i in tqdm.tqdm(range(len(positive_prompts))):
84
+ scheduled_conds.append(self.build_scheduled_cond(
85
+ positive_prompts[i], steps, cache))
86
+
87
+ plain_scheduled_cond = self.build_scheduled_cond(
88
+ plain_prompt_template, steps, cache)
89
+
90
+ scheduled_uncond = self.build_scheduled_cond(
91
+ neg_prompt_template, steps, cache)
92
+
93
+ self.scheduled_conds = scheduled_conds
94
+ self.plain_scheduled_cond = plain_scheduled_cond
95
+ self.scheduled_uncond = scheduled_uncond
96
+
97
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
98
+ r"""
99
+ Encodes the prompt into text encoder hidden states.
100
+
101
+ Args:
102
+ prompt (`str` or `list(int)`):
103
+ prompt to be encoded
104
+ device: (`torch.device`):
105
+ torch device
106
+ num_images_per_prompt (`int`):
107
+ number of images that should be generated per prompt
108
+ do_classifier_free_guidance (`bool`):
109
+ whether to use classifier free guidance or not
110
+ negative_prompt (`str` or `List[str]`):
111
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
112
+ if `guidance_scale` is less than `1`).
113
+ """
114
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
115
+
116
+ text_inputs = self.tokenizer(
117
+ prompt,
118
+ padding="max_length",
119
+ max_length=self.tokenizer.model_max_length,
120
+ truncation=True,
121
+ return_tensors="np",
122
+ )
123
+ text_input_ids = text_inputs.input_ids
124
+ text_input_ids = torch.from_numpy(text_input_ids)
125
+ untruncated_ids = self.tokenizer(
126
+ prompt, padding="max_length", return_tensors="np").input_ids
127
+ untruncated_ids = torch.from_numpy(untruncated_ids)
128
+
129
+ if (
130
+ text_input_ids.shape == untruncated_ids.shape
131
+ and text_input_ids.numel() == untruncated_ids.numel()
132
+ and not torch.equal(text_input_ids, untruncated_ids)
133
+ ):
134
+ removed_text = self.tokenizer.batch_decode(
135
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1])
136
+ logger.warning(
137
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
138
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
139
+ )
140
+
141
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
142
+ attention_mask = text_inputs.attention_mask.to(device)
143
+ else:
144
+ attention_mask = None
145
+
146
+ text_embeddings = self.text_encoder(
147
+ text_input_ids.to(device), attention_mask=attention_mask)
148
+ text_embeddings = text_embeddings[0]
149
+
150
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
151
+ bs_embed, seq_len, _ = text_embeddings.shape
152
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
153
+ text_embeddings = text_embeddings.view(
154
+ bs_embed * num_images_per_prompt, seq_len, -1)
155
+
156
+ # get unconditional embeddings for classifier free guidance
157
+ if do_classifier_free_guidance:
158
+ uncond_tokens: List[str]
159
+ if negative_prompt is None:
160
+ uncond_tokens = [""] * batch_size
161
+ elif type(prompt) is not type(negative_prompt):
162
+ raise TypeError(
163
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
164
+ f" {type(prompt)}."
165
+ )
166
+ elif isinstance(negative_prompt, str):
167
+ uncond_tokens = [negative_prompt]
168
+ elif batch_size != len(negative_prompt):
169
+ raise ValueError(
170
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
171
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
172
+ " the batch size of `prompt`."
173
+ )
174
+ else:
175
+ uncond_tokens = negative_prompt
176
+
177
+ max_length = text_input_ids.shape[-1]
178
+ uncond_input = self.tokenizer(
179
+ uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="np",
180
+ )
181
+
182
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
183
+ attention_mask = torch.from_numpy(
184
+ uncond_input.attention_mask).to(device)
185
+ else:
186
+ attention_mask = None
187
+
188
+ uncond_embeddings = self.text_encoder(
189
+ torch.from_numpy(uncond_input.input_ids).to(device), attention_mask=attention_mask,
190
+ )
191
+ uncond_embeddings = uncond_embeddings[0]
192
+
193
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
194
+ seq_len = uncond_embeddings.shape[1]
195
+ uncond_embeddings = uncond_embeddings.repeat(
196
+ 1, num_images_per_prompt, 1)
197
+ uncond_embeddings = uncond_embeddings.view(
198
+ batch_size * num_images_per_prompt, seq_len, -1)
199
+
200
+ # For classifier free guidance, we need to do two forward passes.
201
+ # Here we concatenate the unconditional and text embeddings into a single batch
202
+ # to avoid doing two forward passes
203
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
204
+
205
+ return text_embeddings
206
+
207
+ def _encode_promptv2(
208
+ self,
209
+ prompt,
210
+ device,
211
+ num_images_per_prompt,
212
+ do_classifier_free_guidance,
213
+ negative_prompt=None,
214
+ prompt_embeds: Optional[torch.FloatTensor] = None,
215
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
216
+ ):
217
+
218
+ if prompt is not None and isinstance(prompt, str):
219
+ batch_size = 1
220
+ elif prompt is not None and isinstance(prompt, list):
221
+ batch_size = len(prompt)
222
+ else:
223
+ batch_size = prompt_embeds.shape[0]
224
+
225
+ if prompt_embeds is None:
226
+ text_inputs = self.tokenizer(
227
+ prompt,
228
+ padding="max_length",
229
+ max_length=self.tokenizer.model_max_length,
230
+ truncation=True,
231
+ return_tensors="pt",
232
+ )
233
+ text_input_ids = text_inputs.input_ids
234
+ untruncated_ids = self.tokenizer(
235
+ prompt, padding="longest", return_tensors="pt").input_ids
236
+
237
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
238
+ text_input_ids, untruncated_ids
239
+ ):
240
+ removed_text = self.tokenizer.batch_decode(
241
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]
242
+ )
243
+
244
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
245
+ attention_mask = text_inputs.attention_mask.to(device)
246
+ else:
247
+ attention_mask = None
248
+
249
+ prompt_embeds = self.text_encoder(
250
+ text_input_ids.to(device),
251
+ attention_mask=attention_mask,
252
+ )
253
+ prompt_embeds = prompt_embeds[0]
254
+
255
+ prompt_embeds = prompt_embeds.to(
256
+ dtype=self.text_encoder.dtype, device=device)
257
+
258
+ bs_embed, seq_len, _ = prompt_embeds.shape
259
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
260
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
261
+ prompt_embeds = prompt_embeds.view(
262
+ bs_embed * num_images_per_prompt, seq_len, -1)
263
+
264
+ # get unconditional embeddings for classifier free guidance
265
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
266
+ uncond_tokens: List[str]
267
+ if negative_prompt is None:
268
+ uncond_tokens = [""] * batch_size
269
+ elif type(prompt) is not type(negative_prompt):
270
+ raise TypeError(
271
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
272
+ f" {type(prompt)}."
273
+ )
274
+ elif isinstance(negative_prompt, str):
275
+ uncond_tokens = [negative_prompt]
276
+ elif batch_size != len(negative_prompt):
277
+ raise ValueError(
278
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
279
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
280
+ " the batch size of `prompt`."
281
+ )
282
+ else:
283
+ uncond_tokens = negative_prompt
284
+
285
+ max_length = prompt_embeds.shape[1]
286
+ uncond_input = self.tokenizer(
287
+ uncond_tokens,
288
+ padding="max_length",
289
+ max_length=max_length,
290
+ truncation=True,
291
+ return_tensors="pt",
292
+ )
293
+
294
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
295
+ attention_mask = uncond_input.attention_mask.to(device)
296
+ else:
297
+ attention_mask = None
298
+
299
+ negative_prompt_embeds = self.text_encoder(
300
+ uncond_input.input_ids.to(device),
301
+ attention_mask=attention_mask,
302
+ )
303
+ negative_prompt_embeds = negative_prompt_embeds[0]
304
+
305
+ if do_classifier_free_guidance:
306
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
307
+ seq_len = negative_prompt_embeds.shape[1]
308
+
309
+ negative_prompt_embeds = negative_prompt_embeds.to(
310
+ dtype=self.text_encoder.dtype, device=device)
311
+
312
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
313
+ 1, num_images_per_prompt, 1)
314
+ negative_prompt_embeds = negative_prompt_embeds.view(
315
+ batch_size * num_images_per_prompt, seq_len, -1)
316
+
317
+ negative_prompt_embeds, prompt_embeds = self.compel.pad_conditioning_tensors_to_same_length(
318
+ [negative_prompt_embeds, prompt_embeds])
319
+ # For classifier free guidance, we need to do two forward passes.
320
+ # Here we concatenate the unconditional and text embeddings into a single batch
321
+ # to avoid doing two forward passes
322
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
323
+
324
+ return prompt_embeds
325
+
326
+ def _pyramid_noise_like(self, noise, device, seed, iterations=6, discount=0.4):
327
+ gen = torch.manual_seed(seed)
328
+ # EDIT: w and h get over-written, rename for a different variant!
329
+ b, c, w, h = noise.shape
330
+ u = torch.nn.Upsample(size=(w, h), mode="bilinear").to(device)
331
+ for i in range(iterations):
332
+ r = random.random() * 2 + 2 # Rather than always going 2x,
333
+ wn, hn = max(1, int(w / (r**i))), max(1, int(h / (r**i)))
334
+ noise += u(torch.randn(b, c, wn, hn,
335
+ generator=gen).to(device)) * discount**i
336
+ if wn == 1 or hn == 1:
337
+ break # Lowest resolution is 1x1
338
+ return noise / noise.std() # Scaled back to roughly unit variance
339
+
340
+ @torch.no_grad()
341
+ def inferV4(
342
+ self,
343
+ prompt: Union[str, List[str]],
344
+ height: Optional[int] = None,
345
+ width: Optional[int] = None,
346
+ num_inference_steps: int = 50,
347
+ guidance_scale: float = 7.5,
348
+ negative_prompt: Optional[Union[str, List[str]]] = None,
349
+ num_images_per_prompt: Optional[int] = 1,
350
+ eta: float = 0.0,
351
+ generator: Optional[torch.Generator] = None,
352
+ latents: Optional[torch.FloatTensor] = None,
353
+ output_type: Optional[str] = "pil",
354
+ return_dict: bool = True,
355
+ callback: Optional[Callable[[
356
+ int, int, torch.FloatTensor], None]] = None,
357
+ callback_steps: Optional[int] = 1,
358
+ compile_unet: bool = True,
359
+ compile_vae: bool = True,
360
+ compile_tenc: bool = True,
361
+ max_tokens=0,
362
+ seed=-1,
363
+ flags=[],
364
+ og_prompt=None,
365
+ og_neg_prompt=None,
366
+ disc=0.4,
367
+ iter=6,
368
+ pyramid=0, # disabled by default unless specified
369
+ ):
370
+ r"""
371
+ Function invoked when calling the pipeline for generation.
372
+
373
+ Args:
374
+ prompt (`str` or `List[str]`):
375
+ The prompt or prompts to guide the image generation.
376
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
377
+ The height in pixels of the generated image.
378
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
379
+ The width in pixels of the generated image.
380
+ num_inference_steps (`int`, *optional*, defaults to 50):
381
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
382
+ expense of slower inference.
383
+ guidance_scale (`float`, *optional*, defaults to 7.5):
384
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
385
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
386
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
387
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
388
+ usually at the expense of lower image quality.
389
+ negative_prompt (`str` or `List[str]`, *optional*):
390
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
391
+ if `guidance_scale` is less than `1`).
392
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
393
+ The number of images to generate per prompt.
394
+ eta (`float`, *optional*, defaults to 0.0):
395
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
396
+ [`schedulers.DDIMScheduler`], will be ignored for others.
397
+ generator (`torch.Generator`, *optional*):
398
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
399
+ deterministic.
400
+ latents (`torch.FloatTensor`, *optional*):
401
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
402
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
403
+ tensor will ge generated by sampling using the supplied random `generator`.
404
+ output_type (`str`, *optional*, defaults to `"pil"`):
405
+ The output format of the generate image. Choose between
406
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
407
+ return_dict (`bool`, *optional*, defaults to `True`):
408
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
409
+ plain tuple.
410
+ callback (`Callable`, *optional*):
411
+ A function that will be called every `callback_steps` steps during inference. The function will be
412
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
413
+ callback_steps (`int`, *optional*, defaults to 1):
414
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
415
+ called at every step.
416
+
417
+ Returns:
418
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
419
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
420
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
421
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
422
+ (nsfw) content, according to the `safety_checker`.
423
+ """
424
+ # 0. Default height and width to unet
425
+
426
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
427
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
428
+
429
+ self.check_inputs(prompt, height, width, callback_steps)
430
+ if negative_prompt == None:
431
+ negative_prompt = ['']
432
+ # 2. Define call parameters
433
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
434
+ device = self._execution_device
435
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
436
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
437
+ # corresponds to doing no classifier free guidance.
438
+ do_classifier_free_guidance = guidance_scale > 1.0
439
+
440
+ # # 3. Encode input prompt
441
+
442
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
443
+ timesteps = self.scheduler.timesteps
444
+
445
+ # Cache key for flags
446
+ plain = "plain" in flags
447
+ flair = None
448
+ for flag in flags:
449
+ if "flair" in flag:
450
+ flair = flag
451
+ break
452
+
453
+ with torch.no_grad():
454
+ c_time = time.time()
455
+ user_cond = self.build_scheduled_cond(
456
+ prompt[0], num_inference_steps, ('pos', og_prompt, seed, plain, flair))
457
+ c_time = time.time()
458
+ user_uncond = self.build_scheduled_cond(
459
+ negative_prompt[0], num_inference_steps, ('neg', negative_prompt[0], 0))
460
+
461
+ c = []
462
+ c.extend(user_cond)
463
+ uc = []
464
+ uc.extend(user_uncond)
465
+ max_token_count = 0
466
+
467
+ for cond in uc:
468
+ if cond.cond.shape[1] > max_token_count:
469
+ max_token_count = cond.cond.shape[1]
470
+ for cond in c:
471
+ if cond.cond.shape[1] > max_token_count:
472
+ max_token_count = cond.cond.shape[1]
473
+
474
+ def pad_tensor(conditionings: List[ScheduledPromptConditioning], max_token_count: int) -> List[ScheduledPromptConditioning]:
475
+
476
+ c0_shape = conditionings[0].cond.shape
477
+ if not all([len(c.cond.shape) == len(c0_shape) for c in conditionings]):
478
+ raise ValueError(
479
+ "Conditioning tensors must all have either 2 dimensions (unbatched) or 3 dimensions (batched)")
480
+
481
+ if len(c0_shape) == 2:
482
+ # need to be unsqueezed
483
+ for c in conditionings:
484
+ c.cond = c.cond.unsqueeze(0)
485
+ c0_shape = conditionings[0].cond.shape
486
+ if len(c0_shape) != 3:
487
+ raise ValueError(
488
+ f"All conditioning tensors must have the same number of dimensions (2 or 3)")
489
+
490
+ if not all([c.cond.shape[0] == c0_shape[0] and c.cond.shape[2] == c0_shape[2] for c in conditionings]):
491
+ raise ValueError(
492
+ f"All conditioning tensors must have the same batch size ({c0_shape[0]}) and number of embeddings per token ({c0_shape[1]}")
493
+
494
+ # if necessary, pad shorter tensors out with an emptystring tensor
495
+ empty_z = torch.cat(
496
+ [self.compel.build_conditioning_tensor("")] * c0_shape[0])
497
+ for i, c in enumerate(conditionings):
498
+ cond = c.cond.to(self.device)
499
+ while cond.shape[1] < max_token_count:
500
+ cond = torch.cat([cond, empty_z], dim=1)
501
+ conditionings[i] = ScheduledPromptConditioning(
502
+ c.end_at_step, cond)
503
+ return conditionings
504
+
505
+ uc = pad_tensor(uc, max_token_count)
506
+ c = pad_tensor(c, max_token_count)
507
+
508
+ next_uc = uc.pop(0)
509
+ next_c = c.pop(0)
510
+ prompt_embeds = None
511
+ new_embeds = True
512
+ embed_per_step = []
513
+ for i in range(len(timesteps)):
514
+ if i > next_uc.end_at_step:
515
+ next_uc = uc.pop(0)
516
+ new_embeds = True
517
+ if i > next_c.end_at_step:
518
+ next_c = c.pop(0)
519
+ new_embeds = True
520
+
521
+ if new_embeds:
522
+ negative_prompt_embeds, prompt_embeds = self.compel.pad_conditioning_tensors_to_same_length([
523
+ next_uc.cond, next_c.cond])
524
+ prompt_embeds = torch.cat(
525
+ [negative_prompt_embeds, prompt_embeds])
526
+ new_embeds = False
527
+
528
+ embed_per_step.append(prompt_embeds)
529
+
530
+ # 5. Prepare latent variables
531
+ num_channels_latents = self.unet.in_channels
532
+ latents = self.prepare_latents(
533
+ batch_size * num_images_per_prompt,
534
+ num_channels_latents,
535
+ height,
536
+ width,
537
+ prompt_embeds.dtype,
538
+ device,
539
+ generator,
540
+ latents,
541
+ )
542
+
543
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
544
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
545
+
546
+ # 7. Denoising loop
547
+ num_warmup_steps = len(timesteps) - \
548
+ num_inference_steps * self.scheduler.order
549
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
550
+ for i, t in enumerate(timesteps):
551
+ # expand the latents if we are doing classifier free guidance
552
+ latent_model_input = torch.cat(
553
+ [latents] * 2) if do_classifier_free_guidance else latents
554
+ latent_model_input = self.scheduler.scale_model_input(
555
+ latent_model_input, t)
556
+
557
+ prompt_embeds = embed_per_step[i]
558
+ # predict the noise residual
559
+
560
+ noise_pred = self.unet(
561
+ latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
562
+
563
+ # perform guidance
564
+ if do_classifier_free_guidance:
565
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
566
+ noise_pred = noise_pred_uncond + guidance_scale * \
567
+ (noise_pred_text - noise_pred_uncond)
568
+
569
+ if (i < pyramid*num_inference_steps):
570
+ noise_pred = self._pyramid_noise_like(
571
+ noise_pred, device, seed, iterations=iter, discount=disc)
572
+
573
+ # compute the previous noisy sample x_t -> x_t-1
574
+ latents = self.scheduler.step(
575
+ noise_pred, t, latents, **extra_step_kwargs).prev_sample
576
+
577
+ # call the callback, if provided
578
+ if (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0:
579
+ progress_bar.update()
580
+ if callback is not None and i % callback_steps == 0:
581
+ callback(i, t, latents)
582
+
583
+ if not output_type == "latent":
584
+ image = self.vae.decode(
585
+ latents / self.vae.config.scaling_factor, return_dict=False)[0]
586
+ image, has_nsfw_concept = self.run_safety_checker(
587
+ image, device, prompt_embeds.dtype)
588
+ else:
589
+ image = latents
590
+ has_nsfw_concept = None
591
+
592
+ if has_nsfw_concept is None:
593
+ do_denormalize = [True] * image.shape[0]
594
+ else:
595
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
596
+
597
+ image = self.image_processor.postprocess(
598
+ image, output_type=output_type, do_denormalize=do_denormalize)
599
+
600
+ # Offload last model to CPU
601
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
602
+ self.final_offload_hook.offload()
603
+
604
+ if not return_dict:
605
+ return (image, has_nsfw_concept)
606
+
607
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
608
+
609
+ @torch.no_grad()
610
+ def inferPipe(
611
+ self,
612
+ prompt: Union[str, List[str]] = None,
613
+ height: Optional[int] = None,
614
+ width: Optional[int] = None,
615
+ num_inference_steps: int = 50,
616
+ guidance_scale: float = 7.5,
617
+ negative_prompt: Optional[Union[str, List[str]]] = None,
618
+ num_images_per_prompt: Optional[int] = 1,
619
+ eta: float = 0.0,
620
+ generator: Optional[Union[torch.Generator,
621
+ List[torch.Generator]]] = None,
622
+ latents: Optional[torch.FloatTensor] = None,
623
+ prompt_embeds: Optional[torch.FloatTensor] = None,
624
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
625
+ output_type: Optional[str] = "pil",
626
+ return_dict: bool = True,
627
+ callback: Optional[Callable[[
628
+ int, int, torch.FloatTensor], None]] = None,
629
+ callback_steps: int = 1,
630
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
631
+ ):
632
+ r"""
633
+ Function invoked when calling the pipeline for generation.
634
+
635
+ Args:
636
+ prompt (`str` or `List[str]`, *optional*):
637
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
638
+ instead.
639
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
640
+ The height in pixels of the generated image.
641
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
642
+ The width in pixels of the generated image.
643
+ num_inference_steps (`int`, *optional*, defaults to 50):
644
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
645
+ expense of slower inference.
646
+ guidance_scale (`float`, *optional*, defaults to 7.5):
647
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
648
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
649
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
650
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
651
+ usually at the expense of lower image quality.
652
+ negative_prompt (`str` or `List[str]`, *optional*):
653
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
654
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
655
+ less than `1`).
656
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
657
+ The number of images to generate per prompt.
658
+ eta (`float`, *optional*, defaults to 0.0):
659
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
660
+ [`schedulers.DDIMScheduler`], will be ignored for others.
661
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
662
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
663
+ to make generation deterministic.
664
+ latents (`torch.FloatTensor`, *optional*):
665
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
666
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
667
+ tensor will ge generated by sampling using the supplied random `generator`.
668
+ prompt_embeds (`torch.FloatTensor`, *optional*):
669
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
670
+ provided, text embeddings will be generated from `prompt` input argument.
671
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
672
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
673
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
674
+ argument.
675
+ output_type (`str`, *optional*, defaults to `"pil"`):
676
+ The output format of the generate image. Choose between
677
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
678
+ return_dict (`bool`, *optional*, defaults to `True`):
679
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
680
+ plain tuple.
681
+ callback (`Callable`, *optional*):
682
+ A function that will be called every `callback_steps` steps during inference. The function will be
683
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
684
+ callback_steps (`int`, *optional*, defaults to 1):
685
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
686
+ called at every step.
687
+ cross_attention_kwargs (`dict`, *optional*):
688
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
689
+ `self.processor` in
690
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
691
+
692
+ Examples:
693
+
694
+ Returns:
695
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
696
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
697
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
698
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
699
+ (nsfw) content, according to the `safety_checker`.
700
+ """
701
+ # 0. Default height and width to unet
702
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
703
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
704
+
705
+ # 1. Check inputs. Raise error if not correct
706
+ self.check_inputs(prompt, height, width, callback_steps)
707
+
708
+ # 2. Define call parameters
709
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
710
+ device = self._execution_device
711
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
712
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
713
+ # corresponds to doing no classifier free guidance.
714
+ do_classifier_free_guidance = guidance_scale > 1.0
715
+
716
+ # 3. Encode input prompt
717
+ text_embeddings = self._encode_prompt(
718
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
719
+ )
720
+
721
+ # 4. Prepare timesteps
722
+ self.scheduler.set_timesteps(num_inference_steps)
723
+ timesteps = self.scheduler.timesteps
724
+
725
+ # 5. Prepare latent variables
726
+ num_channels_latents = self.unet.in_channels
727
+ latents = self.prepare_latents(
728
+ batch_size * num_images_per_prompt,
729
+ num_channels_latents,
730
+ height,
731
+ width,
732
+ text_embeddings.dtype,
733
+ device,
734
+ generator,
735
+ latents,
736
+ )
737
+
738
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
739
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
740
+
741
+ # 7. Denoising loop
742
+ num_warmup_steps = len(timesteps) - \
743
+ num_inference_steps * self.scheduler.order
744
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
745
+ for i, t in enumerate(timesteps):
746
+ # expand the latents if we are doing classifier free guidance
747
+ latent_model_input = torch.cat(
748
+ [latents] * 2) if do_classifier_free_guidance else latents
749
+ latent_model_input = self.scheduler.scale_model_input(
750
+ latent_model_input, t)
751
+
752
+ noise_pred = self.unet(
753
+ latent_model_input, t, encoder_hidden_states=text_embeddings).sample
754
+
755
+ # perform guidance
756
+ if do_classifier_free_guidance:
757
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
758
+ noise_pred = noise_pred_uncond + guidance_scale * \
759
+ (noise_pred_text - noise_pred_uncond)
760
+
761
+ # compute the previous noisy sample x_t -> x_t-1
762
+ latents = self.scheduler.step(
763
+ noise_pred, t, latents, **extra_step_kwargs).prev_sample
764
+
765
+ # call the callback, if provided
766
+ if (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0:
767
+ progress_bar.update()
768
+ if callback is not None and i % callback_steps == 0:
769
+ callback(i, t, latents)
770
+
771
+ if not output_type == "latent":
772
+ image = self.vae.decode(
773
+ latents / self.vae.config.scaling_factor, return_dict=False)[0]
774
+ image, has_nsfw_concept = self.run_safety_checker(
775
+ image, device, text_embeddings.dtype)
776
+ else:
777
+ image = latents
778
+ has_nsfw_concept = None
779
+
780
+ if has_nsfw_concept is None:
781
+ do_denormalize = [True] * image.shape[0]
782
+ else:
783
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
784
+
785
+ image = self.image_processor.postprocess(
786
+ image, output_type=output_type, do_denormalize=do_denormalize)
787
+
788
+ # Offload last model to CPU
789
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
790
+ self.final_offload_hook.offload()
791
+
792
+ if not return_dict:
793
+ return (image, has_nsfw_concept)
794
+
795
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
tokenizer_util.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Callable, Dict, Optional, Union, List
3
+ from urllib.parse import urlparse
4
+ from transformers import PreTrainedModel, PreTrainedTokenizer, CLIPTokenizer
5
+ import copy
6
+ import random
7
+ from io import BytesIO
8
+ from compel.embeddings_provider import BaseTextualInversionManager
9
+
10
+ class TextualInversionLoaderMixin(BaseTextualInversionManager):
11
+ r"""
12
+ Mixin class for adding textual inversion tokens and embeddings to the tokenizer and text encoder with method:
13
+ - [`~TextualInversionLoaderMixin.load_textual_inversion_embeddings`]
14
+ - [`~TextualInversionLoaderMixin.add_textual_inversion_embedding`]
15
+ """
16
+
17
+ def load_textual_inversion_embeddings(
18
+ self,
19
+ embedding_path_dict_or_list: Union[Dict[str, str], List[Dict[str, str]]],
20
+ allow_replacement: bool = False,
21
+ ):
22
+ r"""
23
+ Loads textual inversion embeddings and adds them to the tokenizer's vocabulary and the text encoder's embeddings.
24
+ Arguments:
25
+ embeddings_path_dict_or_list (`Dict[str, str]` or `List[str]`):
26
+ Dictionary of token to embedding path or List of embedding paths to embedding dictionaries.
27
+ The dictionary must have the following keys:
28
+ - `token`: name of the token to be added to the tokenizers' vocabulary
29
+ - `embedding`: path to the embedding of the token to be added to the text encoder's embedding matrix
30
+ The list must contain paths to embedding dictionaries where the keys are the tokens and the
31
+ values are the embeddings (same as above dictionary definition).
32
+ allow_replacement (`bool`, *optional*, defaults to `False`):
33
+ Whether to allow replacement of existing tokens in the tokenizer's vocabulary. If `False`
34
+ and a token is already in the vocabulary, an error will be raised.
35
+ Returns:
36
+ None
37
+ """
38
+ # Validate that inheriting class instance contains required attributes
39
+ self._validate_method_call(self.load_textual_inversion_embeddings)
40
+
41
+ if isinstance(embedding_path_dict_or_list, dict):
42
+ for token, embedding_path in embedding_path_dict_or_list.items():
43
+
44
+ embedding_dict = torch.load(embedding_path, map_location=self.text_encoder.device)
45
+ embedding, is_multi_vec_token = self._extract_embedding_from_dict(embedding_dict)
46
+
47
+ self._validate_token_update(token, allow_replacement, is_multi_vec_token)
48
+ self.add_textual_inversion_embedding(token, embedding)
49
+ elif isinstance(embedding_path_dict_or_list, list):
50
+ for embedding_path in embedding_path_dict_or_list:
51
+ embedding_dict = torch.load(embedding_path, map_location=self.text_encoder.device)
52
+ token = self._extract_token_from_dict(embedding_dict)
53
+ embedding, is_multi_vec_token = self._extract_embedding_from_dict(embedding_dict)
54
+
55
+ self._validate_token_update(token, allow_replacement, is_multi_vec_token)
56
+ self.add_textual_inversion_embedding(token, embedding)
57
+ else:
58
+ raise ValueError(
59
+ f"Type {type(embedding_path_dict_or_list)} is invalid. The value passed to `embedding_path_dict_or_list` "
60
+ "must be a dictionary that maps a token to it's embedding file path "
61
+ "or a list of paths to embedding files containing embedding dictionaries."
62
+ )
63
+
64
+ def add_textual_inversion_embedding(self, token: str, embedding: torch.Tensor):
65
+ r"""
66
+ Adds a token to the tokenizer's vocabulary and an embedding to the text encoder's embedding matrix.
67
+ Arguments:
68
+ token (`str`):
69
+ The token to be added to the tokenizers' vocabulary
70
+ embedding (`torch.Tensor`):
71
+ The embedding of the token to be added to the text encoder's embedding matrix
72
+ Returns:
73
+ None
74
+ """
75
+ # NOTE: Not clear to me that we intend for this to be a public/exposed method.
76
+ # Validate that inheriting class instance contains required attributes
77
+ self._validate_method_call(self.load_textual_inversion_embeddings)
78
+
79
+ embedding = embedding.to(self.text_encoder.dtype)
80
+
81
+ if not isinstance(self.tokenizer, MultiTokenCLIPTokenizer):
82
+ if token in self.tokenizer.get_vocab():
83
+ # If user has allowed replacement and the token exists, we only need to
84
+ # extract the existing id and update the embedding
85
+ token_id = self.tokenizer.convert_tokens_to_ids(token)
86
+ self.text_encoder.get_input_embeddings().weight.data[token_id] = embedding
87
+ else:
88
+ # If the token does not exist, we add it to the tokenizer, then resize and update the
89
+ # text encoder acccordingly
90
+ self.tokenizer.add_tokens([token])
91
+
92
+ token_id = self.tokenizer.convert_tokens_to_ids(token)
93
+ self.text_encoder.resize_token_embeddings(len(self.tokenizer))
94
+ self.text_encoder.get_input_embeddings().weight.data[token_id] = embedding
95
+ else:
96
+ if token in self.tokenizer.token_map:
97
+ # If user has allowed replacement and the token exists, we need to
98
+ # remove all existing tokens associated with the old embbedding and
99
+ # upddate with the new ones
100
+ indices_to_remove = []
101
+ for token_to_remove in self.tokenizer.token_map[token]:
102
+ indices_to_remove.append(self.tokenizer.get_added_vocab()[token_to_remove])
103
+
104
+ # Remove old tokens from tokenizer
105
+ self.tokenizer.added_tokens_encoder.pop(token_to_remove)
106
+
107
+ # Convert indices to remove to tensor
108
+ indices_to_remove = torch.LongTensor(indices_to_remove)
109
+
110
+ # Remove old tokens from text encoder
111
+ token_embeds = self.text_encoder.get_input_embeddings().weight.data
112
+ indices_to_keep = torch.arange(0, token_embeds.shape[0])
113
+ indices_to_keep = indices_to_keep[indices_to_keep != indices_to_remove].squeeze()
114
+ token_embeds = token_embeds[indices_to_keep]
115
+
116
+ # Downsize text encoder
117
+ self.text_encoder.resize_token_embeddings(len(self.tokenizer))
118
+
119
+ # Remove token from map so MultiTokenCLIPTokenizer doesn't complain
120
+ # on update
121
+ self.tokenizer.token_map.pop(token)
122
+
123
+ # Update token with new embedding
124
+ embedding_dims = len(embedding.shape)
125
+ num_vec_per_token = 1 if embedding_dims == 1 else embedding.shape[0]
126
+
127
+ self.tokenizer.add_placeholder_tokens(token, num_vec_per_token=num_vec_per_token)
128
+ self.text_encoder.resize_token_embeddings(len(self.tokenizer))
129
+ token_ids = self.tokenizer.encode(token, add_special_tokens=False)
130
+
131
+ if embedding_dims > 1:
132
+ for i, token_id in enumerate(token_ids):
133
+ self.text_encoder.get_input_embeddings().weight.data[token_id] = embedding[i]
134
+ else:
135
+ self.text_encoder.get_input_embeddings().weight.data[token_ids] = embedding
136
+
137
+ def _extract_embedding_from_dict(self, embedding_dict: Dict[str, str]) -> torch.Tensor:
138
+ r"""
139
+ Extracts the embedding from the embedding dictionary.
140
+ Arguments:
141
+ embedding_dict (`Dict[str, str]`):
142
+ The embedding dictionary loaded from the embedding path
143
+ Returns:
144
+ embedding (`torch.Tensor`):
145
+ The embedding to be added to the text encoder's embedding matrix
146
+ is_multi_vec_token (`bool`):
147
+ Whether the embedding is a multi-vector token or not
148
+ """
149
+ is_multi_vec_token = False
150
+ # auto1111 embedding case
151
+ if "string_to_param" in embedding_dict:
152
+ embedding_dict = embedding_dict["string_to_param"]
153
+ embedding = embedding_dict["*"]
154
+ else:
155
+ embedding = list(embedding_dict.values())[0]
156
+
157
+ if len(embedding.shape) > 1:
158
+ # If the embedding has more than one dimension,
159
+ # We need to ensure the tokenizer is a MultiTokenTokenizer
160
+ # because there is branching logic that depends on that class
161
+ if not isinstance(self.tokenizer, MultiTokenCLIPTokenizer):
162
+ raise ValueError(
163
+ f"{self.__class__.__name__} requires `self.tokenizer` of type `MultiTokenCLIPTokenizer` for loading embeddings with more than one dimension."
164
+ )
165
+ is_multi_vec_token = True
166
+
167
+ return embedding, is_multi_vec_token
168
+
169
+ def _extract_token_from_dict(self, embedding_dict: Dict[str, str]) -> str:
170
+ r"""
171
+ Extracts the token from the embedding dictionary.
172
+ Arguments:
173
+ embedding_dict (`Dict[str, str]`):
174
+ The embedding dictionary loaded from the embedding path
175
+ Returns:
176
+ token (`str`):
177
+ The token to be added to the tokenizers' vocabulary
178
+ """
179
+ # auto1111 embedding case
180
+ if "string_to_param" in embedding_dict:
181
+ token = embedding_dict["name"]
182
+ return token
183
+
184
+ return list(embedding_dict.keys())[0]
185
+
186
+ def _validate_method_call(self, method: Callable):
187
+ r"""
188
+ Validates that the method is being called from a class instance that has the required attributes.
189
+ Arguments:
190
+ method (`function`):
191
+ The class's method being called
192
+ Raises:
193
+ ValueError:
194
+ If the method is being called from a class instance that does not have
195
+ the required attributes, the method will not be callable.
196
+ Returns:
197
+ None
198
+ """
199
+ if not hasattr(self, "tokenizer") or not isinstance(self.tokenizer, PreTrainedTokenizer):
200
+ raise ValueError(
201
+ f"{self.__class__.__name__} requires `self.tokenizer` of type `PreTrainedTokenizer` for calling `{method.__name__}`"
202
+ )
203
+
204
+ if not hasattr(self, "text_encoder") or not isinstance(self.text_encoder, PreTrainedModel):
205
+ raise ValueError(
206
+ f"{self.__class__.__name__} requires `self.text_encoder` of type `PreTrainedModel` for calling `{method.__name__}`"
207
+ )
208
+
209
+ def _validate_token_update(self, token, allow_replacement=False, is_multi_vec_token=False):
210
+ r"""Validates that the token is not already in the tokenizer's vocabulary.
211
+ Arguments:
212
+ token (`str`):
213
+ The token to be added to the tokenizers' vocabulary
214
+ allow_replacement (`bool`):
215
+ Whether to allow replacement of the token if it already exists in the tokenizer's vocabulary
216
+ is_multi_vec_token (`bool`):
217
+ Whether the embedding is a multi-vector token or not
218
+ Raises:
219
+ ValueError:
220
+ If the token is already in the tokenizer's vocabulary and `allow_replacement` is False.
221
+ Returns:
222
+ None
223
+ """
224
+ if (not is_multi_vec_token and token in self.tokenizer.get_vocab()) or (
225
+ is_multi_vec_token and token in self.tokenizer.token_map
226
+ ):
227
+ if allow_replacement:
228
+ print(
229
+ f"Token {token} already in tokenizer vocabulary. Overwriting existing token and embedding with the new one."
230
+ )
231
+ else:
232
+ raise ValueError(
233
+ f"Token {token} already in tokenizer vocabulary. Please choose a different token name."
234
+ )
235
+
236
+
237
+ def expand_textual_inversion_token_ids_if_necessary(self, token_ids: List[int]) -> List[int]:
238
+ pass
239
+
240
+ class MultiTokenCLIPTokenizer(CLIPTokenizer):
241
+ """Tokenizer for CLIP models that have multi-vector tokens."""
242
+
243
+ def __init__(self, *args, **kwargs):
244
+ super().__init__(*args, **kwargs)
245
+ self.token_map = {}
246
+
247
+ def add_placeholder_tokens(self, placeholder_token, *args, num_vec_per_token=1, **kwargs):
248
+ r"""Adds placeholder tokens to the tokenizer's vocabulary.
249
+ Arguments:
250
+ placeholder_token (`str`):
251
+ The placeholder token to be added to the tokenizers' vocabulary and token map.
252
+ num_vec_per_token (`int`):
253
+ The number of vectors per token. Defaults to 1.
254
+ *args:
255
+ The arguments to be passed to the tokenizer's `add_tokens` method.
256
+ **kwargs:
257
+ The keyword arguments to be passed to the tokenizer's `add_tokens` method.
258
+ Returns:
259
+ None
260
+ """
261
+ output = []
262
+ if num_vec_per_token == 1:
263
+ self.add_tokens(placeholder_token, *args, **kwargs)
264
+ output.append(placeholder_token)
265
+ else:
266
+ output = []
267
+ for i in range(num_vec_per_token):
268
+ ith_token = placeholder_token + f"_{i}"
269
+ self.add_tokens(ith_token, *args, **kwargs)
270
+ output.append(ith_token)
271
+ # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
272
+ for token in self.token_map:
273
+ if token in placeholder_token:
274
+ raise ValueError(
275
+ f"The tokenizer already has placeholder token {token} that can get confused with"
276
+ f" {placeholder_token}keep placeholder tokens independent"
277
+ )
278
+ self.token_map[placeholder_token] = output
279
+
280
+ def replace_placeholder_tokens_in_text(self, text, vector_shuffle=False, prop_tokens_to_load=1.0):
281
+ r"""Replaces placeholder tokens in text with the tokens in the token map.
282
+ Opttionally, implements:
283
+ a) vector shuffling (https://github.com/rinongal/textual_inversion/pull/119)where
284
+ shuffling tokens were found to force the model to learn the concepts more descriptively.
285
+ b) proportional token loading so that not every token in the token map is loaded on each call;
286
+ used as part of progressive token loading during training which can improve generalization
287
+ during inference.
288
+ Arguments:
289
+ text (`str`):
290
+ The text to be processed.
291
+ vector_shuffle (`bool`):
292
+ Whether to shuffle the vectors in the token map. Defaults to False.
293
+ prop_tokens_to_load (`float`):
294
+ The proportion of tokens to load from the token map. Defaults to 1.0.
295
+ Returns:
296
+ `str`: The processed text.
297
+ """
298
+ if isinstance(text, list):
299
+ output = []
300
+ for i in range(len(text)):
301
+ output.append(self.replace_placeholder_tokens_in_text(text[i], vector_shuffle=vector_shuffle))
302
+ return output
303
+ for placeholder_token in self.token_map:
304
+ if placeholder_token in text:
305
+ tokens = self.token_map[placeholder_token]
306
+ tokens = tokens[: 1 + int(len(tokens) * prop_tokens_to_load)]
307
+ if vector_shuffle:
308
+ tokens = copy.copy(tokens)
309
+ random.shuffle(tokens)
310
+ text = text.replace(placeholder_token, " ".join(tokens))
311
+ return text
312
+
313
+ def __call__(self, text, *args, vector_shuffle=False, prop_tokens_to_load=1.0, **kwargs):
314
+ """Wrapper around [`~transformers.tokenization_utils.PreTrainedTokenizerBase.__call__`] method
315
+ but first replace placeholder tokens in text with the tokens in the token map.
316
+ Returns:
317
+ [`~transformers.tokenization_utils_base.BatchEncoding`]
318
+ """
319
+ return super().__call__(
320
+ self.replace_placeholder_tokens_in_text(
321
+ text,
322
+ vector_shuffle=vector_shuffle,
323
+ prop_tokens_to_load=prop_tokens_to_load,
324
+ ),
325
+ *args,
326
+ **kwargs,
327
+ )
328
+
329
+ def encode(self, text, *args, vector_shuffle=False, prop_tokens_to_load=1.0, **kwargs):
330
+ """Wrapper around the tokenizer's [`transformers.tokenization_utils.PreTrainedTokenizerBase.encode`] method
331
+ but first replaces placeholder tokens in text with the tokens in the token map.
332
+ Arguments:
333
+ text (`str`):
334
+ The text to be encoded.
335
+ *args:
336
+ The arguments to be passed to the tokenizer's `encode` method.
337
+ vector_shuffle (`bool`):
338
+ Whether to shuffle the vectors in the token map. Defaults to False.
339
+ prop_tokens_to_load (`float`):
340
+ The proportion of tokens to load from the token map. Defaults to 1.0.
341
+ **kwargs:
342
+ The keyword arguments to be passed to the tokenizer's `encode` method.
343
+ Returns:
344
+ List[`int`]: sequence of ids (integer)
345
+ """
346
+ return super().encode(
347
+ self.replace_placeholder_tokens_in_text(
348
+ text,
349
+ vector_shuffle=vector_shuffle,
350
+ prop_tokens_to_load=prop_tokens_to_load,
351
+ ),
352
+ *args,
353
+ **kwargs,
354
+ )