zhiweili commited on
Commit
bc088da
1 Parent(s): 3ec1dea

add app_makeup

Browse files
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .vscode
2
+ .DS_Store
3
+ __pycache__
README.md CHANGED
@@ -10,4 +10,5 @@ pinned: false
10
  license: mit
11
  ---
12
 
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
10
  license: mit
11
  ---
12
 
13
+ Modified from: https://huggingface.co/spaces/turboedit/turbo_edit
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from app_makeup import create_demo as create_demo_makeup
4
+
5
+ with gr.Blocks(css="style.css") as demo:
6
+ with gr.Tabs():
7
+ with gr.Tab(label="Face Makeup"):
8
+ create_demo_makeup()
9
+
10
+ demo.launch()
app_makeup.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import time
4
+ import torch
5
+
6
+ from PIL import Image
7
+ from segment_utils import(
8
+ segment_image,
9
+ restore_result,
10
+ )
11
+ from enhance_utils import enhance_image
12
+ from inversion_run_adapter import run as adapter_run
13
+
14
+
15
+ DEFAULT_SRC_PROMPT = "a woman"
16
+ DEFAULT_EDIT_PROMPT = "a woman, with red lips, 8k, high quality"
17
+
18
+ DEFAULT_CATEGORY = "face"
19
+
20
+ device = "cuda" if torch.cuda.is_available() else "cpu"
21
+
22
+ @spaces.GPU(duration=15)
23
+ def image_to_image(
24
+ input_image: Image,
25
+ input_image_prompt: str,
26
+ edit_prompt: str,
27
+ seed: int,
28
+ w1: float,
29
+ num_steps: int,
30
+ start_step: int,
31
+ guidance_scale: float,
32
+ generate_size: int,
33
+ lineart_scale: float,
34
+ canny_scale: float,
35
+ lineart_detect: float,
36
+ canny_detect: float,
37
+ ):
38
+ w2 = 1.0
39
+ run_task_time = 0
40
+ time_cost_str = ''
41
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
42
+ run_model = adapter_run
43
+ generated_image = run_model(
44
+ input_image,
45
+ input_image_prompt,
46
+ edit_prompt,
47
+ generate_size,
48
+ seed,
49
+ w1,
50
+ w2,
51
+ num_steps,
52
+ start_step,
53
+ guidance_scale,
54
+ lineart_scale,
55
+ canny_scale,
56
+ lineart_detect,
57
+ canny_detect,
58
+ )
59
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
60
+ enhanced_image = enhance_image(generated_image, False)
61
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
62
+
63
+ return enhanced_image, generated_image, time_cost_str
64
+
65
+ def get_time_cost(run_task_time, time_cost_str):
66
+ now_time = int(time.time()*1000)
67
+ if run_task_time == 0:
68
+ time_cost_str = 'start'
69
+ else:
70
+ if time_cost_str != '':
71
+ time_cost_str += f'-->'
72
+ time_cost_str += f'{now_time - run_task_time}'
73
+ run_task_time = now_time
74
+ return run_task_time, time_cost_str
75
+
76
+ def create_demo() -> gr.Blocks:
77
+ with gr.Blocks() as demo:
78
+ croper = gr.State()
79
+ with gr.Row():
80
+ with gr.Column():
81
+ input_image_prompt = gr.Textbox(lines=1, label="Input Image Prompt", value=DEFAULT_SRC_PROMPT)
82
+ edit_prompt = gr.Textbox(lines=1, label="Edit Prompt", value=DEFAULT_EDIT_PROMPT)
83
+ category = gr.Textbox(label="Category", value=DEFAULT_CATEGORY, visible=False)
84
+ with gr.Column():
85
+ num_steps = gr.Slider(minimum=1, maximum=100, value=20, step=1, label="Num Steps")
86
+ start_step = gr.Slider(minimum=1, maximum=100, value=15, step=1, label="Start Step")
87
+ with gr.Accordion("Advanced Options", open=False):
88
+ guidance_scale = gr.Slider(minimum=0, maximum=20, value=0, step=0.5, label="Guidance Scale", visible=True)
89
+ generate_size = gr.Number(label="Generate Size", value=1024)
90
+ mask_expansion = gr.Number(label="Mask Expansion", value=10, visible=True)
91
+ mask_dilation = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Mask Dilation")
92
+ lineart_scale = gr.Slider(minimum=0, maximum=5, value=0.8, step=0.1, label="Lineart Weights", visible=True)
93
+ canny_scale = gr.Slider(minimum=0, maximum=5, value=0.4, step=0.1, label="Canny Weights", visible=True)
94
+ lineart_detect = gr.Number(label="Lineart Detect", value=0.375, visible=True)
95
+ canny_detect = gr.Number(label="Canny Detect", value=0.375, visible=True)
96
+ with gr.Column():
97
+ seed = gr.Number(label="Seed", value=8)
98
+ w1 = gr.Number(label="W1", value=2.5)
99
+ g_btn = gr.Button("Edit Image")
100
+
101
+ with gr.Row():
102
+ with gr.Column():
103
+ input_image = gr.Image(label="Input Image", type="pil")
104
+ with gr.Column():
105
+ restored_image = gr.Image(label="Restored Image", type="pil", interactive=False)
106
+ download_path = gr.File(label="Download the output image", interactive=False)
107
+ with gr.Column():
108
+ origin_area_image = gr.Image(label="Origin Area Image", type="pil", interactive=False)
109
+ enhanced_image = gr.Image(label="Enhanced Image", type="pil", interactive=False)
110
+ generated_cost = gr.Textbox(label="Time cost by step (ms):", visible=True, interactive=False)
111
+ generated_image = gr.Image(label="Generated Image", type="pil", interactive=False)
112
+
113
+ g_btn.click(
114
+ fn=segment_image,
115
+ inputs=[input_image, category, generate_size, mask_expansion, mask_dilation],
116
+ outputs=[origin_area_image, croper],
117
+ ).success(
118
+ fn=image_to_image,
119
+ inputs=[origin_area_image, input_image_prompt, edit_prompt,seed,w1, num_steps, start_step, guidance_scale, generate_size, lineart_scale, canny_scale, lineart_detect, canny_detect],
120
+ outputs=[enhanced_image, generated_image, generated_cost],
121
+ ).success(
122
+ fn=restore_result,
123
+ inputs=[croper, category, enhanced_image],
124
+ outputs=[restored_image, download_path],
125
+ )
126
+
127
+ return demo
checkpoints/selfie_multiclass_256x256.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6748b1253a99067ef71f7e26ca71096cd449baefa8f101900ea23016507e0e0
3
+ size 16371837
config.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ml_collections import config_dict
2
+ import yaml
3
+ from diffusers.schedulers import (
4
+ DDIMScheduler,
5
+ EulerAncestralDiscreteScheduler,
6
+ EulerDiscreteScheduler,
7
+ DDPMScheduler,
8
+ )
9
+ from inversion_utils import (
10
+ deterministic_ddim_step,
11
+ deterministic_ddpm_step,
12
+ deterministic_euler_step,
13
+ deterministic_non_ancestral_euler_step,
14
+ )
15
+
16
+ BREAKDOWNS = ["x_t_c_hat", "x_t_hat_c", "no_breakdown", "x_t_hat_c_with_zeros"]
17
+ SCHEDULERS = ["ddpm", "ddim", "euler", "euler_non_ancestral"]
18
+ MODELS = [
19
+ "stabilityai/sdxl-turbo",
20
+ "stabilityai/stable-diffusion-xl-base-1.0",
21
+ "CompVis/stable-diffusion-v1-4",
22
+ ]
23
+
24
+ def get_num_steps_actual(cfg):
25
+ return (
26
+ cfg.num_steps_inversion
27
+ - cfg.step_start
28
+ + (1 if cfg.clean_step_timestep > 0 else 0)
29
+ if cfg.timesteps is None
30
+ else len(cfg.timesteps) + (1 if cfg.clean_step_timestep > 0 else 0)
31
+ )
32
+
33
+
34
+ def get_config(args):
35
+ if args.config_from_file and args.config_from_file != "":
36
+ with open(args.config_from_file, "r") as f:
37
+ cfg = config_dict.ConfigDict(yaml.safe_load(f))
38
+
39
+ num_steps_actual = get_num_steps_actual(cfg)
40
+
41
+ else:
42
+ cfg = config_dict.ConfigDict()
43
+
44
+ cfg.seed = 2
45
+ cfg.self_r = 0.5
46
+ cfg.cross_r = 0.9
47
+ cfg.eta = 1
48
+ cfg.scheduler_type = SCHEDULERS[0]
49
+
50
+ cfg.num_steps_inversion = 50 # timesteps: 999, 799, 599, 399, 199
51
+ cfg.step_start = 20
52
+ cfg.timesteps = None
53
+ cfg.noise_timesteps = None
54
+ num_steps_actual = get_num_steps_actual(cfg)
55
+ cfg.ws1 = [2] * num_steps_actual
56
+ cfg.ws2 = [1] * num_steps_actual
57
+ cfg.real_cfg_scale = 0
58
+ cfg.real_cfg_scale_save = 0
59
+ cfg.breakdown = BREAKDOWNS[1]
60
+ cfg.noise_shift_delta = 1
61
+ cfg.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
62
+
63
+ cfg.clean_step_timestep = 0
64
+
65
+ cfg.model = MODELS[1]
66
+
67
+ if cfg.scheduler_type == "ddim":
68
+ cfg.scheduler_class = DDIMScheduler
69
+ cfg.step_function = deterministic_ddim_step
70
+ elif cfg.scheduler_type == "ddpm":
71
+ cfg.scheduler_class = DDPMScheduler
72
+ cfg.step_function = deterministic_ddpm_step
73
+ elif cfg.scheduler_type == "euler":
74
+ cfg.scheduler_class = EulerAncestralDiscreteScheduler
75
+ cfg.step_function = deterministic_euler_step
76
+ elif cfg.scheduler_type == "euler_non_ancestral":
77
+ cfg.scheduler_class = EulerDiscreteScheduler
78
+ cfg.step_function = deterministic_non_ancestral_euler_step
79
+ else:
80
+ raise ValueError(f"Unknown scheduler type: {cfg.scheduler_type}")
81
+
82
+ with cfg.ignore_type():
83
+ if isinstance(cfg.max_norm_zs, (int, float)):
84
+ cfg.max_norm_zs = [cfg.max_norm_zs] * num_steps_actual
85
+
86
+ if isinstance(cfg.ws1, (int, float)):
87
+ cfg.ws1 = [cfg.ws1] * num_steps_actual
88
+
89
+ if isinstance(cfg.ws2, (int, float)):
90
+ cfg.ws2 = [cfg.ws2] * num_steps_actual
91
+
92
+ if not hasattr(cfg, "update_eta"):
93
+ cfg.update_eta = False
94
+
95
+ if not hasattr(cfg, "save_timesteps"):
96
+ cfg.save_timesteps = None
97
+
98
+ if not hasattr(cfg, "scheduler_timesteps"):
99
+ cfg.scheduler_timesteps = None
100
+
101
+ assert (
102
+ cfg.scheduler_type == "ddpm" or cfg.timesteps is None
103
+ ), "timesteps must be None for ddim/euler"
104
+
105
+ cfg.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
106
+ assert (
107
+ len(cfg.max_norm_zs) == num_steps_actual
108
+ ), f"len(cfg.max_norm_zs) ({len(cfg.max_norm_zs)}) != num_steps_actual ({num_steps_actual})"
109
+
110
+ assert (
111
+ len(cfg.ws1) == num_steps_actual
112
+ ), f"len(cfg.ws1) ({len(cfg.ws1)}) != num_steps_actual ({num_steps_actual})"
113
+
114
+ assert (
115
+ len(cfg.ws2) == num_steps_actual
116
+ ), f"len(cfg.ws2) ({len(cfg.ws2)}) != num_steps_actual ({num_steps_actual})"
117
+
118
+ assert cfg.noise_timesteps is None or len(cfg.noise_timesteps) == (
119
+ num_steps_actual - (1 if cfg.clean_step_timestep > 0 else 0)
120
+ ), f"len(cfg.noise_timesteps) ({len(cfg.noise_timesteps)}) != num_steps_actual ({num_steps_actual})"
121
+
122
+ assert cfg.save_timesteps is None or len(cfg.save_timesteps) == (
123
+ num_steps_actual - (1 if cfg.clean_step_timestep > 0 else 0)
124
+ ), f"len(cfg.save_timesteps) ({len(cfg.save_timesteps)}) != num_steps_actual ({num_steps_actual})"
125
+
126
+ return cfg
127
+
128
+
129
+ def get_config_name(config, args):
130
+ if args.folder_name is not None and args.folder_name != "":
131
+ return args.folder_name
132
+ timesteps_str = (
133
+ f"step_start {config.step_start}"
134
+ if config.timesteps is None
135
+ else f"timesteps {config.timesteps}"
136
+ )
137
+ return f"""\
138
+ ws1 {config.ws1[0]} ws2 {config.ws2[0]} real_cfg_scale {config.real_cfg_scale} {timesteps_str} \
139
+ real_cfg_scale_save {config.real_cfg_scale_save} seed {config.seed} max_norm_zs {config.max_norm_zs[-1]} noise_shift_delta {config.noise_shift_delta} \
140
+ scheduler_type {config.scheduler_type} fp16 {args.fp16}\
141
+ """
croper.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PIL
2
+ import numpy as np
3
+
4
+ from PIL import Image
5
+
6
+ class Croper:
7
+ def __init__(
8
+ self,
9
+ input_image: PIL.Image,
10
+ target_mask: np.ndarray,
11
+ mask_size: int = 256,
12
+ mask_expansion: int = 20,
13
+ ):
14
+ self.input_image = input_image
15
+ self.target_mask = target_mask
16
+ self.mask_size = mask_size
17
+ self.mask_expansion = mask_expansion
18
+
19
+ def corp_mask_image(self):
20
+ target_mask = self.target_mask
21
+ input_image = self.input_image
22
+ mask_expansion = self.mask_expansion
23
+ original_width, original_height = input_image.size
24
+ mask_indices = np.where(target_mask)
25
+ start_y = np.min(mask_indices[0])
26
+ end_y = np.max(mask_indices[0])
27
+ start_x = np.min(mask_indices[1])
28
+ end_x = np.max(mask_indices[1])
29
+ mask_height = end_y - start_y
30
+ mask_width = end_x - start_x
31
+ # choose the max side length
32
+ max_side_length = max(mask_height, mask_width)
33
+ # expand the mask area
34
+ height_diff = (max_side_length - mask_height) // 2
35
+ width_diff = (max_side_length - mask_width) // 2
36
+ start_y = start_y - mask_expansion - height_diff
37
+ if start_y < 0:
38
+ start_y = 0
39
+ end_y = end_y + mask_expansion + height_diff
40
+ if end_y > original_height:
41
+ end_y = original_height
42
+ start_x = start_x - mask_expansion - width_diff
43
+ if start_x < 0:
44
+ start_x = 0
45
+ end_x = end_x + mask_expansion + width_diff
46
+ if end_x > original_width:
47
+ end_x = original_width
48
+ expanded_height = end_y - start_y
49
+ expanded_width = end_x - start_x
50
+ expanded_max_side_length = max(expanded_height, expanded_width)
51
+ # calculate the crop area
52
+ crop_mask = target_mask[start_y:end_y, start_x:end_x]
53
+ crop_mask_start_y = (expanded_max_side_length - expanded_height) // 2
54
+ crop_mask_end_y = crop_mask_start_y + expanded_height
55
+ crop_mask_start_x = (expanded_max_side_length - expanded_width) // 2
56
+ crop_mask_end_x = crop_mask_start_x + expanded_width
57
+ # create a square mask
58
+ square_mask = np.zeros((expanded_max_side_length, expanded_max_side_length), dtype=target_mask.dtype)
59
+ square_mask[crop_mask_start_y:crop_mask_end_y, crop_mask_start_x:crop_mask_end_x] = crop_mask
60
+ square_mask_image = Image.fromarray((square_mask * 255).astype(np.uint8))
61
+
62
+ crop_image = input_image.crop((start_x, start_y, end_x, end_y))
63
+ square_image = Image.new("RGB", (expanded_max_side_length, expanded_max_side_length))
64
+ square_image.paste(crop_image, (crop_mask_start_x, crop_mask_start_y))
65
+
66
+ self.origin_start_x = start_x
67
+ self.origin_start_y = start_y
68
+ self.origin_end_x = end_x
69
+ self.origin_end_y = end_y
70
+
71
+ self.square_start_x = crop_mask_start_x
72
+ self.square_start_y = crop_mask_start_y
73
+ self.square_end_x = crop_mask_end_x
74
+ self.square_end_y = crop_mask_end_y
75
+
76
+ self.square_length = expanded_max_side_length
77
+ self.square_mask_image = square_mask_image
78
+ self.square_image = square_image
79
+ self.corp_mask = crop_mask
80
+
81
+ mask_size = self.mask_size
82
+ self.resized_square_mask_image = square_mask_image.resize((mask_size, mask_size))
83
+ self.resized_square_image = square_image.resize((mask_size, mask_size))
84
+
85
+ return self.resized_square_mask_image
86
+
87
+ def restore_result(self, generated_image):
88
+ square_length = self.square_length
89
+ generated_image = generated_image.resize((square_length, square_length))
90
+ square_mask_image = self.square_mask_image
91
+ cropped_generated_image = generated_image.crop((self.square_start_x, self.square_start_y, self.square_end_x, self.square_end_y))
92
+ cropped_square_mask_image = square_mask_image.crop((self.square_start_x, self.square_start_y, self.square_end_x, self.square_end_y))
93
+
94
+ restored_image = self.input_image.copy()
95
+ restored_image.paste(cropped_generated_image, (self.origin_start_x, self.origin_start_y), cropped_square_mask_image)
96
+
97
+ return restored_image
98
+
99
+ def restore_result_v2(self, generated_image):
100
+ square_length = self.square_length
101
+ generated_image = generated_image.resize((square_length, square_length))
102
+ cropped_generated_image = generated_image.crop((self.square_start_x, self.square_start_y, self.square_end_x, self.square_end_y))
103
+
104
+ restored_image = self.input_image.copy()
105
+ restored_image.paste(cropped_generated_image, (self.origin_start_x, self.origin_start_y))
106
+
107
+ return restored_image
108
+
enhance_utils.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import cv2
4
+ import numpy as np
5
+
6
+ from PIL import Image
7
+ from gfpgan.utils import GFPGANer
8
+ from basicsr.archs.srvgg_arch import SRVGGNetCompact
9
+ from realesrgan.utils import RealESRGANer
10
+
11
+ os.system("pip freeze")
12
+ if not os.path.exists('GFPGANv1.4.pth'):
13
+ os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .")
14
+ if not os.path.exists('realesr-general-x4v3.pth'):
15
+ os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P .")
16
+
17
+ os.makedirs('output', exist_ok=True)
18
+
19
+ model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
20
+ model_path = 'realesr-general-x4v3.pth'
21
+ half = True if torch.cuda.is_available() else False
22
+ upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)
23
+
24
+ face_enhancer = GFPGANer(model_path='GFPGANv1.4.pth', upscale=1, arch='clean', channel_multiplier=2)
25
+
26
+ def enhance_image(
27
+ pil_image: Image,
28
+ enhance_face: bool = True,
29
+ ):
30
+ img = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
31
+
32
+ h, w = img.shape[0:2]
33
+ if h < 300:
34
+ img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
35
+ if enhance_face:
36
+ _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=True, paste_back=True)
37
+ else:
38
+ output, _ = upsampler.enhance(img, outscale=2)
39
+ pil_output = Image.fromarray(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))
40
+
41
+ return pil_output
inversion_run_adapter.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from diffusers import (
4
+ DDPMScheduler,
5
+ DiffusionPipeline,
6
+ T2IAdapter,
7
+ MultiAdapter,
8
+ )
9
+ from controlnet_aux import (
10
+ LineartDetector,
11
+ CannyDetector,
12
+ MidasDetector,
13
+ PidiNetDetector,
14
+ )
15
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img import retrieve_timesteps, retrieve_latents
16
+ from PIL import Image
17
+ from inversion_utils import get_ddpm_inversion_scheduler, create_xts
18
+ from config import get_config, get_num_steps_actual
19
+ from functools import partial
20
+ from compel import Compel, ReturnedEmbeddingsType
21
+
22
+ class Object(object):
23
+ pass
24
+
25
+ args = Object()
26
+ args.images_paths = None
27
+ args.images_folder = None
28
+ args.force_use_cpu = False
29
+ args.folder_name = 'test_measure_time'
30
+ args.config_from_file = 'run_configs/noise_shift_guidance_1_5.yaml'
31
+ args.save_intermediate_results = False
32
+ args.batch_size = None
33
+ args.skip_p_to_p = True
34
+ args.only_p_to_p = False
35
+ args.fp16 = False
36
+ args.prompts_file = 'dataset_measure_time/dataset.json'
37
+ args.images_in_prompts_file = None
38
+ args.seed = 986
39
+ args.time_measure_n = 1
40
+
41
+
42
+ assert (
43
+ args.batch_size is None or args.save_intermediate_results is False
44
+ ), "save_intermediate_results is not implemented for batch_size > 1"
45
+
46
+ generator = None
47
+ device = "cuda" if torch.cuda.is_available() else "cpu"
48
+
49
+ # BASE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"
50
+ BASE_MODEL = "stabilityai/sdxl-turbo"
51
+ # BASE_MODEL = "SG161222/RealVisXL_V5.0_Lightning"
52
+ # BASE_MODEL = "Lykon/dreamshaper-xl-v2-turbo"
53
+ # BASE_MODEL = "RunDiffusion/Juggernaut-XL-Lightning"
54
+
55
+ lineart_detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
56
+ lineart_detector = lineart_detector.to(device)
57
+
58
+ pidinet_detector = PidiNetDetector.from_pretrained("lllyasviel/Annotators")
59
+ pidinet_detector = pidinet_detector.to(device)
60
+
61
+ canndy_detector = CannyDetector()
62
+
63
+ midas_detector = MidasDetector.from_pretrained(
64
+ "valhalla/t2iadapter-aux-models", filename="dpt_large_384.pt", model_type="dpt_large"
65
+ )
66
+ midas_detector = midas_detector.to(device)
67
+
68
+ adapters = MultiAdapter(
69
+ [
70
+ T2IAdapter.from_pretrained(
71
+ "TencentARC/t2i-adapter-lineart-sdxl-1.0",
72
+ torch_dtype=torch.float16,
73
+ varient="fp16",
74
+ ),
75
+ T2IAdapter.from_pretrained(
76
+ "TencentARC/t2i-adapter-canny-sdxl-1.0",
77
+ torch_dtype=torch.float16,
78
+ varient="fp16",
79
+ ),
80
+ # T2IAdapter.from_pretrained(
81
+ # "TencentARC/t2i-adapter-sketch-sdxl-1.0",
82
+ # torch_dtype=torch.float16,
83
+ # varient="fp16",
84
+ # ),
85
+ # T2IAdapter.from_pretrained(
86
+ # "TencentARC/t2i-adapter-depth-midas-sdxl-1.0",
87
+ # torch_dtype=torch.float16,
88
+ # varient="fp16",
89
+ # ),
90
+ ]
91
+ )
92
+ adapters = adapters.to(torch.float16)
93
+
94
+ pipeline = DiffusionPipeline.from_pretrained(
95
+ BASE_MODEL,
96
+ torch_dtype=torch.float16,
97
+ variant="fp16",
98
+ use_safetensors=True,
99
+ adapter=adapters,
100
+ custom_pipeline="./pipelines/pipeline_sdxl_adapter_img2img.py",
101
+ )
102
+ pipeline = pipeline.to(device)
103
+
104
+ pipeline.scheduler = DDPMScheduler.from_pretrained(
105
+ BASE_MODEL,
106
+ subfolder="scheduler",
107
+ )
108
+
109
+ config = get_config(args)
110
+
111
+ compel_proc = Compel(
112
+ tokenizer=[pipeline.tokenizer, pipeline.tokenizer_2] ,
113
+ text_encoder=[pipeline.text_encoder, pipeline.text_encoder_2],
114
+ returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
115
+ requires_pooled=[False, True]
116
+ )
117
+
118
+ def run(
119
+ input_image:Image,
120
+ src_prompt:str,
121
+ tgt_prompt:str,
122
+ generate_size:int,
123
+ seed:int,
124
+ w1:float,
125
+ w2:float,
126
+ num_steps:int,
127
+ start_step:int,
128
+ guidance_scale:float,
129
+ lineart_scale:float = 0.5,
130
+ canny_scale:float = 0.5,
131
+ lineart_detect:float = 0.375,
132
+ canny_detect:float = 0.375,
133
+ ):
134
+ generator = torch.Generator().manual_seed(seed)
135
+
136
+ config.num_steps_inversion = num_steps
137
+ config.step_start = start_step
138
+ num_steps_actual = get_num_steps_actual(config)
139
+
140
+
141
+ num_steps_inversion = config.num_steps_inversion
142
+ denoising_start = (num_steps_inversion - num_steps_actual) / num_steps_inversion
143
+ print(f"-------->num_steps_inversion: {num_steps_inversion} num_steps_actual: {num_steps_actual} denoising_start: {denoising_start}")
144
+
145
+ timesteps, num_inference_steps = retrieve_timesteps(
146
+ pipeline.scheduler, num_steps_inversion, device, None
147
+ )
148
+ timesteps, num_inference_steps = pipeline.get_timesteps(
149
+ num_inference_steps=num_inference_steps,
150
+ denoising_start=denoising_start,
151
+ strength=0,
152
+ device=device,
153
+ )
154
+ timesteps = timesteps.type(torch.int64)
155
+
156
+ timesteps = [torch.tensor(t) for t in timesteps.tolist()]
157
+ timesteps_len = len(timesteps)
158
+ config.step_start = start_step + num_steps_actual - timesteps_len
159
+ num_steps_actual = timesteps_len
160
+ config.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
161
+ print(f"-------->num_steps_inversion: {num_steps_inversion} num_steps_actual: {num_steps_actual} step_start: {config.step_start}")
162
+ print(f"-------->timesteps len: {len(timesteps)} max_norm_zs len: {len(config.max_norm_zs)}")
163
+ lineart_image = lineart_detector(input_image, detect_resolution=int(generate_size * lineart_detect), image_resolution=generate_size)
164
+ canny_image = canndy_detector(input_image, detect_resolution=int(generate_size * canny_detect), image_resolution=generate_size)
165
+ # pidinet_image = pidinet_detector(input_image, detect_resolution=512, image_resolution=generate_size, apply_filter=True)
166
+ # depth_image = midas_detector(input_image, detect_resolution=512, image_resolution=generate_size)
167
+ cond_image = [lineart_image, canny_image]
168
+ conditioning_scale = [lineart_scale, canny_scale]
169
+ pipeline.__call__ = partial(
170
+ pipeline.__call__,
171
+ num_inference_steps=num_steps_inversion,
172
+ guidance_scale=guidance_scale,
173
+ generator=generator,
174
+ denoising_start=denoising_start,
175
+ strength=0,
176
+ adapter_image=cond_image,
177
+ adapter_conditioning_scale=conditioning_scale,
178
+ )
179
+
180
+ x_0_image = input_image
181
+ x_0 = encode_image(x_0_image, pipeline)
182
+ x_ts = create_xts(1, None, 0, generator, pipeline.scheduler, timesteps, x_0, no_add_noise=False)
183
+ x_ts = [xt.to(dtype=torch.float16) for xt in x_ts]
184
+ latents = [x_ts[0]]
185
+ x_ts_c_hat = [None]
186
+ config.ws1 = [w1] * num_steps_actual
187
+ config.ws2 = [w2] * num_steps_actual
188
+ pipeline.scheduler = get_ddpm_inversion_scheduler(
189
+ pipeline.scheduler,
190
+ config.step_function,
191
+ config,
192
+ timesteps,
193
+ config.save_timesteps,
194
+ latents,
195
+ x_ts,
196
+ x_ts_c_hat,
197
+ args.save_intermediate_results,
198
+ pipeline,
199
+ x_0,
200
+ v1s_images := [],
201
+ v2s_images := [],
202
+ deltas_images := [],
203
+ v1_x0s := [],
204
+ v2_x0s := [],
205
+ deltas_x0s := [],
206
+ "res12",
207
+ image_name="im_name",
208
+ time_measure_n=args.time_measure_n,
209
+ )
210
+ latent = latents[0].expand(3, -1, -1, -1)
211
+ prompt = [src_prompt, src_prompt, tgt_prompt]
212
+ conditioning, pooled = compel_proc(prompt)
213
+
214
+ image = pipeline.__call__(
215
+ image=latent,
216
+ prompt_embeds=conditioning,
217
+ pooled_prompt_embeds=pooled,
218
+ eta=1,
219
+ ).images
220
+ return image[2]
221
+
222
+ def encode_image(image, pipe):
223
+ image = pipe.image_processor.preprocess(image)
224
+ originDtype = pipe.dtype
225
+ image = image.to(device=device, dtype=originDtype)
226
+
227
+ if pipe.vae.config.force_upcast:
228
+ image = image.float()
229
+ pipe.vae.to(dtype=torch.float32)
230
+
231
+ if isinstance(generator, list):
232
+ init_latents = [
233
+ retrieve_latents(pipe.vae.encode(image[i : i + 1]), generator=generator[i])
234
+ for i in range(1)
235
+ ]
236
+ init_latents = torch.cat(init_latents, dim=0)
237
+ else:
238
+ init_latents = retrieve_latents(pipe.vae.encode(image), generator=generator)
239
+
240
+ if pipe.vae.config.force_upcast:
241
+ pipe.vae.to(originDtype)
242
+
243
+ init_latents = init_latents.to(originDtype)
244
+ init_latents = pipe.vae.config.scaling_factor * init_latents
245
+
246
+ return init_latents.to(dtype=torch.float16)
247
+
248
+ def get_timesteps(pipe, num_inference_steps, strength, device, denoising_start=None):
249
+ # get the original timestep using init_timestep
250
+ if denoising_start is None:
251
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
252
+ t_start = max(num_inference_steps - init_timestep, 0)
253
+ else:
254
+ t_start = 0
255
+
256
+ timesteps = pipe.scheduler.timesteps[t_start * pipe.scheduler.order :]
257
+
258
+ # Strength is irrelevant if we directly request a timestep to start at;
259
+ # that is, strength is determined by the denoising_start instead.
260
+ if denoising_start is not None:
261
+ discrete_timestep_cutoff = int(
262
+ round(
263
+ pipe.scheduler.config.num_train_timesteps
264
+ - (denoising_start * pipe.scheduler.config.num_train_timesteps)
265
+ )
266
+ )
267
+
268
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
269
+ if pipe.scheduler.order == 2 and num_inference_steps % 2 == 0:
270
+ # if the scheduler is a 2nd order scheduler we might have to do +1
271
+ # because `num_inference_steps` might be even given that every timestep
272
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
273
+ # mean that we cut the timesteps in the middle of the denoising step
274
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
275
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
276
+ num_inference_steps = num_inference_steps + 1
277
+
278
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
279
+ timesteps = timesteps[-num_inference_steps:]
280
+ return timesteps, num_inference_steps
281
+
282
+ return timesteps, num_inference_steps - t_start
inversion_utils.py ADDED
@@ -0,0 +1,794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import PIL
4
+
5
+ from typing import List, Optional, Union
6
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
7
+ from PIL import Image
8
+ from diffusers.utils import logging
9
+
10
+ VECTOR_DATA_FOLDER = "vector_data"
11
+ VECTOR_DATA_DICT = "vector_data"
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ def get_ddpm_inversion_scheduler(
16
+ scheduler,
17
+ step_function,
18
+ config,
19
+ timesteps,
20
+ save_timesteps,
21
+ latents,
22
+ x_ts,
23
+ x_ts_c_hat,
24
+ save_intermediate_results,
25
+ pipe,
26
+ x_0,
27
+ v1s_images,
28
+ v2s_images,
29
+ deltas_images,
30
+ v1_x0s,
31
+ v2_x0s,
32
+ deltas_x0s,
33
+ folder_name,
34
+ image_name,
35
+ time_measure_n,
36
+ ):
37
+ def step(
38
+ model_output: torch.FloatTensor,
39
+ timestep: int,
40
+ sample: torch.FloatTensor,
41
+ eta: float = 0.0,
42
+ use_clipped_model_output: bool = False,
43
+ generator=None,
44
+ variance_noise: Optional[torch.FloatTensor] = None,
45
+ return_dict: bool = True,
46
+ ):
47
+ # if scheduler.is_save:
48
+ # start = timer()
49
+ res_inv = step_save_latents(
50
+ scheduler,
51
+ model_output[:1, :, :, :],
52
+ timestep,
53
+ sample[:1, :, :, :],
54
+ eta,
55
+ use_clipped_model_output,
56
+ generator,
57
+ variance_noise,
58
+ return_dict,
59
+ )
60
+ # end = timer()
61
+ # print(f"Run Time Inv: {end - start}")
62
+
63
+ res_inf = step_use_latents(
64
+ scheduler,
65
+ model_output[1:, :, :, :],
66
+ timestep,
67
+ sample[1:, :, :, :],
68
+ eta,
69
+ use_clipped_model_output,
70
+ generator,
71
+ variance_noise,
72
+ return_dict,
73
+ )
74
+ # res = res_inv
75
+ res = (torch.cat((res_inv[0], res_inf[0]), dim=0),)
76
+ return res
77
+ # return res
78
+
79
+ scheduler.step_function = step_function
80
+ scheduler.is_save = True
81
+ scheduler._timesteps = timesteps
82
+ scheduler._save_timesteps = save_timesteps if save_timesteps else timesteps
83
+ scheduler._config = config
84
+ scheduler.latents = latents
85
+ scheduler.x_ts = x_ts
86
+ scheduler.x_ts_c_hat = x_ts_c_hat
87
+ scheduler.step = step
88
+ scheduler.save_intermediate_results = save_intermediate_results
89
+ scheduler.pipe = pipe
90
+ scheduler.v1s_images = v1s_images
91
+ scheduler.v2s_images = v2s_images
92
+ scheduler.deltas_images = deltas_images
93
+ scheduler.v1_x0s = v1_x0s
94
+ scheduler.v2_x0s = v2_x0s
95
+ scheduler.deltas_x0s = deltas_x0s
96
+ scheduler.clean_step_run = False
97
+ scheduler.x_0s = create_xts(
98
+ config.noise_shift_delta,
99
+ config.noise_timesteps,
100
+ config.clean_step_timestep,
101
+ None,
102
+ pipe.scheduler,
103
+ timesteps,
104
+ x_0,
105
+ no_add_noise=True,
106
+ )
107
+ scheduler.folder_name = folder_name
108
+ scheduler.image_name = image_name
109
+ scheduler.p_to_p = False
110
+ scheduler.p_to_p_replace = False
111
+ scheduler.time_measure_n = time_measure_n
112
+ return scheduler
113
+
114
+ def step_save_latents(
115
+ self,
116
+ model_output: torch.FloatTensor,
117
+ timestep: int,
118
+ sample: torch.FloatTensor,
119
+ eta: float = 0.0,
120
+ use_clipped_model_output: bool = False,
121
+ generator=None,
122
+ variance_noise: Optional[torch.FloatTensor] = None,
123
+ return_dict: bool = True,
124
+ ):
125
+ # print(self._save_timesteps)
126
+ # timestep_index = map_timpstep_to_index[timestep]
127
+ # timestep_index = ((self._save_timesteps == timestep).nonzero(as_tuple=True)[0]).item()
128
+ timestep_index = self._save_timesteps.index(timestep) if not self.clean_step_run else -1
129
+ next_timestep_index = timestep_index + 1 if not self.clean_step_run else -1
130
+ u_hat_t = self.step_function(
131
+ model_output=model_output,
132
+ timestep=timestep,
133
+ sample=sample,
134
+ eta=eta,
135
+ use_clipped_model_output=use_clipped_model_output,
136
+ generator=generator,
137
+ variance_noise=variance_noise,
138
+ return_dict=False,
139
+ scheduler=self,
140
+ )
141
+
142
+ x_t_minus_1 = self.x_ts[next_timestep_index]
143
+ self.x_ts_c_hat.append(u_hat_t)
144
+
145
+ z_t = x_t_minus_1 - u_hat_t
146
+ self.latents.append(z_t)
147
+ z_t, _ = normalize(z_t, timestep_index, self._config.max_norm_zs)
148
+
149
+ x_t_minus_1_predicted = u_hat_t + z_t
150
+
151
+ if not return_dict:
152
+ return (x_t_minus_1_predicted,)
153
+
154
+ return DDIMSchedulerOutput(prev_sample=x_t_minus_1, pred_original_sample=None)
155
+
156
+ def step_use_latents(
157
+ self,
158
+ model_output: torch.FloatTensor,
159
+ timestep: int,
160
+ sample: torch.FloatTensor,
161
+ eta: float = 0.0,
162
+ use_clipped_model_output: bool = False,
163
+ generator=None,
164
+ variance_noise: Optional[torch.FloatTensor] = None,
165
+ return_dict: bool = True,
166
+ ):
167
+ # timestep_index = ((self._save_timesteps == timestep).nonzero(as_tuple=True)[0]).item()
168
+ timestep_index = self._timesteps.index(timestep) if not self.clean_step_run else -1
169
+ next_timestep_index = (
170
+ timestep_index + 1 if not self.clean_step_run else -1
171
+ )
172
+ z_t = self.latents[next_timestep_index] # + 1 because latents[0] is X_T
173
+
174
+ _, normalize_coefficient = normalize(
175
+ z_t[0] if self._config.breakdown == "x_t_hat_c_with_zeros" else z_t,
176
+ timestep_index,
177
+ self._config.max_norm_zs,
178
+ )
179
+
180
+ if normalize_coefficient == 0:
181
+ eta = 0
182
+
183
+ # eta = normalize_coefficient
184
+
185
+ x_t_hat_c_hat = self.step_function(
186
+ model_output=model_output,
187
+ timestep=timestep,
188
+ sample=sample,
189
+ eta=eta,
190
+ use_clipped_model_output=use_clipped_model_output,
191
+ generator=generator,
192
+ variance_noise=variance_noise,
193
+ return_dict=False,
194
+ scheduler=self,
195
+ )
196
+
197
+ w1 = self._config.ws1[timestep_index]
198
+ w2 = self._config.ws2[timestep_index]
199
+
200
+ x_t_minus_1_exact = self.x_ts[next_timestep_index]
201
+ x_t_minus_1_exact = x_t_minus_1_exact.expand_as(x_t_hat_c_hat)
202
+
203
+ x_t_c_hat: torch.Tensor = self.x_ts_c_hat[next_timestep_index]
204
+ if self._config.breakdown == "x_t_c_hat":
205
+ raise NotImplementedError("breakdown x_t_c_hat not implemented yet")
206
+
207
+ # x_t_c_hat = x_t_c_hat.expand_as(x_t_hat_c_hat)
208
+ x_t_c = x_t_c_hat[0].expand_as(x_t_hat_c_hat)
209
+
210
+ # if self._config.breakdown == "x_t_c_hat":
211
+ # v1 = x_t_hat_c_hat - x_t_c_hat
212
+ # v2 = x_t_c_hat - x_t_c
213
+ if (
214
+ self._config.breakdown == "x_t_hat_c"
215
+ or self._config.breakdown == "x_t_hat_c_with_zeros"
216
+ ):
217
+ zero_index_reconstruction = 1 if not self.time_measure_n else 0
218
+ edit_prompts_num = (
219
+ (model_output.size(0) - zero_index_reconstruction) // 3
220
+ if self._config.breakdown == "x_t_hat_c_with_zeros" and not self.p_to_p
221
+ else (model_output.size(0) - zero_index_reconstruction) // 2
222
+ )
223
+ x_t_hat_c_indices = (zero_index_reconstruction, edit_prompts_num + zero_index_reconstruction)
224
+ edit_images_indices = (
225
+ edit_prompts_num + zero_index_reconstruction,
226
+ (
227
+ model_output.size(0)
228
+ if self._config.breakdown == "x_t_hat_c"
229
+ else zero_index_reconstruction + 2 * edit_prompts_num
230
+ ),
231
+ )
232
+ x_t_hat_c = torch.zeros_like(x_t_hat_c_hat)
233
+ x_t_hat_c[edit_images_indices[0] : edit_images_indices[1]] = x_t_hat_c_hat[
234
+ x_t_hat_c_indices[0] : x_t_hat_c_indices[1]
235
+ ]
236
+ v1 = x_t_hat_c_hat - x_t_hat_c
237
+ v2 = x_t_hat_c - normalize_coefficient * x_t_c
238
+ if self._config.breakdown == "x_t_hat_c_with_zeros" and not self.p_to_p:
239
+ path = os.path.join(
240
+ self.folder_name,
241
+ VECTOR_DATA_FOLDER,
242
+ self.image_name,
243
+ )
244
+ if not hasattr(self, VECTOR_DATA_DICT):
245
+ os.makedirs(path, exist_ok=True)
246
+ self.vector_data = dict()
247
+
248
+ x_t_0 = x_t_c_hat[1]
249
+ empty_prompt_indices = (1 + 2 * edit_prompts_num, 1 + 3 * edit_prompts_num)
250
+ x_t_hat_0 = x_t_hat_c_hat[empty_prompt_indices[0] : empty_prompt_indices[1]]
251
+
252
+ self.vector_data[timestep.item()] = dict()
253
+ self.vector_data[timestep.item()]["x_t_hat_c"] = x_t_hat_c[
254
+ edit_images_indices[0] : edit_images_indices[1]
255
+ ]
256
+ self.vector_data[timestep.item()]["x_t_hat_0"] = x_t_hat_0
257
+ self.vector_data[timestep.item()]["x_t_c"] = x_t_c[0].expand_as(x_t_hat_0)
258
+ self.vector_data[timestep.item()]["x_t_0"] = x_t_0.expand_as(x_t_hat_0)
259
+ self.vector_data[timestep.item()]["x_t_hat_c_hat"] = x_t_hat_c_hat[
260
+ edit_images_indices[0] : edit_images_indices[1]
261
+ ]
262
+ self.vector_data[timestep.item()]["x_t_minus_1_noisy"] = x_t_minus_1_exact[
263
+ 0
264
+ ].expand_as(x_t_hat_0)
265
+ self.vector_data[timestep.item()]["x_t_minus_1_clean"] = self.x_0s[
266
+ next_timestep_index
267
+ ].expand_as(x_t_hat_0)
268
+
269
+ else: # no breakdown
270
+ v1 = x_t_hat_c_hat - normalize_coefficient * x_t_c
271
+ v2 = 0
272
+
273
+ if self.save_intermediate_results and not self.p_to_p:
274
+ delta = v1 + v2
275
+ v1_plus_x0 = self.x_0s[next_timestep_index] + v1
276
+ v2_plus_x0 = self.x_0s[next_timestep_index] + v2
277
+ delta_plus_x0 = self.x_0s[next_timestep_index] + delta
278
+
279
+ v1_images = decode_latents(v1, self.pipe)
280
+ self.v1s_images.append(v1_images)
281
+ v2_images = (
282
+ decode_latents(v2, self.pipe)
283
+ if self._config.breakdown != "no_breakdown"
284
+ else [PIL.Image.new("RGB", (1, 1))]
285
+ )
286
+ self.v2s_images.append(v2_images)
287
+ delta_images = decode_latents(delta, self.pipe)
288
+ self.deltas_images.append(delta_images)
289
+ v1_plus_x0_images = decode_latents(v1_plus_x0, self.pipe)
290
+ self.v1_x0s.append(v1_plus_x0_images)
291
+ v2_plus_x0_images = (
292
+ decode_latents(v2_plus_x0, self.pipe)
293
+ if self._config.breakdown != "no_breakdown"
294
+ else [PIL.Image.new("RGB", (1, 1))]
295
+ )
296
+ self.v2_x0s.append(v2_plus_x0_images)
297
+ delta_plus_x0_images = decode_latents(delta_plus_x0, self.pipe)
298
+ self.deltas_x0s.append(delta_plus_x0_images)
299
+
300
+ # print(f"v1 norm: {torch.norm(v1, dim=0).mean()}")
301
+ # if self._config.breakdown != "no_breakdown":
302
+ # print(f"v2 norm: {torch.norm(v2, dim=0).mean()}")
303
+ # print(f"v sum norm: {torch.norm(v1 + v2, dim=0).mean()}")
304
+
305
+ x_t_minus_1 = normalize_coefficient * x_t_minus_1_exact + w1 * v1 + w2 * v2
306
+
307
+ if (
308
+ self._config.breakdown == "x_t_hat_c"
309
+ or self._config.breakdown == "x_t_hat_c_with_zeros"
310
+ ):
311
+ x_t_minus_1[x_t_hat_c_indices[0] : x_t_hat_c_indices[1]] = x_t_minus_1[
312
+ edit_images_indices[0] : edit_images_indices[1]
313
+ ] # update x_t_hat_c to be x_t_hat_c_hat
314
+ if self._config.breakdown == "x_t_hat_c_with_zeros" and not self.p_to_p:
315
+ x_t_minus_1[empty_prompt_indices[0] : empty_prompt_indices[1]] = (
316
+ x_t_minus_1[edit_images_indices[0] : edit_images_indices[1]]
317
+ )
318
+ self.vector_data[timestep.item()]["x_t_minus_1_edited"] = x_t_minus_1[
319
+ edit_images_indices[0] : edit_images_indices[1]
320
+ ]
321
+ if timestep == self._timesteps[-1]:
322
+ torch.save(
323
+ self.vector_data,
324
+ os.path.join(
325
+ path,
326
+ f"{VECTOR_DATA_DICT}.pt",
327
+ ),
328
+ )
329
+ # p_to_p_force_perfect_reconstruction
330
+ if not self.time_measure_n:
331
+ x_t_minus_1[0] = x_t_minus_1_exact[0]
332
+
333
+ if not return_dict:
334
+ return (x_t_minus_1,)
335
+
336
+ return DDIMSchedulerOutput(
337
+ prev_sample=x_t_minus_1,
338
+ pred_original_sample=None,
339
+ )
340
+
341
+ def create_xts(
342
+ noise_shift_delta,
343
+ noise_timesteps,
344
+ clean_step_timestep,
345
+ generator,
346
+ scheduler,
347
+ timesteps,
348
+ x_0,
349
+ no_add_noise=False,
350
+ ):
351
+ if noise_timesteps is None:
352
+ noising_delta = noise_shift_delta * (timesteps[0] - timesteps[1])
353
+ noise_timesteps = [timestep - int(noising_delta) for timestep in timesteps]
354
+
355
+ first_x_0_idx = len(noise_timesteps)
356
+ for i in range(len(noise_timesteps)):
357
+ if noise_timesteps[i] <= 0:
358
+ first_x_0_idx = i
359
+ break
360
+
361
+ noise_timesteps = noise_timesteps[:first_x_0_idx]
362
+
363
+ x_0_expanded = x_0.expand(len(noise_timesteps), -1, -1, -1)
364
+ noise = (
365
+ torch.randn(x_0_expanded.size(), generator=generator, device="cpu").to(
366
+ x_0.device
367
+ )
368
+ if not no_add_noise
369
+ else torch.zeros_like(x_0_expanded)
370
+ )
371
+ x_ts = scheduler.add_noise(
372
+ x_0_expanded,
373
+ noise,
374
+ torch.IntTensor(noise_timesteps),
375
+ )
376
+ x_ts = [t.unsqueeze(dim=0) for t in list(x_ts)]
377
+ x_ts += [x_0] * (len(timesteps) - first_x_0_idx)
378
+ x_ts += [x_0]
379
+ if clean_step_timestep > 0:
380
+ x_ts += [x_0]
381
+ return x_ts
382
+
383
+ def normalize(
384
+ z_t,
385
+ i,
386
+ max_norm_zs,
387
+ ):
388
+ max_norm = max_norm_zs[i]
389
+ if max_norm < 0:
390
+ return z_t, 1
391
+
392
+ norm = torch.norm(z_t)
393
+ if norm < max_norm:
394
+ return z_t, 1
395
+
396
+ coeff = max_norm / norm
397
+ z_t = z_t * coeff
398
+ return z_t, coeff
399
+
400
+ def decode_latents(latent, pipe):
401
+ latent_img = pipe.vae.decode(
402
+ latent / pipe.vae.config.scaling_factor, return_dict=False
403
+ )[0]
404
+ return pipe.image_processor.postprocess(latent_img, output_type="pil")
405
+
406
+ def deterministic_ddim_step(
407
+ model_output: torch.FloatTensor,
408
+ timestep: int,
409
+ sample: torch.FloatTensor,
410
+ eta: float = 0.0,
411
+ use_clipped_model_output: bool = False,
412
+ generator=None,
413
+ variance_noise: Optional[torch.FloatTensor] = None,
414
+ return_dict: bool = True,
415
+ scheduler=None,
416
+ ):
417
+
418
+ if scheduler.num_inference_steps is None:
419
+ raise ValueError(
420
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
421
+ )
422
+
423
+ prev_timestep = (
424
+ timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
425
+ )
426
+
427
+ # 2. compute alphas, betas
428
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
429
+ alpha_prod_t_prev = (
430
+ scheduler.alphas_cumprod[prev_timestep]
431
+ if prev_timestep >= 0
432
+ else scheduler.final_alpha_cumprod
433
+ )
434
+
435
+ beta_prod_t = 1 - alpha_prod_t
436
+
437
+ if scheduler.config.prediction_type == "epsilon":
438
+ pred_original_sample = (
439
+ sample - beta_prod_t ** (0.5) * model_output
440
+ ) / alpha_prod_t ** (0.5)
441
+ pred_epsilon = model_output
442
+ elif scheduler.config.prediction_type == "sample":
443
+ pred_original_sample = model_output
444
+ pred_epsilon = (
445
+ sample - alpha_prod_t ** (0.5) * pred_original_sample
446
+ ) / beta_prod_t ** (0.5)
447
+ elif scheduler.config.prediction_type == "v_prediction":
448
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (
449
+ beta_prod_t**0.5
450
+ ) * model_output
451
+ pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
452
+ else:
453
+ raise ValueError(
454
+ f"prediction_type given as {scheduler.config.prediction_type} must be one of `epsilon`, `sample`, or"
455
+ " `v_prediction`"
456
+ )
457
+
458
+ # 4. Clip or threshold "predicted x_0"
459
+ if scheduler.config.thresholding:
460
+ pred_original_sample = scheduler._threshold_sample(pred_original_sample)
461
+ elif scheduler.config.clip_sample:
462
+ pred_original_sample = pred_original_sample.clamp(
463
+ -scheduler.config.clip_sample_range,
464
+ scheduler.config.clip_sample_range,
465
+ )
466
+
467
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
468
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
469
+ variance = scheduler._get_variance(timestep, prev_timestep)
470
+ std_dev_t = eta * variance ** (0.5)
471
+
472
+ if use_clipped_model_output:
473
+ # the pred_epsilon is always re-derived from the clipped x_0 in Glide
474
+ pred_epsilon = (
475
+ sample - alpha_prod_t ** (0.5) * pred_original_sample
476
+ ) / beta_prod_t ** (0.5)
477
+
478
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
479
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (
480
+ 0.5
481
+ ) * pred_epsilon
482
+
483
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
484
+ prev_sample = (
485
+ alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
486
+ )
487
+ return prev_sample
488
+
489
+
490
+ def deterministic_euler_step(
491
+ model_output: torch.FloatTensor,
492
+ timestep: Union[float, torch.FloatTensor],
493
+ sample: torch.FloatTensor,
494
+ eta,
495
+ use_clipped_model_output,
496
+ generator,
497
+ variance_noise,
498
+ return_dict,
499
+ scheduler,
500
+ ):
501
+ """
502
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
503
+ process from the learned model outputs (most often the predicted noise).
504
+
505
+ Args:
506
+ model_output (`torch.FloatTensor`):
507
+ The direct output from learned diffusion model.
508
+ timestep (`float`):
509
+ The current discrete timestep in the diffusion chain.
510
+ sample (`torch.FloatTensor`):
511
+ A current instance of a sample created by the diffusion process.
512
+ generator (`torch.Generator`, *optional*):
513
+ A random number generator.
514
+ return_dict (`bool`):
515
+ Whether or not to return a
516
+ [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or tuple.
517
+
518
+ Returns:
519
+ [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or `tuple`:
520
+ If return_dict is `True`,
521
+ [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] is returned,
522
+ otherwise a tuple is returned where the first element is the sample tensor.
523
+
524
+ """
525
+
526
+ if (
527
+ isinstance(timestep, int)
528
+ or isinstance(timestep, torch.IntTensor)
529
+ or isinstance(timestep, torch.LongTensor)
530
+ ):
531
+ raise ValueError(
532
+ (
533
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
534
+ " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
535
+ " one of the `scheduler.timesteps` as a timestep."
536
+ ),
537
+ )
538
+
539
+ if scheduler.step_index is None:
540
+ scheduler._init_step_index(timestep)
541
+
542
+ sigma = scheduler.sigmas[scheduler.step_index]
543
+
544
+ # Upcast to avoid precision issues when computing prev_sample
545
+ sample = sample.to(torch.float32)
546
+
547
+ # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
548
+ if scheduler.config.prediction_type == "epsilon":
549
+ pred_original_sample = sample - sigma * model_output
550
+ elif scheduler.config.prediction_type == "v_prediction":
551
+ # * c_out + input * c_skip
552
+ pred_original_sample = model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (
553
+ sample / (sigma**2 + 1)
554
+ )
555
+ elif scheduler.config.prediction_type == "sample":
556
+ raise NotImplementedError("prediction_type not implemented yet: sample")
557
+ else:
558
+ raise ValueError(
559
+ f"prediction_type given as {scheduler.config.prediction_type} must be one of `epsilon`, or `v_prediction`"
560
+ )
561
+
562
+ sigma_from = scheduler.sigmas[scheduler.step_index]
563
+ sigma_to = scheduler.sigmas[scheduler.step_index + 1]
564
+ sigma_up = (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
565
+ sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
566
+
567
+ # 2. Convert to an ODE derivative
568
+ derivative = (sample - pred_original_sample) / sigma
569
+
570
+ dt = sigma_down - sigma
571
+
572
+ prev_sample = sample + derivative * dt
573
+
574
+ # Cast sample back to model compatible dtype
575
+ prev_sample = prev_sample.to(model_output.dtype)
576
+
577
+ # upon completion increase step index by one
578
+ scheduler._step_index += 1
579
+
580
+ return prev_sample
581
+
582
+
583
+ def deterministic_non_ancestral_euler_step(
584
+ model_output: torch.FloatTensor,
585
+ timestep: Union[float, torch.FloatTensor],
586
+ sample: torch.FloatTensor,
587
+ eta: float = 0.0,
588
+ use_clipped_model_output: bool = False,
589
+ s_churn: float = 0.0,
590
+ s_tmin: float = 0.0,
591
+ s_tmax: float = float("inf"),
592
+ s_noise: float = 1.0,
593
+ generator: Optional[torch.Generator] = None,
594
+ variance_noise: Optional[torch.FloatTensor] = None,
595
+ return_dict: bool = True,
596
+ scheduler=None,
597
+ ):
598
+ """
599
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
600
+ process from the learned model outputs (most often the predicted noise).
601
+
602
+ Args:
603
+ model_output (`torch.FloatTensor`):
604
+ The direct output from learned diffusion model.
605
+ timestep (`float`):
606
+ The current discrete timestep in the diffusion chain.
607
+ sample (`torch.FloatTensor`):
608
+ A current instance of a sample created by the diffusion process.
609
+ s_churn (`float`):
610
+ s_tmin (`float`):
611
+ s_tmax (`float`):
612
+ s_noise (`float`, defaults to 1.0):
613
+ Scaling factor for noise added to the sample.
614
+ generator (`torch.Generator`, *optional*):
615
+ A random number generator.
616
+ return_dict (`bool`):
617
+ Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
618
+ tuple.
619
+
620
+ Returns:
621
+ [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
622
+ If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
623
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
624
+ """
625
+
626
+ if (
627
+ isinstance(timestep, int)
628
+ or isinstance(timestep, torch.IntTensor)
629
+ or isinstance(timestep, torch.LongTensor)
630
+ ):
631
+ raise ValueError(
632
+ (
633
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
634
+ " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
635
+ " one of the `scheduler.timesteps` as a timestep."
636
+ ),
637
+ )
638
+
639
+ if not scheduler.is_scale_input_called:
640
+ logger.warning(
641
+ "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
642
+ "See `StableDiffusionPipeline` for a usage example."
643
+ )
644
+
645
+ if scheduler.step_index is None:
646
+ scheduler._init_step_index(timestep)
647
+
648
+ # Upcast to avoid precision issues when computing prev_sample
649
+ sample = sample.to(torch.float32)
650
+
651
+ sigma = scheduler.sigmas[scheduler.step_index]
652
+
653
+ gamma = (
654
+ min(s_churn / (len(scheduler.sigmas) - 1), 2**0.5 - 1)
655
+ if s_tmin <= sigma <= s_tmax
656
+ else 0.0
657
+ )
658
+
659
+ sigma_hat = sigma * (gamma + 1)
660
+
661
+ # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
662
+ # NOTE: "original_sample" should not be an expected prediction_type but is left in for
663
+ # backwards compatibility
664
+ if (
665
+ scheduler.config.prediction_type == "original_sample"
666
+ or scheduler.config.prediction_type == "sample"
667
+ ):
668
+ pred_original_sample = model_output
669
+ elif scheduler.config.prediction_type == "epsilon":
670
+ pred_original_sample = sample - sigma_hat * model_output
671
+ elif scheduler.config.prediction_type == "v_prediction":
672
+ # denoised = model_output * c_out + input * c_skip
673
+ pred_original_sample = model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (
674
+ sample / (sigma**2 + 1)
675
+ )
676
+ else:
677
+ raise ValueError(
678
+ f"prediction_type given as {scheduler.config.prediction_type} must be one of `epsilon`, or `v_prediction`"
679
+ )
680
+
681
+ # 2. Convert to an ODE derivative
682
+ derivative = (sample - pred_original_sample) / sigma_hat
683
+
684
+ dt = scheduler.sigmas[scheduler.step_index + 1] - sigma_hat
685
+
686
+ prev_sample = sample + derivative * dt
687
+
688
+ # Cast sample back to model compatible dtype
689
+ prev_sample = prev_sample.to(model_output.dtype)
690
+
691
+ # upon completion increase step index by one
692
+ scheduler._step_index += 1
693
+
694
+ return prev_sample
695
+
696
+
697
+ def deterministic_ddpm_step(
698
+ model_output: torch.FloatTensor,
699
+ timestep: Union[float, torch.FloatTensor],
700
+ sample: torch.FloatTensor,
701
+ eta,
702
+ use_clipped_model_output,
703
+ generator,
704
+ variance_noise,
705
+ return_dict,
706
+ scheduler,
707
+ ):
708
+ """
709
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
710
+ process from the learned model outputs (most often the predicted noise).
711
+
712
+ Args:
713
+ model_output (`torch.FloatTensor`):
714
+ The direct output from learned diffusion model.
715
+ timestep (`float`):
716
+ The current discrete timestep in the diffusion chain.
717
+ sample (`torch.FloatTensor`):
718
+ A current instance of a sample created by the diffusion process.
719
+ generator (`torch.Generator`, *optional*):
720
+ A random number generator.
721
+ return_dict (`bool`, *optional*, defaults to `True`):
722
+ Whether or not to return a [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`.
723
+
724
+ Returns:
725
+ [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`:
726
+ If return_dict is `True`, [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] is returned, otherwise a
727
+ tuple is returned where the first element is the sample tensor.
728
+
729
+ """
730
+ t = timestep
731
+
732
+ prev_t = scheduler.previous_timestep(t)
733
+
734
+ if model_output.shape[1] == sample.shape[1] * 2 and scheduler.variance_type in [
735
+ "learned",
736
+ "learned_range",
737
+ ]:
738
+ model_output, predicted_variance = torch.split(
739
+ model_output, sample.shape[1], dim=1
740
+ )
741
+ else:
742
+ predicted_variance = None
743
+
744
+ # 1. compute alphas, betas
745
+ alpha_prod_t = scheduler.alphas_cumprod[t]
746
+ alpha_prod_t_prev = (
747
+ scheduler.alphas_cumprod[prev_t] if prev_t >= 0 else scheduler.one
748
+ )
749
+ beta_prod_t = 1 - alpha_prod_t
750
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
751
+ current_alpha_t = alpha_prod_t / alpha_prod_t_prev
752
+ current_beta_t = 1 - current_alpha_t
753
+
754
+ # 2. compute predicted original sample from predicted noise also called
755
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
756
+ if scheduler.config.prediction_type == "epsilon":
757
+ pred_original_sample = (
758
+ sample - beta_prod_t ** (0.5) * model_output
759
+ ) / alpha_prod_t ** (0.5)
760
+ elif scheduler.config.prediction_type == "sample":
761
+ pred_original_sample = model_output
762
+ elif scheduler.config.prediction_type == "v_prediction":
763
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (
764
+ beta_prod_t**0.5
765
+ ) * model_output
766
+ else:
767
+ raise ValueError(
768
+ f"prediction_type given as {scheduler.config.prediction_type} must be one of `epsilon`, `sample` or"
769
+ " `v_prediction` for the DDPMScheduler."
770
+ )
771
+
772
+ # 3. Clip or threshold "predicted x_0"
773
+ if scheduler.config.thresholding:
774
+ pred_original_sample = scheduler._threshold_sample(pred_original_sample)
775
+ elif scheduler.config.clip_sample:
776
+ pred_original_sample = pred_original_sample.clamp(
777
+ -scheduler.config.clip_sample_range, scheduler.config.clip_sample_range
778
+ )
779
+
780
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
781
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
782
+ pred_original_sample_coeff = (
783
+ alpha_prod_t_prev ** (0.5) * current_beta_t
784
+ ) / beta_prod_t
785
+ current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t
786
+
787
+ # 5. Compute predicted previous sample µ_t
788
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
789
+ pred_prev_sample = (
790
+ pred_original_sample_coeff * pred_original_sample
791
+ + current_sample_coeff * sample
792
+ )
793
+
794
+ return pred_prev_sample
pipelines/pipeline_sdxl_adapter_img2img.py ADDED
@@ -0,0 +1,1672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import (
22
+ CLIPImageProcessor,
23
+ CLIPTextModel,
24
+ CLIPTextModelWithProjection,
25
+ CLIPTokenizer,
26
+ CLIPVisionModelWithProjection,
27
+ )
28
+
29
+ from diffusers.callbacks import (
30
+ MultiPipelineCallbacks,
31
+ PipelineCallback,
32
+ )
33
+
34
+ from diffusers.image_processor import (
35
+ PipelineImageInput,
36
+ VaeImageProcessor,
37
+ )
38
+
39
+ from diffusers.loaders import (
40
+ FromSingleFileMixin,
41
+ IPAdapterMixin,
42
+ StableDiffusionXLLoraLoaderMixin,
43
+ TextualInversionLoaderMixin,
44
+ )
45
+
46
+ from diffusers.models import (
47
+ AutoencoderKL,
48
+ ImageProjection,
49
+ MultiAdapter,
50
+ T2IAdapter,
51
+ UNet2DConditionModel,
52
+ )
53
+
54
+ from diffusers.models.attention_processor import (
55
+ AttnProcessor2_0,
56
+ XFormersAttnProcessor,
57
+ )
58
+
59
+ from diffusers.models.lora import (
60
+ adjust_lora_scale_text_encoder,
61
+ )
62
+
63
+ from diffusers.schedulers import (
64
+ KarrasDiffusionSchedulers,
65
+ )
66
+
67
+ from diffusers.utils import (
68
+ PIL_INTERPOLATION,
69
+ USE_PEFT_BACKEND,
70
+ deprecate,
71
+ is_invisible_watermark_available,
72
+ is_torch_xla_available,
73
+ logging,
74
+ replace_example_docstring,
75
+ scale_lora_layers,
76
+ unscale_lora_layers,
77
+ )
78
+
79
+ from diffusers.utils.torch_utils import (
80
+ randn_tensor,
81
+ )
82
+
83
+ from diffusers.pipelines.pipeline_utils import (
84
+ DiffusionPipeline,
85
+ StableDiffusionMixin,
86
+ )
87
+
88
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import (
89
+ StableDiffusionXLPipelineOutput,
90
+ )
91
+
92
+
93
+ if is_invisible_watermark_available():
94
+ from diffusers.pipelines.stable_diffusion_xl.watermark import (
95
+ StableDiffusionXLWatermarker,
96
+ )
97
+
98
+ if is_torch_xla_available():
99
+ import torch_xla.core.xla_model as xm
100
+
101
+ XLA_AVAILABLE = True
102
+ else:
103
+ XLA_AVAILABLE = False
104
+
105
+
106
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
107
+
108
+ EXAMPLE_DOC_STRING = """
109
+ Examples:
110
+ ```py
111
+ >>> import torch
112
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
113
+ >>> from diffusers.utils import load_image
114
+
115
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
116
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
117
+ ... )
118
+ >>> pipe = pipe.to("cuda")
119
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
120
+
121
+ >>> init_image = load_image(url).convert("RGB")
122
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
123
+ >>> image = pipe(prompt, image=init_image).images[0]
124
+ ```
125
+ """
126
+
127
+
128
+ def _preprocess_adapter_image(image, height, width):
129
+ if isinstance(image, torch.Tensor):
130
+ return image
131
+ elif isinstance(image, PIL.Image.Image):
132
+ image = [image]
133
+
134
+ if isinstance(image[0], PIL.Image.Image):
135
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
136
+ image = [
137
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
138
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
139
+ image = np.concatenate(image, axis=0)
140
+ image = np.array(image).astype(np.float32) / 255.0
141
+ image = image.transpose(0, 3, 1, 2)
142
+ image = torch.from_numpy(image)
143
+ elif isinstance(image[0], torch.Tensor):
144
+ if image[0].ndim == 3:
145
+ image = torch.stack(image, dim=0)
146
+ elif image[0].ndim == 4:
147
+ image = torch.cat(image, dim=0)
148
+ else:
149
+ raise ValueError(
150
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
151
+ )
152
+ return image
153
+
154
+
155
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
156
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
157
+ """
158
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
159
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
160
+ """
161
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
162
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
163
+ # rescale the results from guidance (fixes overexposure)
164
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
165
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
166
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
167
+ return noise_cfg
168
+
169
+
170
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
171
+ def retrieve_latents(
172
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
173
+ ):
174
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
175
+ return encoder_output.latent_dist.sample(generator)
176
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
177
+ return encoder_output.latent_dist.mode()
178
+ elif hasattr(encoder_output, "latents"):
179
+ return encoder_output.latents
180
+ else:
181
+ raise AttributeError("Could not access latents of provided encoder_output")
182
+
183
+
184
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
185
+ def retrieve_timesteps(
186
+ scheduler,
187
+ num_inference_steps: Optional[int] = None,
188
+ device: Optional[Union[str, torch.device]] = None,
189
+ timesteps: Optional[List[int]] = None,
190
+ sigmas: Optional[List[float]] = None,
191
+ **kwargs,
192
+ ):
193
+ """
194
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
195
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
196
+
197
+ Args:
198
+ scheduler (`SchedulerMixin`):
199
+ The scheduler to get timesteps from.
200
+ num_inference_steps (`int`):
201
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
202
+ must be `None`.
203
+ device (`str` or `torch.device`, *optional*):
204
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
205
+ timesteps (`List[int]`, *optional*):
206
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
207
+ `num_inference_steps` and `sigmas` must be `None`.
208
+ sigmas (`List[float]`, *optional*):
209
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
210
+ `num_inference_steps` and `timesteps` must be `None`.
211
+
212
+ Returns:
213
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
214
+ second element is the number of inference steps.
215
+ """
216
+ if timesteps is not None and sigmas is not None:
217
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
218
+ if timesteps is not None:
219
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
220
+ if not accepts_timesteps:
221
+ raise ValueError(
222
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
223
+ f" timestep schedules. Please check whether you are using the correct scheduler."
224
+ )
225
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
226
+ timesteps = scheduler.timesteps
227
+ num_inference_steps = len(timesteps)
228
+ elif sigmas is not None:
229
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
230
+ if not accept_sigmas:
231
+ raise ValueError(
232
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
233
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
234
+ )
235
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
236
+ timesteps = scheduler.timesteps
237
+ num_inference_steps = len(timesteps)
238
+ else:
239
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
240
+ timesteps = scheduler.timesteps
241
+ return timesteps, num_inference_steps
242
+
243
+
244
+ class StableDiffusionXLImg2ImgPipeline(
245
+ DiffusionPipeline,
246
+ StableDiffusionMixin,
247
+ TextualInversionLoaderMixin,
248
+ FromSingleFileMixin,
249
+ StableDiffusionXLLoraLoaderMixin,
250
+ IPAdapterMixin,
251
+ ):
252
+ r"""
253
+ Pipeline for text-to-image generation using Stable Diffusion XL.
254
+
255
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
256
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
257
+
258
+ The pipeline also inherits the following loading methods:
259
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
260
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
261
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
262
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
263
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
264
+
265
+ Args:
266
+ vae ([`AutoencoderKL`]):
267
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
268
+ text_encoder ([`CLIPTextModel`]):
269
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
270
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
271
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
272
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
273
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
274
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
275
+ specifically the
276
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
277
+ variant.
278
+ tokenizer (`CLIPTokenizer`):
279
+ Tokenizer of class
280
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
281
+ tokenizer_2 (`CLIPTokenizer`):
282
+ Second Tokenizer of class
283
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
284
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
285
+ scheduler ([`SchedulerMixin`]):
286
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
287
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
288
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
289
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
290
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
291
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
292
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
293
+ `stabilityai/stable-diffusion-xl-base-1-0`.
294
+ add_watermarker (`bool`, *optional*):
295
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
296
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
297
+ watermarker will be used.
298
+ """
299
+
300
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
301
+ _optional_components = [
302
+ "tokenizer",
303
+ "tokenizer_2",
304
+ "text_encoder",
305
+ "text_encoder_2",
306
+ "image_encoder",
307
+ "feature_extractor",
308
+ ]
309
+ _callback_tensor_inputs = [
310
+ "latents",
311
+ "prompt_embeds",
312
+ "negative_prompt_embeds",
313
+ "add_text_embeds",
314
+ "add_time_ids",
315
+ "negative_pooled_prompt_embeds",
316
+ "add_neg_time_ids",
317
+ ]
318
+
319
+ def __init__(
320
+ self,
321
+ vae: AutoencoderKL,
322
+ text_encoder: CLIPTextModel,
323
+ text_encoder_2: CLIPTextModelWithProjection,
324
+ tokenizer: CLIPTokenizer,
325
+ tokenizer_2: CLIPTokenizer,
326
+ unet: UNet2DConditionModel,
327
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
328
+ scheduler: KarrasDiffusionSchedulers,
329
+ image_encoder: CLIPVisionModelWithProjection = None,
330
+ feature_extractor: CLIPImageProcessor = None,
331
+ requires_aesthetics_score: bool = False,
332
+ force_zeros_for_empty_prompt: bool = True,
333
+ add_watermarker: Optional[bool] = None,
334
+ ):
335
+ super().__init__()
336
+
337
+ self.register_modules(
338
+ vae=vae,
339
+ text_encoder=text_encoder,
340
+ text_encoder_2=text_encoder_2,
341
+ tokenizer=tokenizer,
342
+ tokenizer_2=tokenizer_2,
343
+ unet=unet,
344
+ adapter=adapter,
345
+ image_encoder=image_encoder,
346
+ feature_extractor=feature_extractor,
347
+ scheduler=scheduler,
348
+ )
349
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
350
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
351
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
352
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
353
+
354
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
355
+
356
+ if add_watermarker:
357
+ self.watermark = StableDiffusionXLWatermarker()
358
+ else:
359
+ self.watermark = None
360
+
361
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
362
+ def encode_prompt(
363
+ self,
364
+ prompt: str,
365
+ prompt_2: Optional[str] = None,
366
+ device: Optional[torch.device] = None,
367
+ num_images_per_prompt: int = 1,
368
+ do_classifier_free_guidance: bool = True,
369
+ negative_prompt: Optional[str] = None,
370
+ negative_prompt_2: Optional[str] = None,
371
+ prompt_embeds: Optional[torch.Tensor] = None,
372
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
373
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
374
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
375
+ lora_scale: Optional[float] = None,
376
+ clip_skip: Optional[int] = None,
377
+ ):
378
+ r"""
379
+ Encodes the prompt into text encoder hidden states.
380
+
381
+ Args:
382
+ prompt (`str` or `List[str]`, *optional*):
383
+ prompt to be encoded
384
+ prompt_2 (`str` or `List[str]`, *optional*):
385
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
386
+ used in both text-encoders
387
+ device: (`torch.device`):
388
+ torch device
389
+ num_images_per_prompt (`int`):
390
+ number of images that should be generated per prompt
391
+ do_classifier_free_guidance (`bool`):
392
+ whether to use classifier free guidance or not
393
+ negative_prompt (`str` or `List[str]`, *optional*):
394
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
395
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
396
+ less than `1`).
397
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
398
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
399
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
400
+ prompt_embeds (`torch.Tensor`, *optional*):
401
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
402
+ provided, text embeddings will be generated from `prompt` input argument.
403
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
404
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
405
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
406
+ argument.
407
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
408
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
409
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
410
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
411
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
412
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
413
+ input argument.
414
+ lora_scale (`float`, *optional*):
415
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
416
+ clip_skip (`int`, *optional*):
417
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
418
+ the output of the pre-final layer will be used for computing the prompt embeddings.
419
+ """
420
+ device = device or self._execution_device
421
+
422
+ # set lora scale so that monkey patched LoRA
423
+ # function of text encoder can correctly access it
424
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
425
+ self._lora_scale = lora_scale
426
+
427
+ # dynamically adjust the LoRA scale
428
+ if self.text_encoder is not None:
429
+ if not USE_PEFT_BACKEND:
430
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
431
+ else:
432
+ scale_lora_layers(self.text_encoder, lora_scale)
433
+
434
+ if self.text_encoder_2 is not None:
435
+ if not USE_PEFT_BACKEND:
436
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
437
+ else:
438
+ scale_lora_layers(self.text_encoder_2, lora_scale)
439
+
440
+ prompt = [prompt] if isinstance(prompt, str) else prompt
441
+
442
+ if prompt is not None:
443
+ batch_size = len(prompt)
444
+ else:
445
+ batch_size = prompt_embeds.shape[0]
446
+
447
+ # Define tokenizers and text encoders
448
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
449
+ text_encoders = (
450
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
451
+ )
452
+
453
+ if prompt_embeds is None:
454
+ prompt_2 = prompt_2 or prompt
455
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
456
+
457
+ # textual inversion: process multi-vector tokens if necessary
458
+ prompt_embeds_list = []
459
+ prompts = [prompt, prompt_2]
460
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
461
+ if isinstance(self, TextualInversionLoaderMixin):
462
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
463
+
464
+ text_inputs = tokenizer(
465
+ prompt,
466
+ padding="max_length",
467
+ max_length=tokenizer.model_max_length,
468
+ truncation=True,
469
+ return_tensors="pt",
470
+ )
471
+
472
+ text_input_ids = text_inputs.input_ids
473
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
474
+
475
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
476
+ text_input_ids, untruncated_ids
477
+ ):
478
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
479
+ logger.warning(
480
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
481
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
482
+ )
483
+
484
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
485
+
486
+ # We are only ALWAYS interested in the pooled output of the final text encoder
487
+ pooled_prompt_embeds = prompt_embeds[0]
488
+ if clip_skip is None:
489
+ prompt_embeds = prompt_embeds.hidden_states[-2]
490
+ else:
491
+ # "2" because SDXL always indexes from the penultimate layer.
492
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
493
+
494
+ prompt_embeds_list.append(prompt_embeds)
495
+
496
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
497
+
498
+ # get unconditional embeddings for classifier free guidance
499
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
500
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
501
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
502
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
503
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
504
+ negative_prompt = negative_prompt or ""
505
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
506
+
507
+ # normalize str to list
508
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
509
+ negative_prompt_2 = (
510
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
511
+ )
512
+
513
+ uncond_tokens: List[str]
514
+ if prompt is not None and type(prompt) is not type(negative_prompt):
515
+ raise TypeError(
516
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
517
+ f" {type(prompt)}."
518
+ )
519
+ elif batch_size != len(negative_prompt):
520
+ raise ValueError(
521
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
522
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
523
+ " the batch size of `prompt`."
524
+ )
525
+ else:
526
+ uncond_tokens = [negative_prompt, negative_prompt_2]
527
+
528
+ negative_prompt_embeds_list = []
529
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
530
+ if isinstance(self, TextualInversionLoaderMixin):
531
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
532
+
533
+ max_length = prompt_embeds.shape[1]
534
+ uncond_input = tokenizer(
535
+ negative_prompt,
536
+ padding="max_length",
537
+ max_length=max_length,
538
+ truncation=True,
539
+ return_tensors="pt",
540
+ )
541
+
542
+ negative_prompt_embeds = text_encoder(
543
+ uncond_input.input_ids.to(device),
544
+ output_hidden_states=True,
545
+ )
546
+ # We are only ALWAYS interested in the pooled output of the final text encoder
547
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
548
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
549
+
550
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
551
+
552
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
553
+
554
+ if self.text_encoder_2 is not None:
555
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
556
+ else:
557
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
558
+
559
+ bs_embed, seq_len, _ = prompt_embeds.shape
560
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
561
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
562
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
563
+
564
+ if do_classifier_free_guidance:
565
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
566
+ seq_len = negative_prompt_embeds.shape[1]
567
+
568
+ if self.text_encoder_2 is not None:
569
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
570
+ else:
571
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
572
+
573
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
574
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
575
+
576
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
577
+ bs_embed * num_images_per_prompt, -1
578
+ )
579
+ if do_classifier_free_guidance:
580
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
581
+ bs_embed * num_images_per_prompt, -1
582
+ )
583
+
584
+ if self.text_encoder is not None:
585
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
586
+ # Retrieve the original scale by scaling back the LoRA layers
587
+ unscale_lora_layers(self.text_encoder, lora_scale)
588
+
589
+ if self.text_encoder_2 is not None:
590
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
591
+ # Retrieve the original scale by scaling back the LoRA layers
592
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
593
+
594
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
595
+
596
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
597
+ def prepare_ip_adapter_image_embeds(
598
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
599
+ ):
600
+ image_embeds = []
601
+ if do_classifier_free_guidance:
602
+ negative_image_embeds = []
603
+ if ip_adapter_image_embeds is None:
604
+ if not isinstance(ip_adapter_image, list):
605
+ ip_adapter_image = [ip_adapter_image]
606
+
607
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
608
+ raise ValueError(
609
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
610
+ )
611
+
612
+ for single_ip_adapter_image, image_proj_layer in zip(
613
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
614
+ ):
615
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
616
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
617
+ single_ip_adapter_image, device, 1, output_hidden_state
618
+ )
619
+
620
+ image_embeds.append(single_image_embeds[None, :])
621
+ if do_classifier_free_guidance:
622
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
623
+ else:
624
+ for single_image_embeds in ip_adapter_image_embeds:
625
+ if do_classifier_free_guidance:
626
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
627
+ negative_image_embeds.append(single_negative_image_embeds)
628
+ image_embeds.append(single_image_embeds)
629
+
630
+ ip_adapter_image_embeds = []
631
+ for i, single_image_embeds in enumerate(image_embeds):
632
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
633
+ if do_classifier_free_guidance:
634
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
635
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
636
+
637
+ single_image_embeds = single_image_embeds.to(device=device)
638
+ ip_adapter_image_embeds.append(single_image_embeds)
639
+
640
+ return ip_adapter_image_embeds
641
+
642
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
643
+ def prepare_extra_step_kwargs(self, generator, eta):
644
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
645
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
646
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
647
+ # and should be between [0, 1]
648
+
649
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
650
+ extra_step_kwargs = {}
651
+ if accepts_eta:
652
+ extra_step_kwargs["eta"] = eta
653
+
654
+ # check if the scheduler accepts generator
655
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
656
+ if accepts_generator:
657
+ extra_step_kwargs["generator"] = generator
658
+ return extra_step_kwargs
659
+
660
+ def check_inputs(
661
+ self,
662
+ prompt,
663
+ prompt_2,
664
+ strength,
665
+ num_inference_steps,
666
+ callback_steps,
667
+ negative_prompt=None,
668
+ negative_prompt_2=None,
669
+ prompt_embeds=None,
670
+ negative_prompt_embeds=None,
671
+ ip_adapter_image=None,
672
+ ip_adapter_image_embeds=None,
673
+ callback_on_step_end_tensor_inputs=None,
674
+ ):
675
+ if strength < 0 or strength > 1:
676
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
677
+ if num_inference_steps is None:
678
+ raise ValueError("`num_inference_steps` cannot be None.")
679
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
680
+ raise ValueError(
681
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
682
+ f" {type(num_inference_steps)}."
683
+ )
684
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
685
+ raise ValueError(
686
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
687
+ f" {type(callback_steps)}."
688
+ )
689
+
690
+ if callback_on_step_end_tensor_inputs is not None and not all(
691
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
692
+ ):
693
+ raise ValueError(
694
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
695
+ )
696
+
697
+ if prompt is not None and prompt_embeds is not None:
698
+ raise ValueError(
699
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
700
+ " only forward one of the two."
701
+ )
702
+ elif prompt_2 is not None and prompt_embeds is not None:
703
+ raise ValueError(
704
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
705
+ " only forward one of the two."
706
+ )
707
+ elif prompt is None and prompt_embeds is None:
708
+ raise ValueError(
709
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
710
+ )
711
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
712
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
713
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
714
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
715
+
716
+ if negative_prompt is not None and negative_prompt_embeds is not None:
717
+ raise ValueError(
718
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
719
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
720
+ )
721
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
722
+ raise ValueError(
723
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
724
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
725
+ )
726
+
727
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
728
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
729
+ raise ValueError(
730
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
731
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
732
+ f" {negative_prompt_embeds.shape}."
733
+ )
734
+
735
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
736
+ raise ValueError(
737
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
738
+ )
739
+
740
+ if ip_adapter_image_embeds is not None:
741
+ if not isinstance(ip_adapter_image_embeds, list):
742
+ raise ValueError(
743
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
744
+ )
745
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
746
+ raise ValueError(
747
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
748
+ )
749
+
750
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
751
+ # get the original timestep using init_timestep
752
+ if denoising_start is None:
753
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
754
+ t_start = max(num_inference_steps - init_timestep, 0)
755
+ else:
756
+ t_start = 0
757
+
758
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
759
+
760
+ # Strength is irrelevant if we directly request a timestep to start at;
761
+ # that is, strength is determined by the denoising_start instead.
762
+ if denoising_start is not None:
763
+ discrete_timestep_cutoff = int(
764
+ round(
765
+ self.scheduler.config.num_train_timesteps
766
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
767
+ )
768
+ )
769
+
770
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
771
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
772
+ # if the scheduler is a 2nd order scheduler we might have to do +1
773
+ # because `num_inference_steps` might be even given that every timestep
774
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
775
+ # mean that we cut the timesteps in the middle of the denoising step
776
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
777
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
778
+ num_inference_steps = num_inference_steps + 1
779
+
780
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
781
+ timesteps = timesteps[-num_inference_steps:]
782
+ return timesteps, num_inference_steps
783
+
784
+ return timesteps, num_inference_steps - t_start
785
+
786
+ def prepare_latents(
787
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
788
+ ):
789
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
790
+ raise ValueError(
791
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
792
+ )
793
+
794
+ latents_mean = latents_std = None
795
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
796
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
797
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
798
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
799
+
800
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
801
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
802
+ self.text_encoder_2.to("cpu")
803
+ torch.cuda.empty_cache()
804
+
805
+ image = image.to(device=device, dtype=dtype)
806
+
807
+ batch_size = batch_size * num_images_per_prompt
808
+
809
+ if image.shape[1] == 4:
810
+ init_latents = image
811
+
812
+ else:
813
+ # make sure the VAE is in float32 mode, as it overflows in float16
814
+ if self.vae.config.force_upcast:
815
+ image = image.float()
816
+ self.vae.to(dtype=torch.float32)
817
+
818
+ if isinstance(generator, list) and len(generator) != batch_size:
819
+ raise ValueError(
820
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
821
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
822
+ )
823
+
824
+ elif isinstance(generator, list):
825
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
826
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
827
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
828
+ raise ValueError(
829
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
830
+ )
831
+
832
+ init_latents = [
833
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
834
+ for i in range(batch_size)
835
+ ]
836
+ init_latents = torch.cat(init_latents, dim=0)
837
+ else:
838
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
839
+
840
+ if self.vae.config.force_upcast:
841
+ self.vae.to(dtype)
842
+
843
+ init_latents = init_latents.to(dtype)
844
+ if latents_mean is not None and latents_std is not None:
845
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
846
+ latents_std = latents_std.to(device=device, dtype=dtype)
847
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
848
+ else:
849
+ init_latents = self.vae.config.scaling_factor * init_latents
850
+
851
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
852
+ # expand init_latents for batch_size
853
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
854
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
855
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
856
+ raise ValueError(
857
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
858
+ )
859
+ else:
860
+ init_latents = torch.cat([init_latents], dim=0)
861
+
862
+ if add_noise:
863
+ shape = init_latents.shape
864
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
865
+ # get latents
866
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
867
+
868
+ latents = init_latents
869
+
870
+ return latents
871
+
872
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
873
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
874
+ dtype = next(self.image_encoder.parameters()).dtype
875
+
876
+ if not isinstance(image, torch.Tensor):
877
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
878
+
879
+ image = image.to(device=device, dtype=dtype)
880
+ if output_hidden_states:
881
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
882
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
883
+ uncond_image_enc_hidden_states = self.image_encoder(
884
+ torch.zeros_like(image), output_hidden_states=True
885
+ ).hidden_states[-2]
886
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
887
+ num_images_per_prompt, dim=0
888
+ )
889
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
890
+ else:
891
+ image_embeds = self.image_encoder(image).image_embeds
892
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
893
+ uncond_image_embeds = torch.zeros_like(image_embeds)
894
+
895
+ return image_embeds, uncond_image_embeds
896
+
897
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
898
+ def prepare_ip_adapter_image_embeds(
899
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
900
+ ):
901
+ image_embeds = []
902
+ if do_classifier_free_guidance:
903
+ negative_image_embeds = []
904
+ if ip_adapter_image_embeds is None:
905
+ if not isinstance(ip_adapter_image, list):
906
+ ip_adapter_image = [ip_adapter_image]
907
+
908
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
909
+ raise ValueError(
910
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
911
+ )
912
+
913
+ for single_ip_adapter_image, image_proj_layer in zip(
914
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
915
+ ):
916
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
917
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
918
+ single_ip_adapter_image, device, 1, output_hidden_state
919
+ )
920
+
921
+ image_embeds.append(single_image_embeds[None, :])
922
+ if do_classifier_free_guidance:
923
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
924
+ else:
925
+ for single_image_embeds in ip_adapter_image_embeds:
926
+ if do_classifier_free_guidance:
927
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
928
+ negative_image_embeds.append(single_negative_image_embeds)
929
+ image_embeds.append(single_image_embeds)
930
+
931
+ ip_adapter_image_embeds = []
932
+ for i, single_image_embeds in enumerate(image_embeds):
933
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
934
+ if do_classifier_free_guidance:
935
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
936
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
937
+
938
+ single_image_embeds = single_image_embeds.to(device=device)
939
+ ip_adapter_image_embeds.append(single_image_embeds)
940
+
941
+ return ip_adapter_image_embeds
942
+
943
+ def _get_add_time_ids(
944
+ self,
945
+ original_size,
946
+ crops_coords_top_left,
947
+ target_size,
948
+ aesthetic_score,
949
+ negative_aesthetic_score,
950
+ negative_original_size,
951
+ negative_crops_coords_top_left,
952
+ negative_target_size,
953
+ dtype,
954
+ text_encoder_projection_dim=None,
955
+ ):
956
+ if self.config.requires_aesthetics_score:
957
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
958
+ add_neg_time_ids = list(
959
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
960
+ )
961
+ else:
962
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
963
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
964
+
965
+ passed_add_embed_dim = (
966
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
967
+ )
968
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
969
+
970
+ if (
971
+ expected_add_embed_dim > passed_add_embed_dim
972
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
973
+ ):
974
+ raise ValueError(
975
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
976
+ )
977
+ elif (
978
+ expected_add_embed_dim < passed_add_embed_dim
979
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
980
+ ):
981
+ raise ValueError(
982
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
983
+ )
984
+ elif expected_add_embed_dim != passed_add_embed_dim:
985
+ raise ValueError(
986
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
987
+ )
988
+
989
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
990
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
991
+
992
+ return add_time_ids, add_neg_time_ids
993
+
994
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
995
+ def upcast_vae(self):
996
+ dtype = self.vae.dtype
997
+ self.vae.to(dtype=torch.float32)
998
+ use_torch_2_0_or_xformers = isinstance(
999
+ self.vae.decoder.mid_block.attentions[0].processor,
1000
+ (
1001
+ AttnProcessor2_0,
1002
+ XFormersAttnProcessor,
1003
+ ),
1004
+ )
1005
+ # if xformers or torch_2_0 is used attention block does not need
1006
+ # to be in float32 which can save lots of memory
1007
+ if use_torch_2_0_or_xformers:
1008
+ self.vae.post_quant_conv.to(dtype)
1009
+ self.vae.decoder.conv_in.to(dtype)
1010
+ self.vae.decoder.mid_block.to(dtype)
1011
+
1012
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
1013
+ def _default_height_width(self, height, width, image):
1014
+ # NOTE: It is possible that a list of images have different
1015
+ # dimensions for each image, so just checking the first image
1016
+ # is not _exactly_ correct, but it is simple.
1017
+ while isinstance(image, list):
1018
+ image = image[0]
1019
+
1020
+ if height is None:
1021
+ if isinstance(image, PIL.Image.Image):
1022
+ height = image.height
1023
+ elif isinstance(image, torch.Tensor):
1024
+ height = image.shape[-2]
1025
+
1026
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1027
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
1028
+
1029
+ if width is None:
1030
+ if isinstance(image, PIL.Image.Image):
1031
+ width = image.width
1032
+ elif isinstance(image, torch.Tensor):
1033
+ width = image.shape[-1]
1034
+
1035
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1036
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
1037
+
1038
+ return height, width
1039
+
1040
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1041
+ def get_guidance_scale_embedding(
1042
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1043
+ ) -> torch.Tensor:
1044
+ """
1045
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1046
+
1047
+ Args:
1048
+ w (`torch.Tensor`):
1049
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1050
+ embedding_dim (`int`, *optional*, defaults to 512):
1051
+ Dimension of the embeddings to generate.
1052
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1053
+ Data type of the generated embeddings.
1054
+
1055
+ Returns:
1056
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1057
+ """
1058
+ assert len(w.shape) == 1
1059
+ w = w * 1000.0
1060
+
1061
+ half_dim = embedding_dim // 2
1062
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1063
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1064
+ emb = w.to(dtype)[:, None] * emb[None, :]
1065
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1066
+ if embedding_dim % 2 == 1: # zero pad
1067
+ emb = torch.nn.functional.pad(emb, (0, 1))
1068
+ assert emb.shape == (w.shape[0], embedding_dim)
1069
+ return emb
1070
+
1071
+ @property
1072
+ def guidance_scale(self):
1073
+ return self._guidance_scale
1074
+
1075
+ @property
1076
+ def guidance_rescale(self):
1077
+ return self._guidance_rescale
1078
+
1079
+ @property
1080
+ def clip_skip(self):
1081
+ return self._clip_skip
1082
+
1083
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1084
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1085
+ # corresponds to doing no classifier free guidance.
1086
+ @property
1087
+ def do_classifier_free_guidance(self):
1088
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1089
+
1090
+ @property
1091
+ def cross_attention_kwargs(self):
1092
+ return self._cross_attention_kwargs
1093
+
1094
+ @property
1095
+ def denoising_end(self):
1096
+ return self._denoising_end
1097
+
1098
+ @property
1099
+ def denoising_start(self):
1100
+ return self._denoising_start
1101
+
1102
+ @property
1103
+ def num_timesteps(self):
1104
+ return self._num_timesteps
1105
+
1106
+ @property
1107
+ def interrupt(self):
1108
+ return self._interrupt
1109
+
1110
+ @torch.no_grad()
1111
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1112
+ def __call__(
1113
+ self,
1114
+ prompt: Union[str, List[str]] = None,
1115
+ prompt_2: Optional[Union[str, List[str]]] = None,
1116
+ image: PipelineImageInput = None,
1117
+ height: Optional[int] = None,
1118
+ width: Optional[int] = None,
1119
+ adapter_image: PipelineImageInput = None,
1120
+ strength: float = 0.3,
1121
+ num_inference_steps: int = 50,
1122
+ timesteps: List[int] = None,
1123
+ sigmas: List[float] = None,
1124
+ denoising_start: Optional[float] = None,
1125
+ denoising_end: Optional[float] = None,
1126
+ guidance_scale: float = 5.0,
1127
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1128
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1129
+ num_images_per_prompt: Optional[int] = 1,
1130
+ eta: float = 0.0,
1131
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1132
+ latents: Optional[torch.Tensor] = None,
1133
+ prompt_embeds: Optional[torch.Tensor] = None,
1134
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1135
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1136
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1137
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1138
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1139
+ output_type: Optional[str] = "pil",
1140
+ return_dict: bool = True,
1141
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1142
+ guidance_rescale: float = 0.0,
1143
+ original_size: Tuple[int, int] = None,
1144
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1145
+ target_size: Tuple[int, int] = None,
1146
+ negative_original_size: Optional[Tuple[int, int]] = None,
1147
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1148
+ negative_target_size: Optional[Tuple[int, int]] = None,
1149
+ aesthetic_score: float = 6.0,
1150
+ negative_aesthetic_score: float = 2.5,
1151
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
1152
+ adapter_conditioning_factor: float = 1.0,
1153
+ clip_skip: Optional[int] = None,
1154
+ callback_on_step_end: Optional[
1155
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1156
+ ] = None,
1157
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1158
+ **kwargs,
1159
+ ):
1160
+ r"""
1161
+ Function invoked when calling the pipeline for generation.
1162
+
1163
+ Args:
1164
+ prompt (`str` or `List[str]`, *optional*):
1165
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1166
+ instead.
1167
+ prompt_2 (`str` or `List[str]`, *optional*):
1168
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1169
+ used in both text-encoders
1170
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
1171
+ The image(s) to modify with the pipeline.
1172
+ strength (`float`, *optional*, defaults to 0.3):
1173
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
1174
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
1175
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
1176
+ be maximum and the denoising process will run for the full number of iterations specified in
1177
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
1178
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
1179
+ num_inference_steps (`int`, *optional*, defaults to 50):
1180
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1181
+ expense of slower inference.
1182
+ timesteps (`List[int]`, *optional*):
1183
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1184
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1185
+ passed will be used. Must be in descending order.
1186
+ sigmas (`List[float]`, *optional*):
1187
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1188
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1189
+ will be used.
1190
+ denoising_start (`float`, *optional*):
1191
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1192
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1193
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1194
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1195
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
1196
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1197
+ denoising_end (`float`, *optional*):
1198
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1199
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1200
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1201
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1202
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1203
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refine Image
1204
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1205
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1206
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1207
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1208
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1209
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1210
+ usually at the expense of lower image quality.
1211
+ negative_prompt (`str` or `List[str]`, *optional*):
1212
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1213
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1214
+ less than `1`).
1215
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1216
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1217
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1218
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1219
+ The number of images to generate per prompt.
1220
+ eta (`float`, *optional*, defaults to 0.0):
1221
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1222
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1223
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1224
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1225
+ to make generation deterministic.
1226
+ latents (`torch.Tensor`, *optional*):
1227
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1228
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1229
+ tensor will ge generated by sampling using the supplied random `generator`.
1230
+ prompt_embeds (`torch.Tensor`, *optional*):
1231
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1232
+ provided, text embeddings will be generated from `prompt` input argument.
1233
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1234
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1235
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1236
+ argument.
1237
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1238
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1239
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1240
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1241
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1242
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1243
+ input argument.
1244
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1245
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1246
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1247
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1248
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1249
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1250
+ output_type (`str`, *optional*, defaults to `"pil"`):
1251
+ The output format of the generate image. Choose between
1252
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1253
+ return_dict (`bool`, *optional*, defaults to `True`):
1254
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1255
+ plain tuple.
1256
+ cross_attention_kwargs (`dict`, *optional*):
1257
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1258
+ `self.processor` in
1259
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1260
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1261
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1262
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1263
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1264
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1265
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1266
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1267
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1268
+ explained in section 2.2 of
1269
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1270
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1271
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1272
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1273
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1274
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1275
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1276
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1277
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1278
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1279
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1280
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1281
+ micro-conditioning as explained in section 2.2 of
1282
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1283
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1284
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1285
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1286
+ micro-conditioning as explained in section 2.2 of
1287
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1288
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1289
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1290
+ To negatively condition the generation process based on a target image resolution. It should be as same
1291
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1292
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1293
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1294
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1295
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1296
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1297
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1298
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1299
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1300
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1301
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1302
+ clip_skip (`int`, *optional*):
1303
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1304
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1305
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1306
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1307
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1308
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1309
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1310
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1311
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1312
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1313
+ `._callback_tensor_inputs` attribute of your pipeline class.
1314
+
1315
+ Examples:
1316
+
1317
+ Returns:
1318
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1319
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1320
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1321
+ """
1322
+ height, width = self._default_height_width(height, width, adapter_image)
1323
+ device = self._execution_device
1324
+
1325
+ if isinstance(self.adapter, MultiAdapter):
1326
+ adapter_input = []
1327
+
1328
+ for one_image in adapter_image:
1329
+ one_image = _preprocess_adapter_image(one_image, height, width)
1330
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
1331
+ adapter_input.append(one_image)
1332
+ else:
1333
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1334
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
1335
+
1336
+ callback = kwargs.pop("callback", None)
1337
+ callback_steps = kwargs.pop("callback_steps", None)
1338
+
1339
+ if callback is not None:
1340
+ deprecate(
1341
+ "callback",
1342
+ "1.0.0",
1343
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1344
+ )
1345
+ if callback_steps is not None:
1346
+ deprecate(
1347
+ "callback_steps",
1348
+ "1.0.0",
1349
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1350
+ )
1351
+
1352
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1353
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1354
+
1355
+ # 1. Check inputs. Raise error if not correct
1356
+ self.check_inputs(
1357
+ prompt,
1358
+ prompt_2,
1359
+ strength,
1360
+ num_inference_steps,
1361
+ callback_steps,
1362
+ negative_prompt,
1363
+ negative_prompt_2,
1364
+ prompt_embeds,
1365
+ negative_prompt_embeds,
1366
+ ip_adapter_image,
1367
+ ip_adapter_image_embeds,
1368
+ callback_on_step_end_tensor_inputs,
1369
+ )
1370
+
1371
+ self._guidance_scale = guidance_scale
1372
+ self._guidance_rescale = guidance_rescale
1373
+ self._clip_skip = clip_skip
1374
+ self._cross_attention_kwargs = cross_attention_kwargs
1375
+ self._denoising_end = denoising_end
1376
+ self._denoising_start = denoising_start
1377
+ self._interrupt = False
1378
+
1379
+ # 2. Define call parameters
1380
+ if prompt is not None and isinstance(prompt, str):
1381
+ batch_size = 1
1382
+ elif prompt is not None and isinstance(prompt, list):
1383
+ batch_size = len(prompt)
1384
+ else:
1385
+ batch_size = prompt_embeds.shape[0]
1386
+
1387
+ device = self._execution_device
1388
+
1389
+ # 3. Encode input prompt
1390
+ text_encoder_lora_scale = (
1391
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1392
+ )
1393
+ (
1394
+ prompt_embeds,
1395
+ negative_prompt_embeds,
1396
+ pooled_prompt_embeds,
1397
+ negative_pooled_prompt_embeds,
1398
+ ) = self.encode_prompt(
1399
+ prompt=prompt,
1400
+ prompt_2=prompt_2,
1401
+ device=device,
1402
+ num_images_per_prompt=num_images_per_prompt,
1403
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1404
+ negative_prompt=negative_prompt,
1405
+ negative_prompt_2=negative_prompt_2,
1406
+ prompt_embeds=prompt_embeds,
1407
+ negative_prompt_embeds=negative_prompt_embeds,
1408
+ pooled_prompt_embeds=pooled_prompt_embeds,
1409
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1410
+ lora_scale=text_encoder_lora_scale,
1411
+ clip_skip=self.clip_skip,
1412
+ )
1413
+
1414
+ # 4. Preprocess image
1415
+ image = self.image_processor.preprocess(image)
1416
+
1417
+ # 5. Prepare timesteps
1418
+ def denoising_value_valid(dnv):
1419
+ return isinstance(dnv, float) and 0 < dnv < 1
1420
+
1421
+ timesteps, num_inference_steps = retrieve_timesteps(
1422
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1423
+ )
1424
+ timesteps, num_inference_steps = self.get_timesteps(
1425
+ num_inference_steps,
1426
+ strength,
1427
+ device,
1428
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1429
+ )
1430
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1431
+
1432
+ add_noise = True if self.denoising_start is None else False
1433
+
1434
+ # 6. Prepare latent variables
1435
+ if latents is None:
1436
+ latents = self.prepare_latents(
1437
+ image,
1438
+ latent_timestep,
1439
+ batch_size,
1440
+ num_images_per_prompt,
1441
+ prompt_embeds.dtype,
1442
+ device,
1443
+ generator,
1444
+ add_noise,
1445
+ )
1446
+ # 7. Prepare extra step kwargs.
1447
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1448
+
1449
+ height, width = latents.shape[-2:]
1450
+ height = height * self.vae_scale_factor
1451
+ width = width * self.vae_scale_factor
1452
+
1453
+ original_size = original_size or (height, width)
1454
+ target_size = target_size or (height, width)
1455
+
1456
+ # 8. Prepare added time ids & embeddings
1457
+ # adapter_input = adapter_input.type(latents.dtype)
1458
+ if isinstance(self.adapter, MultiAdapter):
1459
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
1460
+ for k, v in enumerate(adapter_state):
1461
+ adapter_state[k] = v
1462
+ else:
1463
+ adapter_state = self.adapter(adapter_input)
1464
+ for k, v in enumerate(adapter_state):
1465
+ adapter_state[k] = v * adapter_conditioning_scale
1466
+ if num_images_per_prompt > 1:
1467
+ for k, v in enumerate(adapter_state):
1468
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1469
+ if self.do_classifier_free_guidance:
1470
+ for k, v in enumerate(adapter_state):
1471
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1472
+
1473
+ if negative_original_size is None:
1474
+ negative_original_size = original_size
1475
+ if negative_target_size is None:
1476
+ negative_target_size = target_size
1477
+
1478
+ add_text_embeds = pooled_prompt_embeds
1479
+ if self.text_encoder_2 is None:
1480
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1481
+ else:
1482
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1483
+
1484
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1485
+ original_size,
1486
+ crops_coords_top_left,
1487
+ target_size,
1488
+ aesthetic_score,
1489
+ negative_aesthetic_score,
1490
+ negative_original_size,
1491
+ negative_crops_coords_top_left,
1492
+ negative_target_size,
1493
+ dtype=prompt_embeds.dtype,
1494
+ text_encoder_projection_dim=text_encoder_projection_dim,
1495
+ )
1496
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1497
+
1498
+ if self.do_classifier_free_guidance:
1499
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1500
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1501
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1502
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1503
+
1504
+ prompt_embeds = prompt_embeds.to(device)
1505
+ add_text_embeds = add_text_embeds.to(device)
1506
+ add_time_ids = add_time_ids.to(device)
1507
+
1508
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1509
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1510
+ ip_adapter_image,
1511
+ ip_adapter_image_embeds,
1512
+ device,
1513
+ batch_size * num_images_per_prompt,
1514
+ self.do_classifier_free_guidance,
1515
+ )
1516
+
1517
+ # 9. Denoising loop
1518
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1519
+
1520
+ # 9.1 Apply denoising_end
1521
+ if (
1522
+ self.denoising_end is not None
1523
+ and self.denoising_start is not None
1524
+ and denoising_value_valid(self.denoising_end)
1525
+ and denoising_value_valid(self.denoising_start)
1526
+ and self.denoising_start >= self.denoising_end
1527
+ ):
1528
+ raise ValueError(
1529
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1530
+ + f" {self.denoising_end} when using type float."
1531
+ )
1532
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1533
+ discrete_timestep_cutoff = int(
1534
+ round(
1535
+ self.scheduler.config.num_train_timesteps
1536
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1537
+ )
1538
+ )
1539
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1540
+ timesteps = timesteps[:num_inference_steps]
1541
+
1542
+ # 9.2 Optionally get Guidance Scale Embedding
1543
+ timestep_cond = None
1544
+ if self.unet.config.time_cond_proj_dim is not None:
1545
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1546
+ timestep_cond = self.get_guidance_scale_embedding(
1547
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1548
+ ).to(device=device, dtype=latents.dtype)
1549
+
1550
+ self._num_timesteps = len(timesteps)
1551
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1552
+ for i, t in enumerate(timesteps):
1553
+ if self.interrupt:
1554
+ continue
1555
+
1556
+ # expand the latents if we are doing classifier free guidance
1557
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1558
+
1559
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1560
+
1561
+ # predict the noise residual
1562
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1563
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1564
+ added_cond_kwargs["image_embeds"] = image_embeds
1565
+
1566
+ if i < int(num_inference_steps * adapter_conditioning_factor):
1567
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
1568
+ else:
1569
+ down_intrablock_additional_residuals = None
1570
+
1571
+ noise_pred = self.unet(
1572
+ latent_model_input,
1573
+ t,
1574
+ encoder_hidden_states=prompt_embeds,
1575
+ timestep_cond=timestep_cond,
1576
+ cross_attention_kwargs=self.cross_attention_kwargs,
1577
+ added_cond_kwargs=added_cond_kwargs,
1578
+ return_dict=False,
1579
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
1580
+ )[0]
1581
+
1582
+ # perform guidance
1583
+ if self.do_classifier_free_guidance:
1584
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1585
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1586
+
1587
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1588
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1589
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1590
+
1591
+ # compute the previous noisy sample x_t -> x_t-1
1592
+ latents_dtype = latents.dtype
1593
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1594
+ if latents.dtype != latents_dtype:
1595
+ if torch.backends.mps.is_available():
1596
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1597
+ latents = latents.to(latents_dtype)
1598
+
1599
+ if callback_on_step_end is not None:
1600
+ callback_kwargs = {}
1601
+ for k in callback_on_step_end_tensor_inputs:
1602
+ callback_kwargs[k] = locals()[k]
1603
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1604
+
1605
+ latents = callback_outputs.pop("latents", latents)
1606
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1607
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1608
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1609
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1610
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1611
+ )
1612
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1613
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1614
+
1615
+ # call the callback, if provided
1616
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1617
+ progress_bar.update()
1618
+ if callback is not None and i % callback_steps == 0:
1619
+ step_idx = i // getattr(self.scheduler, "order", 1)
1620
+ callback(step_idx, t, latents)
1621
+
1622
+ if XLA_AVAILABLE:
1623
+ xm.mark_step()
1624
+
1625
+ if not output_type == "latent":
1626
+ # make sure the VAE is in float32 mode, as it overflows in float16
1627
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1628
+
1629
+ if needs_upcasting:
1630
+ self.upcast_vae()
1631
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1632
+ elif latents.dtype != self.vae.dtype:
1633
+ if torch.backends.mps.is_available():
1634
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1635
+ self.vae = self.vae.to(latents.dtype)
1636
+
1637
+ # unscale/denormalize the latents
1638
+ # denormalize with the mean and std if available and not None
1639
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1640
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1641
+ if has_latents_mean and has_latents_std:
1642
+ latents_mean = (
1643
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1644
+ )
1645
+ latents_std = (
1646
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1647
+ )
1648
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1649
+ else:
1650
+ latents = latents / self.vae.config.scaling_factor
1651
+
1652
+ image = self.vae.decode(latents, return_dict=False)[0]
1653
+
1654
+ # cast back to fp16 if needed
1655
+ if needs_upcasting:
1656
+ self.vae.to(dtype=torch.float16)
1657
+ else:
1658
+ image = latents
1659
+
1660
+ # apply watermark if available
1661
+ if self.watermark is not None:
1662
+ image = self.watermark.apply_watermark(image)
1663
+
1664
+ image = self.image_processor.postprocess(image, output_type=output_type)
1665
+
1666
+ # Offload all models
1667
+ self.maybe_free_model_hooks()
1668
+
1669
+ if not return_dict:
1670
+ return (image,)
1671
+
1672
+ return StableDiffusionXLPipelineOutput(images=image)
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ml-collections
2
+ gradio
3
+ torch
4
+ torchvision
5
+ diffusers
6
+ transformers
7
+ accelerate
8
+ mediapipe
9
+ spaces
10
+ sentencepiece
11
+ compel
12
+ gfpgan
13
+ git+https://github.com/XPixelGroup/BasicSR@master
14
+ facexlib
15
+ realesrgan
16
+ controlnet_aux
17
+ peft
run_configs/noise_shift_3_steps.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ breakdown: "x_t_hat_c"
2
+ cross_r: 0.9
3
+ eta_reconstruct: 1
4
+ eta_retrieve: 1
5
+ max_norm_zs: [-1, -1, 15.5]
6
+ model: "stabilityai/sdxl-turbo"
7
+ noise_shift_delta: 1
8
+ noise_timesteps: [599, 299, 0]
9
+ timesteps: [799, 499, 199]
10
+ num_steps_inversion: 5
11
+ step_start: 1
12
+ real_cfg_scale: 0
13
+ real_cfg_scale_save: 0
14
+ scheduler_type: "ddpm"
15
+ seed: 2
16
+ self_r: 0.5
17
+ ws1: 1.5
18
+ ws2: 1
19
+ clean_step_timestep: 0
run_configs/noise_shift_guidance_1_5.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ breakdown: "x_t_hat_c"
2
+ cross_r: 0.9
3
+ eta: 1
4
+ max_norm_zs: [-1, -1, -1, 15.5]
5
+ model: ""
6
+ noise_shift_delta: 1
7
+ noise_timesteps: null
8
+ num_steps_inversion: 20
9
+ step_start: 5
10
+ real_cfg_scale: 0
11
+ real_cfg_scale_save: 0
12
+ scheduler_type: "ddpm"
13
+ seed: 2
14
+ self_r: 0.5
15
+ timesteps: null
16
+ ws1: 1.5
17
+ ws2: 1
18
+ clean_step_timestep: 0
segment_utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import mediapipe as mp
3
+ import uuid
4
+
5
+ from PIL import Image
6
+ from mediapipe.tasks import python
7
+ from mediapipe.tasks.python import vision
8
+ from scipy.ndimage import binary_dilation
9
+ from croper import Croper
10
+
11
+ segment_model = "checkpoints/selfie_multiclass_256x256.tflite"
12
+ base_options = python.BaseOptions(model_asset_path=segment_model)
13
+ options = vision.ImageSegmenterOptions(base_options=base_options,output_category_mask=True)
14
+ segmenter = vision.ImageSegmenter.create_from_options(options)
15
+
16
+ def restore_result(croper, category, generated_image):
17
+ square_length = croper.square_length
18
+ generated_image = generated_image.resize((square_length, square_length))
19
+
20
+ cropped_generated_image = generated_image.crop((croper.square_start_x, croper.square_start_y, croper.square_end_x, croper.square_end_y))
21
+ cropped_square_mask_image = get_restore_mask_image(croper, category, cropped_generated_image)
22
+
23
+ restored_image = croper.input_image.copy()
24
+ restored_image.paste(cropped_generated_image, (croper.origin_start_x, croper.origin_start_y), cropped_square_mask_image)
25
+
26
+ extension = 'png'
27
+ if restored_image.mode == 'RGBA':
28
+ extension = 'png'
29
+ else:
30
+ extension = 'jpg'
31
+
32
+ path = f"output/{uuid.uuid4()}.{extension}"
33
+ restored_image.save(path)
34
+
35
+ return restored_image, path
36
+
37
+ def segment_image(input_image, category, input_size, mask_expansion, mask_dilation):
38
+ mask_size = int(input_size)
39
+ mask_expansion = int(mask_expansion)
40
+
41
+ image = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.asarray(input_image))
42
+ segmentation_result = segmenter.segment(image)
43
+ category_mask = segmentation_result.category_mask
44
+ category_mask_np = category_mask.numpy_view()
45
+
46
+ if category == "hair":
47
+ target_mask = get_hair_mask(category_mask_np, mask_dilation)
48
+ elif category == "clothes":
49
+ target_mask = get_clothes_mask(category_mask_np, mask_dilation)
50
+ elif category == "face":
51
+ target_mask = get_face_mask(category_mask_np, mask_dilation)
52
+ else:
53
+ target_mask = get_face_mask(category_mask_np, mask_dilation)
54
+
55
+ croper = Croper(input_image, target_mask, mask_size, mask_expansion)
56
+ croper.corp_mask_image()
57
+ origin_area_image = croper.resized_square_image
58
+
59
+ return origin_area_image, croper
60
+
61
+ def get_face_mask(category_mask_np, dilation=1):
62
+ face_skin_mask = category_mask_np == 3
63
+ if dilation > 0:
64
+ face_skin_mask = binary_dilation(face_skin_mask, iterations=dilation)
65
+
66
+ return face_skin_mask
67
+
68
+ def get_clothes_mask(category_mask_np, dilation=1):
69
+ body_skin_mask = category_mask_np == 2
70
+ clothes_mask = category_mask_np == 4
71
+ combined_mask = np.logical_or(body_skin_mask, clothes_mask)
72
+ combined_mask = binary_dilation(combined_mask, iterations=4)
73
+ if dilation > 0:
74
+ combined_mask = binary_dilation(combined_mask, iterations=dilation)
75
+ return combined_mask
76
+
77
+ def get_hair_mask(category_mask_np, dilation=1):
78
+ hair_mask = category_mask_np == 1
79
+ if dilation > 0:
80
+ hair_mask = binary_dilation(hair_mask, iterations=dilation)
81
+ return hair_mask
82
+
83
+ def get_restore_mask_image(croper, category, generated_image):
84
+ image = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.asarray(generated_image))
85
+ segmentation_result = segmenter.segment(image)
86
+ category_mask = segmentation_result.category_mask
87
+ category_mask_np = category_mask.numpy_view()
88
+
89
+ if category == "hair":
90
+ target_mask = get_hair_mask(category_mask_np, 0)
91
+ elif category == "clothes":
92
+ target_mask = get_clothes_mask(category_mask_np, 0)
93
+ elif category == "face":
94
+ target_mask = get_face_mask(category_mask_np, 0)
95
+
96
+ combined_mask = np.logical_or(target_mask, croper.corp_mask)
97
+ mask_image = Image.fromarray((combined_mask * 255).astype(np.uint8))
98
+ return mask_image