“Transcendental-Programmer” commited on
Commit
c70fcb3
·
1 Parent(s): 9d0294b

feat: inital commit

Browse files
latent_space_explorer/__init__.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from dataclasses import dataclass
4
+ from .fast_sd import fast_diffusion_pipeline
5
+
6
+ import torch
7
+ import pygame
8
+ import numpy as np
9
+ import time
10
+ from PIL import Image
11
+
12
+ from .game_objects import Point, TextPrompt
13
+ from .sampling import (
14
+ DistanceSampling,
15
+ CircleSampling
16
+ )
17
+
18
+ @dataclass
19
+ class GameConfig:
20
+ point_thickness : float = 10 # Thickness for each point
21
+ zoom_speed : float = 0.75 # How fast we zoom in or out
22
+ move_speed : float = 0.75 # How fast we move around canvas
23
+ point_font_size : int = 25 # Size of fonts for points on screen
24
+
25
+ prompt_font_size : int = 30 # Size of font for prompt on screen
26
+
27
+ # screen size
28
+ width : int = 1920
29
+ height : int = 1080
30
+
31
+ # size of sample in top left
32
+ sample_width : int = 512
33
+ sample_height : int = 512
34
+
35
+ compile : bool = False # compile the sd model with torch.compile?
36
+ sampler : str = "distance" # "distance" or "circle"
37
+ seed : int = 0 # Seed for initial latent noise
38
+ call_every : int = 90 # Only calls draw function every *this many* ms. This is to prevent lag. Set this to be around the latency of the model
39
+
40
+ class LatentSpaceExplorer:
41
+ def __init__(self, config : GameConfig = GameConfig()):
42
+ self.config = config
43
+
44
+ self.pipe = fast_diffusion_pipeline(compile = self.config.compile)
45
+ self.points : List[Point] = []
46
+ self.player_pos = None # [2,] np array in R2 space
47
+
48
+ self.dragging_point_idx = None
49
+ self.selected_point_idx = None
50
+
51
+ self.zoom_level = 300.0
52
+ self.translation = np.array([-self.config.width/2, -self.config.height/2])
53
+
54
+ self.point_kwargs = {}
55
+ if self.config.sampler == "distance":
56
+ self.sampler = DistanceSampling
57
+ elif self.config.sampler == "circle":
58
+ self.sampler = CircleSampling
59
+ self.point_kwargs['on_edge'] = True
60
+ else:
61
+ raise ValueError(f"Invalid sampler choice: {self.config.sampler}")
62
+
63
+ pygame.init()
64
+ self.screen = pygame.display.set_mode((self.config.width, self.config.height))
65
+ self.clock = pygame.time.Clock()
66
+ self.ms_elapsed = 0
67
+
68
+ # (n_samples, running average)
69
+ self.avg_latency = (0, 0) # Track average latency of generation for debug
70
+
71
+ self.sample_image = None
72
+ self.sample_font = pygame.font.Font(None, self.config.point_font_size)
73
+
74
+ # User input
75
+ self.input_font = pygame.font.Font(None, self.config.prompt_font_size)
76
+ self.inputting_text = False
77
+ self.inputting_text_for = None # oneof ["modify", "add"]
78
+ self.text_prompt : TextPrompt = None
79
+
80
+ def tick(self):
81
+ self.clock.tick()
82
+ self.ms_elapsed += self.clock.get_time()
83
+
84
+ def update_latency(self, new_observation):
85
+ n = self.avg_latency[0]
86
+ old_avg = self.avg_latency[1]
87
+ self.avg_latency = (n + 1, (old_avg * n + new_observation) / (n + 1))
88
+
89
+ def create_text_prompt(self, prompt_text):
90
+ self.text_prompt = TextPrompt(prompt_text, self.input_font, self.screen)
91
+
92
+ def switch_sampler(self):
93
+ if self.config.sampler == "distance":
94
+ self.config.sampler = "circle"
95
+ self.sampler = CircleSampling
96
+ self.point_kwargs = {'on_edge' : True}
97
+ elif self.config.sampler == "circle":
98
+ self.config.sampler = "distance"
99
+ self.sampler = DistanceSampling
100
+ self.point_kwargs = {}
101
+ self.set_prompts(self.prompts, reset = True)
102
+
103
+ @property
104
+ def encodes(self):
105
+ """
106
+ Get encodings directly from points as a tuple with batched encodings
107
+ """
108
+ if not self.points:
109
+ return None
110
+ encode_list = [p.encoding for p in self.points] # list of N-tuples
111
+ n = len(encode_list[0])
112
+ res = []
113
+ for i in range(n):
114
+ res.append(torch.cat([e[i] for e in encode_list], dim = 0) if encode_list[0][i] is not None else None)
115
+
116
+ return tuple(res)
117
+
118
+ @property
119
+ def prompts(self):
120
+ """
121
+ Get a list of current prompts
122
+ """
123
+ return [p.text for p in self.points]
124
+
125
+ @property
126
+ def r2_points(self):
127
+ """
128
+ Get all points in terms of R2 space
129
+ """
130
+ points = [np.array(p.xy_pos) for p in self.points]
131
+ points = np.stack(points, axis = 0) # [n, 2]
132
+ return points
133
+
134
+ @property
135
+ def screen_space_points(self):
136
+ """
137
+ Get all points in terms of screen space
138
+ """
139
+ screen_space = (self.r2_points * self.zoom_level) - self.translation[None,:]
140
+ return screen_space # list of points in scren space
141
+
142
+ @property
143
+ def mouse_pos(self):
144
+ return np.array(pygame.mouse.get_pos())
145
+
146
+ def invert_screen_space(self, point):
147
+ """
148
+ taking position as [2,] np array in screen space, return R2 pos
149
+ """
150
+ return (point + self.translation) / self.zoom_level
151
+
152
+ def screen_space(self, point):
153
+ """
154
+ R2 -> screenspace as [2,] array
155
+ """
156
+ return (point * self.zoom_level) - self.translation
157
+
158
+ def fixed_seed(self):
159
+ """
160
+ Controls random number generator for initial latent noise
161
+ """
162
+ return torch.Generator('cuda').manual_seed(self.config.seed)
163
+
164
+ def get_encodes(self, text):
165
+ """
166
+ Get text encodings for some prompt then split them so we can associate points with thier encodings
167
+ """
168
+ encodes = self.pipe.get_encodes(text, generator = self.fixed_seed())
169
+ # (n-tuple of lists) into (list of n-tuples)
170
+ if not isinstance(encodes, tuple) and not isinstance(encodes, list):
171
+ return encodes # Already a tensor, no problem
172
+
173
+ res_list = []
174
+ for i in range(len(encodes[0])):
175
+ res_list_i = [encodes_j[i].unsqueeze(0) if encodes_j is not None else None for encodes_j in encodes]
176
+ res_list.append(tuple(res_list_i))
177
+
178
+ return res_list
179
+
180
+ def draw_sample(self):
181
+ """
182
+ Draw sample with current points and player position
183
+ """
184
+ if self.player_pos is not None and self.encodes is not None:
185
+ if self.ms_elapsed >= self.config.call_every:
186
+ time_start = time.time()
187
+ encoding = self.sampler(self.encodes)(self.player_pos, self.r2_points)
188
+ self.sample_image = self.pipe.generate_from_encodes(encoding, generator = self.fixed_seed()).images[0]
189
+ time_total = float(time.time() - time_start) * 1000 # s -> ms
190
+
191
+ self.update_latency(time_total)
192
+
193
+ self.ms_elapsed = 0
194
+
195
+ def get_player_pos_r2(self):
196
+ """
197
+ Get player position in R2 from the
198
+ """
199
+ self.player_pos = self.invert_screen_space(self.mouse_pos)
200
+
201
+ def get_player_pos_screenspace(self):
202
+ """
203
+ Get player pos in screen space
204
+ """
205
+ if self.player_pos is not None: return self.screen_space(self.player_pos)
206
+
207
+ def detect_mouse_on_point(self):
208
+ """
209
+ Detect if mouse is currently in a point. If so, returns index of point, otherwise returns none.
210
+ """
211
+ if not self.points:
212
+ return None
213
+
214
+ mouse_pos = self.mouse_pos
215
+ points = self.screen_space_points
216
+
217
+ distances = np.linalg.norm(points - mouse_pos[None,:], axis = 1)
218
+ close_idx = np.argmin(distances)
219
+
220
+ if distances[close_idx] <= self.config.point_thickness:
221
+ return close_idx
222
+ return None
223
+
224
+ # === POINT/NODE CONTROL ===
225
+
226
+ def modify_node(self, new_prompt):
227
+ idx = self.selected_point_idx
228
+ new_prompts = self.prompts
229
+ new_prompts[idx] = new_prompt
230
+ self.set_prompts(new_prompts, reset = False)
231
+
232
+ def add_node(self, new_prompt):
233
+ self.set_prompts(self.prompts + [new_prompt], reset = False)
234
+
235
+ def del_node(self):
236
+ idx = self.selected_point_idx
237
+ new_prompts = list(self.prompts)
238
+ del new_prompts[idx]
239
+ self.set_prompts(new_prompts, reset = False)
240
+ self.selected_point_idx = None
241
+
242
+ def prepare_to_prompt(self, mode):
243
+ """
244
+ Get ready to show the textbox. Call when we want the text prompt to come
245
+ """
246
+ self.inputting_text = True
247
+ self.inputting_text_for = mode
248
+
249
+ if mode == "modify":
250
+ self.create_text_prompt("Enter New Prompt To Replace Node:")
251
+ elif mode == "add":
252
+ self.create_text_prompt("Enter New Prompt To Create Node:")
253
+
254
+ def handle_prompt(self):
255
+ """
256
+ After enter pressed with textbox, this is called to go back to normal game
257
+ """
258
+ done_prompting = self.text_prompt.update()
259
+
260
+ if done_prompting:
261
+ new_prompt = self.text_prompt.user_input.strip()
262
+ if self.inputting_text_for == "modify":
263
+ self.modify_node(new_prompt)
264
+ elif self.inputting_text_for == "add":
265
+ self.add_node(new_prompt)
266
+ self.text_prompt = None
267
+ self.inputting_text = False
268
+
269
+ def set_prompts(self, prompts : List[str], reset : bool = False):
270
+ """
271
+ :param prompts: New prompts to update to
272
+ :param reset: Reset xy positions of points?
273
+ """
274
+
275
+ if len(prompts) > 0:
276
+ encodes = self.get_encodes(prompts)
277
+
278
+ # First call
279
+ if not self.points or reset:
280
+ self.points = [Point(prompt, encoding, xy_init_kwargs = self.point_kwargs) for (prompt, encoding) in zip(prompts, encodes)]
281
+ return
282
+
283
+ # Modifications
284
+ old_len = len(self.points)
285
+ new_len = len(prompts)
286
+
287
+ pos = [tuple(pos_i) for pos_i in self.r2_points] # positions for each point
288
+
289
+ if old_len <= new_len: # Additions or modification
290
+ pos += [None] * (new_len - old_len) # randomly init this many new positions
291
+ self.points = [Point(prompt, encoding, pos_i, xy_init_kwargs = self.point_kwargs) for (prompt, encoding, pos_i) in zip(prompts, encodes, pos)]
292
+ return
293
+ elif old_len > new_len: # Deletions
294
+ idx_to_keep = []
295
+ for idx, prompt in enumerate(self.prompts):
296
+ if prompt in prompts:
297
+ idx_to_keep.append(idx)
298
+ self.points = [self.points[idx] for idx in idx_to_keep]
299
+ return
300
+
301
+ # === CONTROLS ===
302
+
303
+ def handle_event_controls(self):
304
+ """
305
+ Handles discrete (i.e. keydown, mousedown) controls through events
306
+ """
307
+ for event in pygame.event.get():
308
+ if event.type == pygame.QUIT:
309
+ pygame.quit()
310
+ quit()
311
+ elif event.type == pygame.MOUSEBUTTONDOWN:
312
+ # Click
313
+ if event.button == 1: # Left click
314
+ self.selected_point_idx = self.detect_mouse_on_point()
315
+ if self.selected_point_idx is not None: self.dragging_point_idx = None
316
+ else: # If no point was selected, we move player cursor
317
+ self.get_player_pos_r2()
318
+ self.draw_sample()
319
+ elif event.button == 3: # Right click
320
+ self.dragging_point_idx = self.detect_mouse_on_point()
321
+ if self.dragging_point_idx is not None: self.selected_point_idx = None
322
+ elif event.type == pygame.MOUSEBUTTONUP:
323
+ if event.button == 3: # Right Up
324
+ self.dragging_point_idx = None # Disable drag
325
+ elif event.type == pygame.MOUSEMOTION:
326
+ if self.dragging_point_idx is not None:
327
+ # Drag point
328
+ self.points[self.dragging_point_idx].move(self.invert_screen_space(self.mouse_pos))
329
+ elif pygame.mouse.get_pressed()[0]:
330
+ self.get_player_pos_r2()
331
+ self.draw_sample()
332
+ elif event.type == pygame.KEYDOWN:
333
+ keys = pygame.key.get_pressed()
334
+ if keys[pygame.K_r]:
335
+ self.set_prompts(self.prompts, reset = True)
336
+ elif keys[pygame.K_t] and self.selected_point_idx is not None: # Modify existing node
337
+ self.prepare_to_prompt("modify")
338
+ return
339
+ elif keys[pygame.K_p]: # Adding a node
340
+ self.prepare_to_prompt("add")
341
+ return
342
+ elif keys[pygame.K_o] and self.selected_point_idx is not None:
343
+ # Remove node
344
+ self.del_node()
345
+ elif keys[pygame.K_g]:
346
+ if self.sample_image is not None:
347
+ self.sample_image.save("sample.png")
348
+ elif keys[pygame.K_m]:
349
+ # Change sampler mode
350
+ self.switch_sampler()
351
+
352
+
353
+ def handle_continuous_controls(self):
354
+ """
355
+ Continuous controls for movement (i.e. zoom, movement)
356
+ """
357
+ keys = pygame.key.get_pressed()
358
+ if keys[pygame.K_q]:
359
+ self.zoom_level = max(0.01, self.zoom_level - self.config.zoom_speed)
360
+ elif keys[pygame.K_e]:
361
+ self.zoom_level = self.zoom_level + self.config.zoom_speed
362
+
363
+ idx, sign = None, None
364
+
365
+ # up, down, left, right
366
+ if keys[pygame.K_w]:
367
+ idx, sign = 1, -1
368
+ elif keys[pygame.K_s]:
369
+ idx, sign = 1, 1
370
+ elif keys[pygame.K_a]:
371
+ idx, sign = 0, -1
372
+ elif keys[pygame.K_d]:
373
+ idx, sign = 0, 1
374
+
375
+ if idx is not None and sign is not None:
376
+ self.translation[idx] += sign * self.config.move_speed
377
+
378
+ # === DRAWING THINGS ===
379
+
380
+ def draw_main_screen(self):
381
+ """
382
+ Draw main screen. Sample image, points, etc.
383
+ """
384
+ def get_point_color(idx):
385
+ color = (255, 255, 255) # default to white
386
+ if idx == self.selected_point_idx:
387
+ color = (0, 127.5, 0)
388
+ if idx == self.dragging_point_idx:
389
+ color = (255, 0, 0)
390
+ return color
391
+
392
+ if self.config.sampler == "circle":
393
+ # Draw unit circle on screen
394
+ center = np.array([0,0])
395
+ border = np.array([1,0])
396
+
397
+ center = self.screen_space(center)
398
+ border = self.screen_space(border)
399
+ radius = abs(border[0] - center[0])
400
+
401
+ pygame.draw.circle(self.screen, (255, 255, 255), center, int(radius), 1)
402
+
403
+ if len(self.points) > 0:
404
+ for idx, point in enumerate(self.screen_space_points):
405
+ pygame.draw.circle(self.screen, get_point_color(idx), point, self.config.point_thickness)
406
+ text = self.sample_font.render(self.points[idx].text, True, get_point_color(idx))
407
+ self.screen.blit(text, point)
408
+
409
+ player_pos = self.get_player_pos_screenspace()
410
+ if player_pos is not None:
411
+ pygame.draw.circle(self.screen, (0, 255, 0), player_pos, self.config.point_thickness/2)
412
+
413
+ if self.sample_image is not None:
414
+ pygame_image = pygame.image.fromstring(self.sample_image.tobytes(), self.sample_image.size, self.sample_image.mode)
415
+ pygame_image = pygame.transform.scale(pygame_image, (self.config.sample_width, self.config.sample_height))
416
+ self.screen.blit(pygame_image, (0, 0))
417
+
418
+ def update(self):
419
+ """
420
+ Main pygame loop
421
+ """
422
+
423
+ if not self.inputting_text:
424
+ self.handle_event_controls()
425
+ self.handle_continuous_controls()
426
+ self.tick()
427
+
428
+ self.screen.fill((0,0,0))
429
+ self.draw_main_screen()
430
+
431
+ # Handle prompt after so it can be drawn over the main screen
432
+ if self.inputting_text:
433
+ self.handle_prompt()
434
+ pygame.display.flip()
latent_space_explorer/fast_sd.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import AutoencoderTiny, StableDiffusionXLPipeline
2
+ from .hacked_sdxl_pipeline import HackedSDXLPipeline
3
+ import torch
4
+
5
+ def fast_diffusion_pipeline(model_id = "stabilityai/sdxl-turbo", vae_id = "madebyollin/taesdxl", compile = False):
6
+ """
7
+ :param compile: If true, does a bunch of stuff to make calls fast, but the first call will be very slow as a consequence
8
+ - If you use this, don't vary the batch size (probably)
9
+ """
10
+
11
+ pipe = HackedSDXLPipeline.from_pretrained(model_id, torch_dtype = torch.float16)
12
+ pipe.set_progress_bar_config(disable=True)
13
+ pipe.cached_encode = None
14
+ pipe.vae = AutoencoderTiny.from_pretrained(vae_id, torch_dtype=torch.float16)
15
+
16
+ pipe.to('cuda')
17
+
18
+ if compile:
19
+ pipe.unet = torch.compile(pipe.unet)
20
+ pipe.vae.decode = torch.compile(pipe.vae.decode)
21
+ """
22
+ from sfast.compilers.stable_diffusion_pipeline_compiler import (compile, CompilationConfig)
23
+
24
+ config = CompilationConfig()
25
+ config.enable_jit = True
26
+ config.enable_jit_freeze = True
27
+ config.trace_scheduler = True
28
+ config.enable_cnn_optimization = True
29
+ config.preserve_parameters = False
30
+ config.prefer_lowp_gemm = True
31
+
32
+ pipe = compile(pipe, config)
33
+ """
34
+ return pipe
latent_space_explorer/game_objects.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import random_circle_init
2
+
3
+ import math
4
+ import pygame
5
+
6
+ class Point:
7
+ # Point representing a prompt/generation
8
+ """
9
+ :param text: Text associated with the point
10
+ :param encoding: Encoding associated with the point
11
+ :param xy_pos: Tuple (x, y) for the position of point in R2. If not given, will initialize randomly
12
+ :param xy_init_kwargs: kwargs to random_circle_init for randomly init'ing xy_pos
13
+ """
14
+ def __init__(self, text, encoding, xy_pos = None, xy_init_kwargs = {}):
15
+ self.text = text
16
+
17
+ if xy_pos is not None:
18
+ self.xy_pos = xy_pos # Tuple of x and y in R2 space (not screen space)
19
+ else:
20
+ self.xy_pos = random_circle_init(**xy_init_kwargs)
21
+ self.encoding = encoding
22
+
23
+ if "on_edge" in xy_init_kwargs:
24
+ self.on_edge = xy_init_kwargs['on_edge']
25
+ else:
26
+ self.on_edge = False
27
+
28
+ def move(self, new_xy_pos):
29
+ if self.on_edge:
30
+ x, y = new_xy_pos
31
+ length = math.sqrt(x**2 + y**2)
32
+ self.xy_pos = (x/length, y/length)
33
+ else:
34
+ self.xy_pos = new_xy_pos
35
+
36
+ class TextPrompt:
37
+ def __init__(self, prompt_text, font, screen):
38
+ self.prompt_text = prompt_text
39
+ self.font = font
40
+ self.screen = screen
41
+
42
+ self.user_input = ""
43
+
44
+ def draw_main_blocks(self):
45
+ """
46
+ Draw main text block and text inside it
47
+ """
48
+ screen_width, screen_height = pygame.display.get_surface().get_size()
49
+
50
+ # Margins
51
+ rect_height_fraction = 0.3
52
+ rect_width_fraction = 0.7
53
+ text_prompt_fraction = 0.3
54
+ border_thickness = 10
55
+
56
+ rect_height = int(screen_height * rect_height_fraction)
57
+ rect_width = int(screen_width * rect_width_fraction)
58
+
59
+ rect_x = (screen_width - rect_width) // 2
60
+ rect_y = (screen_height - rect_height) // 2
61
+
62
+ rect = pygame.Rect(rect_x, rect_y, rect_width, rect_height)
63
+
64
+ pygame.draw.rect(self.screen, (0, 0, 0), rect) # Fill rectangle with black
65
+ pygame.draw.rect(self.screen, (255, 255, 255), rect, border_thickness) # Draw white border
66
+
67
+ text_surface = self.font.render(self.prompt_text, True, (255, 255, 255)) # Render text
68
+ text_rect = text_surface.get_rect() # Get text rectangle
69
+ text_rect.centerx = rect.centerx # Center text horizontally
70
+ text_rect.y = rect.y + int(rect.height * text_prompt_fraction) # Position text vertically based on fraction
71
+ self.screen.blit(text_surface, text_rect) # Draw text
72
+
73
+ user_text_surface = self.font.render(self.user_input, True, (255, 255,255))
74
+ user_text_rect = user_text_surface.get_rect()
75
+ user_text_rect.centerx = rect.centerx
76
+ user_text_rect.y = rect.y + int(rect.height * (1 - text_prompt_fraction))
77
+ self.screen.blit(user_text_surface, user_text_rect)
78
+
79
+ def get_user_input(self) -> bool:
80
+ """
81
+ Get user input, update self.user_input, and return True if user pressed enter
82
+ """
83
+ for event in pygame.event.get():
84
+ if event.type == pygame.KEYDOWN:
85
+ if event.key == pygame.K_BACKSPACE:
86
+ self.user_input = self.user_input[:-1]
87
+ elif event.key == pygame.K_RETURN:
88
+ return True
89
+ else:
90
+ self.user_input += event.unicode
91
+ return False
92
+
93
+ def update(self):
94
+ is_done = self.get_user_input()
95
+ self.draw_main_blocks()
96
+
97
+ return is_done
latent_space_explorer/hacked_sdxl_pipeline.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SDXL pipeline hacked to cache embeddings for later use
3
+
4
+ Summary of changes:
5
+ - __call__ takes "mode" that can be "cache" or "call"
6
+ - If "cache", just computes embeddings and returns nothing
7
+ - If "call", uses pre-computed embeddings ()
8
+ - Otherwise just has normal behaviour
9
+
10
+ - There's a few custom methods after the init that you should look at if using
11
+ """
12
+
13
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import *
14
+
15
+ class HackedSDXLPipeline(StableDiffusionXLPipeline):
16
+ def get_encodes(self, *args, **kwargs):
17
+ """
18
+ Get encodings/latents for given prompt. Inputs are identical to if you were calling the pipeline.
19
+ """
20
+
21
+ self.__call__(*args, mode="cache", guidance_scale = 0.0, num_inference_steps = 1, **kwargs)
22
+ return self.cached_encodes
23
+
24
+ def generate_from_encodes(self, encodes, *args, **kwargs):
25
+ """
26
+ Assuming you have some encodings/latents, pass here to generate from them.
27
+ """
28
+
29
+ if len(encodes[0].shape) == 2:
30
+ encodes[0] = encodes[0].unsqueeze(0)
31
+ if len(encodes[2].shape) == 1:
32
+ encodes[2] = encodes[2].unsqueeze(0)
33
+
34
+ self.cached_encodes = encodes
35
+ if 'prompt' in kwargs:
36
+ del kwargs['prompt']
37
+
38
+ return self.__call__(*args, prompt = [""] * len(self.cached_encodes[0]), guidance_scale = 0.0, num_inference_steps = 1, mode = "call", **kwargs)
39
+
40
+ @torch.no_grad()
41
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
42
+ def __call__(
43
+ self,
44
+ prompt: Union[str, List[str]] = None,
45
+ prompt_2: Optional[Union[str, List[str]]] = None,
46
+ height: Optional[int] = None,
47
+ width: Optional[int] = None,
48
+ num_inference_steps: int = 50,
49
+ timesteps: List[int] = None,
50
+ denoising_end: Optional[float] = None,
51
+ guidance_scale: float = 0.0,
52
+ negative_prompt: Optional[Union[str, List[str]]] = None,
53
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
54
+ num_images_per_prompt: Optional[int] = 1,
55
+ eta: float = 0.0,
56
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
57
+ latents: Optional[torch.FloatTensor] = None,
58
+ prompt_embeds: Optional[torch.FloatTensor] = None,
59
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
60
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
61
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
62
+ ip_adapter_image: Optional[PipelineImageInput] = None,
63
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
64
+ output_type: Optional[str] = "pil",
65
+ return_dict: bool = True,
66
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
67
+ guidance_rescale: float = 0.0,
68
+ original_size: Optional[Tuple[int, int]] = None,
69
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
70
+ target_size: Optional[Tuple[int, int]] = None,
71
+ negative_original_size: Optional[Tuple[int, int]] = None,
72
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
73
+ negative_target_size: Optional[Tuple[int, int]] = None,
74
+ clip_skip: Optional[int] = None,
75
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
76
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
77
+ mode = "call", # cache or call
78
+ **kwargs,
79
+ ):
80
+ r"""
81
+ Function invoked when calling the pipeline for generation.
82
+
83
+ Args:
84
+ prompt (`str` or `List[str]`, *optional*):
85
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
86
+ instead.
87
+ prompt_2 (`str` or `List[str]`, *optional*):
88
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
89
+ used in both text-encoders
90
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
91
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
92
+ Anything below 512 pixels won't work well for
93
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
94
+ and checkpoints that are not specifically fine-tuned on low resolutions.
95
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
96
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
97
+ Anything below 512 pixels won't work well for
98
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
99
+ and checkpoints that are not specifically fine-tuned on low resolutions.
100
+ num_inference_steps (`int`, *optional*, defaults to 50):
101
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
102
+ expense of slower inference.
103
+ timesteps (`List[int]`, *optional*):
104
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
105
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
106
+ passed will be used. Must be in descending order.
107
+ denoising_end (`float`, *optional*):
108
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
109
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
110
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
111
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
112
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
113
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
114
+ guidance_scale (`float`, *optional*, defaults to 5.0):
115
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
116
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
117
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
118
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
119
+ usually at the expense of lower image quality.
120
+ negative_prompt (`str` or `List[str]`, *optional*):
121
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
122
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
123
+ less than `1`).
124
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
125
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
126
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
127
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
128
+ The number of images to generate per prompt.
129
+ eta (`float`, *optional*, defaults to 0.0):
130
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
131
+ [`schedulers.DDIMScheduler`], will be ignored for others.
132
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
133
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
134
+ to make generation deterministic.
135
+ latents (`torch.FloatTensor`, *optional*):
136
+ Pre-generated noireturn Nonesy latents, sampled from a Gaussian distribution, to be used as inputs for image
137
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
138
+ tensor will ge generated by sampling using the supplied random `generator`.
139
+ prompt_embeds (`torch.FloatTensor`, *optional*):
140
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
141
+ provided, text embeddings will be generated from `prompt` input argument.
142
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
143
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
144
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
145
+ argument.
146
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
147
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
148
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
149
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
150
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
151
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
152
+ input argument.
153
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
154
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
155
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
156
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
157
+ if `do_classifier_free_guidance` is set to `True`.
158
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
159
+ output_type (`str`, *optional*, defaults to `"pil"`):
160
+ The output format of the generate image. Choose between
161
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
162
+ return_dict (`bool`, *optional*, defaults to `True`):
163
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
164
+ of a plain tuple.
165
+ cross_attention_kwargs (`dict`, *optional*):
166
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
167
+ `self.processor` in
168
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
169
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
170
+ Guidancettioning return Noneas explained in section 2.2 of
171
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
172
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
173
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
174
+ To negatively condition the generation process based on a target image resolution. It should be as same
175
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
176
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
177
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
178
+ callback_on_step_end (`Callable`, *optional*):
179
+ A function that calls at the end of each denoising steps during the inference. The function is called
180
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
181
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
182
+ `callback_on_step_end_tensor_inputs`.
183
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
184
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
185
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
186
+ `._callback_tensor_inputs` attribute of your pipeline class.
187
+
188
+ Examples:
189
+
190
+ Returns:
191
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
192
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
193
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
194
+ """
195
+
196
+ callback = kwargs.pop("callback", None)
197
+ callback_steps = kwargs.pop("callback_steps", None)
198
+
199
+ if callback is not None:
200
+ deprecate(
201
+ "callback",
202
+ "1.0.0",
203
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
204
+ )
205
+ if callback_steps is not None:
206
+ deprecate(
207
+ "callback_steps",
208
+ "1.0.0",
209
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
210
+ )
211
+
212
+ # 0. Default height and width to unet
213
+ height = height or self.default_sample_size * self.vae_scale_factor
214
+ width = width or self.default_sample_size * self.vae_scale_factor
215
+
216
+ original_size = original_size or (height, width)
217
+ target_size = target_size or (height, width)
218
+
219
+ # 1. Check inputs. Raise error if not correct
220
+ self.check_inputs(
221
+ prompt,
222
+ prompt_2,
223
+ height,
224
+ width,
225
+ callback_steps,
226
+ negative_prompt,
227
+ negative_prompt_2,
228
+ prompt_embeds,
229
+ negative_prompt_embeds,
230
+ pooled_prompt_embeds,
231
+ negative_pooled_prompt_embeds,
232
+ ip_adapter_image,
233
+ ip_adapter_image_embeds,
234
+ callback_on_step_end_tensor_inputs,
235
+ )
236
+
237
+ self._guidance_scale = guidance_scale
238
+ self._guidance_rescale = guidance_rescale
239
+ self._clip_skip = clip_skip
240
+ self._cross_attention_kwargs = cross_attention_kwargs
241
+ self._denoising_end = denoising_end
242
+ self._interrupt = False
243
+
244
+ # 2. Define call parameters
245
+ if prompt is not None and isinstance(prompt, str):
246
+ batch_size = 1
247
+ elif prompt is not None and isinstance(prompt, list):
248
+ batch_size = len(prompt)
249
+ else:
250
+ batch_size = prompt_embeds.shape[0]
251
+
252
+ device = self._execution_device
253
+
254
+ # 3. Encode input prompt
255
+ lora_scale = (
256
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
257
+ )
258
+
259
+
260
+ if mode == "cache":
261
+ self.cached_encodes = self.encode_prompt(
262
+ prompt=prompt,
263
+ prompt_2=prompt_2,
264
+ device=device,
265
+ num_images_per_prompt=num_images_per_prompt,
266
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
267
+ negative_prompt=negative_prompt,
268
+ negative_prompt_2=negative_prompt_2,
269
+ prompt_embeds=prompt_embeds,
270
+ negative_prompt_embeds=negative_prompt_embeds,
271
+ pooled_prompt_embeds=pooled_prompt_embeds,
272
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
273
+ lora_scale=lora_scale,
274
+ clip_skip=self.clip_skip,
275
+ )
276
+ return None
277
+ elif mode == "call":
278
+ (
279
+ prompt_embeds,
280
+ negative_prompt_embeds,
281
+ pooled_prompt_embeds,
282
+ negative_pooled_prompt_embeds,
283
+ ) = self.cached_encodes
284
+ else: # Normal behaviour
285
+ (
286
+ prompt_embeds,
287
+ negative_prompt_embeds,
288
+ pooled_prompt_embeds,
289
+ negative_pooled_prompt_embeds,
290
+ ) = self.encode_prompt(
291
+ prompt=prompt,
292
+ prompt_2=prompt_2,
293
+ device=device,
294
+ num_images_per_prompt=num_images_per_prompt,
295
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
296
+ negative_prompt=negative_prompt,
297
+ negative_prompt_2=negative_prompt_2,
298
+ prompt_embeds=prompt_embeds,
299
+ negative_prompt_embeds=negative_prompt_embeds,
300
+ pooled_prompt_embeds=pooled_prompt_embeds,
301
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
302
+ lora_scale=lora_scale,
303
+ clip_skip=self.clip_skip,
304
+ )
305
+
306
+ # 4. Prepare timesteps
307
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
308
+
309
+ # 5. Prepare latent variables
310
+ num_channels_latents = self.unet.config.in_channels
311
+ latents = self.prepare_latents(
312
+ batch_size * num_images_per_prompt,
313
+ num_channels_latents,
314
+ height,
315
+ width,
316
+ prompt_embeds.dtype,
317
+ device,
318
+ generator,
319
+ latents,
320
+ )
321
+
322
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
323
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
324
+
325
+ # 7. Prepare added time ids & embeddings
326
+ add_text_embeds = pooled_prompt_embeds
327
+ if self.text_encoder_2 is None:
328
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
329
+ else:
330
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
331
+
332
+ add_time_ids = self._get_add_time_ids(
333
+ original_size,
334
+ crops_coords_top_left,
335
+ target_size,
336
+ dtype=prompt_embeds.dtype,
337
+ text_encoder_projection_dim=text_encoder_projection_dim,
338
+ )
339
+ if negative_original_size is not None and negative_target_size is not None:
340
+ negative_add_time_ids = self._get_add_time_ids(
341
+ negative_original_size,
342
+ negative_crops_coords_top_left,
343
+ negative_target_size,
344
+ dtype=prompt_embeds.dtype,
345
+ text_encoder_projection_dim=text_encoder_projection_dim,
346
+ )
347
+ else:
348
+ negative_add_time_ids = add_time_ids
349
+
350
+ if False:#self.do_classifier_free_guidance:
351
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
352
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
353
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
354
+
355
+ prompt_embeds = prompt_embeds.to(device)
356
+ add_text_embeds = add_text_embeds.to(device)
357
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
358
+
359
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
360
+ image_embeds = self.prepare_ip_adapter_image_embeds(
361
+ ip_adapter_image,
362
+ ip_adapter_image_embeds,
363
+ device,
364
+ batch_size * num_images_per_prompt,
365
+ self.do_classifier_free_guidance,
366
+ )
367
+
368
+ # 8. Denoising loop
369
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
370
+
371
+ # 8.1 Apply denoising_end
372
+ if (
373
+ self.denoising_end is not None
374
+ and isinstance(self.denoising_end, float)
375
+ and self.denoising_end > 0
376
+ and self.denoising_end < 1
377
+ ):
378
+ discrete_timestep_cutoff = int(
379
+ round(
380
+ self.scheduler.config.num_train_timesteps
381
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
382
+ )
383
+ )
384
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
385
+ timesteps = timesteps[:num_inference_steps]
386
+
387
+ # 9. Optionally get Guidance Scale Embedding
388
+ timestep_cond = None
389
+ if self.unet.config.time_cond_proj_dim is not None:
390
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
391
+ timestep_cond = self.get_guidance_scale_embedding(
392
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
393
+ ).to(device=device, dtype=latents.dtype)
394
+
395
+ self._num_timesteps = len(timesteps)
396
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
397
+ for i, t in enumerate(timesteps):
398
+ if self.interrupt:
399
+ continue
400
+
401
+ # expand the latents if we are doing classifier free guidance
402
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
403
+
404
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
405
+
406
+ # predict the noise residual
407
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
408
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
409
+ added_cond_kwargs["image_embeds"] = image_embeds
410
+ noise_pred = self.unet(
411
+ latent_model_input,
412
+ t,
413
+ encoder_hidden_states=prompt_embeds,
414
+ timestep_cond=timestep_cond,
415
+ cross_attention_kwargs=self.cross_attention_kwargs,
416
+ added_cond_kwargs=added_cond_kwargs,
417
+ return_dict=False,
418
+ )[0]
419
+
420
+ # perform guidance
421
+ if self.do_classifier_free_guidance:
422
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
423
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
424
+
425
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
426
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
427
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
428
+
429
+ # compute the previous noisy sample x_t -> x_t-1
430
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
431
+
432
+ if callback_on_step_end is not None:
433
+ callback_kwargs = {}
434
+ for k in callback_on_step_end_tensor_inputs:
435
+ callback_kwargs[k] = locals()[k]
436
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
437
+
438
+ latents = callback_outputs.pop("latents", latents)
439
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
440
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
441
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
442
+ negative_pooled_prompt_embeds = callback_outputs.pop(
443
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
444
+ )
445
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
446
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
447
+
448
+ # call the callback, if provided
449
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
450
+ progress_bar.update()
451
+ if callback is not None and i % callback_steps == 0:
452
+ step_idx = i // getattr(self.scheduler, "order", 1)
453
+ callback(step_idx, t, latents)
454
+
455
+ if XLA_AVAILABLE:
456
+ xm.mark_step()
457
+
458
+ if not output_type == "latent":
459
+ # make sure the VAE is in float32 mode, as it overflows in float16
460
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
461
+
462
+ if needs_upcasting:
463
+ self.upcast_vae()
464
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
465
+
466
+ # unscale/denormalize the latents
467
+ # denormalize with the mean and std if available and not None
468
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
469
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
470
+ if has_latents_mean and has_latents_std:
471
+ latents_mean = (
472
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
473
+ )
474
+ latents_std = (
475
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
476
+ )
477
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
478
+ else:
479
+ latents = latents / self.vae.config.scaling_factor
480
+
481
+ image = self.vae.decode(latents, return_dict=False)[0]
482
+
483
+ # cast back to fp16 if needed
484
+ if needs_upcasting:
485
+ self.vae.to(dtype=torch.float16)
486
+ else:
487
+ image = latents
488
+
489
+ if not output_type == "latent":
490
+ # apply watermark if available
491
+ if self.watermark is not None:
492
+ image = self.watermark.apply_watermark(image)
493
+
494
+ image = self.image_processor.postprocess(image, output_type=output_type)
495
+
496
+ # Offload all models
497
+ self.maybe_free_model_hooks()
498
+
499
+ if not return_dict:
500
+ return (image,)
501
+
502
+ return StableDiffusionXLPipelineOutput(images=image)