armikaeili commited on
Commit
79c5088
·
0 Parent(s):

code added

Browse files
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.jpg filter=lfs diff=lfs merge=lfs -text
37
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ViT-L-14.pt
2
+ *.png
3
+ *.jpg
4
+ *.jpeg
5
+ ./output/
6
+ ./output_old/
7
+ ./metrics/
8
+ ./dataset/
9
+ __pycache__/
10
+ ./met/*
11
+ *.csv
12
+ ./.idea/
13
+ ./.gradio/
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Cora
3
+ emoji: 🖼️
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 5.26.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ short_description: Demo for Cora. Our few-step image editing method
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+
4
+ from PIL import Image
5
+
6
+ import numpy as np
7
+ import torch.nn.functional as F
8
+
9
+ from utils.pipeline_utils import *
10
+ from utils import get_args
11
+
12
+ from main import run
13
+
14
+ pipeline = None
15
+
16
+
17
+ def get_pipeline():
18
+ global pipeline
19
+ if pipeline is None:
20
+ pipeline = load_pipeline(fp16=False, cache_dir=None)
21
+ return pipeline
22
+
23
+
24
+ def process_masks(masks):
25
+ # masks: list of file paths
26
+ processed_masks = []
27
+ mask_composit = torch.zeros((512, 512), dtype=torch.float32, device='cuda')
28
+ for mask_path in masks:
29
+ mask = Image.open(mask_path).convert("L").resize((512, 512))
30
+ mask = torch.tensor(np.array(mask), dtype=torch.float32, device='cuda')
31
+ mask[mask > 0] = 255.0
32
+ mask = mask / 255.0
33
+ processed_masks.append(mask)
34
+ mask_composit += mask
35
+ mask_composit = torch.clamp(mask_composit, 0, 1)
36
+ mask_composit = F.interpolate(mask_composit[None, None, :, :], size=(64, 64), mode="nearest")[0, 0]
37
+ if mask_composit.sum() == 0:
38
+ mask_composit = None
39
+
40
+ return mask_composit
41
+
42
+
43
+ @spaces.GPU
44
+ def main_pipeline(
45
+ input_image: str,
46
+ src_prompt: str,
47
+ tgt_prompt: str,
48
+ alpha: float,
49
+ beta: float,
50
+ w1: float,
51
+ seed: int,
52
+ dift_correction: bool = True,
53
+ ):
54
+ args = get_args()
55
+ pipeline = get_pipeline()
56
+
57
+ args.alpha = alpha
58
+ args.beta = beta
59
+ args.w1 = w1
60
+ args.seed = seed
61
+ args.structural_alignment = True
62
+ args.support_new_object = True
63
+ args.apply_dift_correction = dift_correction
64
+ torch.cuda.empty_cache()
65
+ res_image = run(input_image['background'], src_prompt, tgt_prompt, masks=process_masks(input_image['layers']),
66
+ pipeline=pipeline, args=args)[2]
67
+
68
+ return res_image
69
+
70
+
71
+ DESCRIPTION = """# Cora 🖼️🐱🦅
72
+ ## Fast & Controllable Image Editing
73
+
74
+ ### 🛠️ Quick start
75
+ 1. **Upload** or drag-and-drop the image you’d like to edit.
76
+ 2. **Source prompt** – describe what’s in the original image.
77
+ 3. **Target prompt** – describe the result you want.
78
+ 4. Adjust the parameters as needed.
79
+ 5. *(Optional)* Paint a mask to specify the area to edit.
80
+ 6. Click **Edit** and wait a few seconds for the output.
81
+
82
+ ### ⚙️ Parameter cheat-sheet
83
+
84
+ | Parameter | What it does | `0` (minimum) | `1` (maximum) |
85
+ |-----------|--------------|---------------|---------------|
86
+ | **alpha** | Appearance transfer control | preserve source appearance | target prompt affects appearance |
87
+ | **beta** | Structural change control | preserve original structure | full layout change |
88
+ | **w** | Prompt strength | subtle tweaks | strong changes |
89
+ | **Seed** | Fixes randomness for reproducibility | – | – |
90
+ | **Apply correspondence correction** | Uses correspondence-aware latent fix | – | – |
91
+
92
+ ### 📜 Tips
93
+ - To replicate **TurboEdit**, set **alpha = 1**, **beta = 1**, and turn **off** *Apply correspondence correction*.
94
+ - To test reconstruction quality of the inversion, use identical source & target prompts with **alpha = 1** and **beta = 1**.
95
+ #### 🙏 Acknowledgements
96
+ The demo template is largely adapted from **[TurboEdit on Hugging Face Spaces](https://huggingface.co/spaces/turboedit/turbo_edit)**.
97
+ """
98
+
99
+ with gr.Blocks(css="app/style.css") as demo:
100
+ gr.HTML(
101
+ """<a href="https://huggingface.co/spaces/armikaeili/cora?duplicate=true">
102
+ <img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space to run privately without waiting in queue"""
103
+ )
104
+ gr.Markdown(DESCRIPTION)
105
+
106
+ with gr.Row():
107
+ with gr.Column():
108
+ input_image = gr.ImageMask(
109
+ label="Input image", type="filepath", height=512, width=512, brush=gr.Brush(color_mode='defaults')
110
+ )
111
+ result = gr.Image(label="Result", type="pil", height=512, width=512)
112
+ with gr.Column():
113
+ src_prompt = gr.Text(
114
+ label="Source Prompt",
115
+ max_lines=1,
116
+ placeholder="Source Prompt",
117
+ )
118
+ tgt_prompt = gr.Text(
119
+ label="Target Prompt",
120
+ max_lines=1,
121
+ placeholder="Target Prompt",
122
+ )
123
+ with gr.Accordion("Advanced Options", open=False):
124
+ seed = gr.Slider(
125
+ label="seed", minimum=0, maximum=16 * 1024, value=200, step=1
126
+ )
127
+ w1 = gr.Slider(
128
+ label="w", minimum=1.0, maximum=3.0, value=1.9, step=0.05
129
+ )
130
+ alpha = gr.Slider(
131
+ label="alpha", minimum=0, maximum=1, value=0, step=0.01
132
+ )
133
+ beta = gr.Slider(
134
+ label="beta", minimum=0, maximum=1, value=0.04, step=0.01
135
+ )
136
+ with gr.Row():
137
+ dift_correction = gr.Checkbox(
138
+ label="Apply correspondence correction",
139
+ value=True)
140
+ run_button = gr.Button("Edit")
141
+
142
+ examples = [
143
+ [
144
+ "assets/white_cat.png", # input_image
145
+ "a cat", # src_prompt
146
+ "a cat wearing a suit", # tgt_prompt
147
+ 0.1, # alpha
148
+ 0.1, # beta
149
+ 1.9, # w1
150
+ 7, # seed
151
+ True # dift_correction
152
+ ],
153
+ [
154
+ "assets/bear.png", # input_image
155
+ "a sitting brown bear", # src_prompt
156
+ "a roaring blue bear", # tgt_prompt
157
+ 0.7, # alpha
158
+ 0.1, # beta
159
+ 1.9, # w1
160
+ 7, # seed
161
+ True # dift_correction
162
+ ],
163
+ [
164
+ "assets/cat.jpg", # input_image
165
+ "a cat", # src_prompt
166
+ "an eagle", # tgt_prompt
167
+ 0.7, # alpha
168
+ 0.3, # beta
169
+ 1.9, # w1
170
+ 7, # seed
171
+ True # dift_correction
172
+ ],
173
+ [
174
+ "assets/dog.png", # input_image
175
+ "a photo of a dog", # src_prompt
176
+ "a photo of a dog lying", # tgt_prompt
177
+ 0.0, # alpha
178
+ 1, # beta
179
+ 1.9, # w1
180
+ 7, # seed
181
+ True # dift_correction
182
+ ],
183
+
184
+ ]
185
+
186
+ inputs = [
187
+ input_image,
188
+ src_prompt,
189
+ tgt_prompt,
190
+ alpha,
191
+ beta,
192
+ w1,
193
+ seed,
194
+ dift_correction
195
+ ]
196
+ outputs = [result]
197
+ #
198
+ gr.Examples(
199
+ examples=examples,
200
+ inputs=inputs,
201
+ outputs=outputs,
202
+ fn=main_pipeline,
203
+ cache_examples=False,
204
+ )
205
+
206
+ run_button.click(fn=main_pipeline, inputs=inputs, outputs=outputs)
207
+ demo.queue(max_size=50).launch(share=False)
assets/bear.png ADDED

Git LFS Details

  • SHA256: 74680fb3775ac09beef3792b058658ed9b89aa9343ebfa31eb7639c55656875e
  • Pointer size: 131 Bytes
  • Size of remote file: 631 kB
assets/cat.jpg ADDED

Git LFS Details

  • SHA256: ad0f729589ee4730408e6eedbc97aec255d598f9f47f4c7d79164af1c059da23
  • Pointer size: 132 Bytes
  • Size of remote file: 1.49 MB
assets/dog.png ADDED

Git LFS Details

  • SHA256: 8b38bf084579cf746fa4aae35dca7ba591f7c0d93d596b30a808c72a96ff668e
  • Pointer size: 131 Bytes
  • Size of remote file: 868 kB
assets/white_cat.png ADDED

Git LFS Details

  • SHA256: a073e35c5cbdd94e69a30e71e8d7bc08b85b65177eed409d6b088b121c2f835e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.29 MB
main.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from PIL import Image
4
+ import jsonc as json
5
+
6
+ from model import (
7
+ DirectionalAttentionControl,
8
+ StableDiffusionXLImg2ImgPipeline,
9
+ register_attention_editor_diffusers,
10
+ )
11
+
12
+ from utils.pipeline_utils import *
13
+ from utils import get_args, extract_mask
14
+ from src import get_ddpm_inversion_scheduler
15
+ from visualization import save_results
16
+
17
+
18
+ def run(
19
+ image_path,
20
+ src_prompt,
21
+ tgt_prompt,
22
+ masks,
23
+ pipeline: StableDiffusionXLImg2ImgPipeline,
24
+ args,
25
+ ):
26
+ seed = args.seed
27
+ num_timesteps = args.timesteps
28
+ torch.manual_seed(seed)
29
+ generator = torch.Generator(device=SAMPLING_DEVICE).manual_seed(seed)
30
+
31
+ timesteps, config = set_pipeline(pipeline, num_timesteps, generator, args)
32
+
33
+ x_0_image = Image.open(image_path).convert("RGB").resize((512, 512), RESIZE_TYPE)
34
+ x_0 = encode_image(x_0_image, pipeline, generator)
35
+ x_ts = create_xts(
36
+ config.noise_shift_delta,
37
+ config.noise_timesteps,
38
+ generator,
39
+ pipeline.scheduler,
40
+ timesteps,
41
+ x_0,
42
+ )
43
+ x_ts = [xt.to(dtype=x_0.dtype) for xt in x_ts]
44
+ latents = [x_ts[0]]
45
+
46
+ if not isinstance(masks, torch.Tensor):
47
+ mask = extract_mask(masks, 512, 512)
48
+ else:
49
+ mask = masks
50
+
51
+ pipeline.scheduler = get_ddpm_inversion_scheduler(
52
+ pipeline.scheduler,
53
+ config,
54
+ timesteps,
55
+ latents,
56
+ x_ts,
57
+ w1=args.w1,
58
+ dift_timestep=args.dift_timestep,
59
+ movement_intensifier=args.movement_intensifier,
60
+ apply_dift_correction=args.apply_dift_correction,
61
+ mask=mask,
62
+ )
63
+
64
+
65
+ step, layer = 0, 44
66
+ editor = DirectionalAttentionControl(
67
+ step, layer, total_steps=11,
68
+ model_type="SDXL",
69
+ alpha=args.alpha, mode=args.mode, beta=1-args.beta,
70
+ structural_alignment=args.structural_alignment,
71
+ support_new_object=args.support_new_object
72
+ )
73
+ register_attention_editor_diffusers(pipeline, editor)
74
+
75
+ latent = latents[0].expand(3, -1, -1, -1)
76
+ prompt = [src_prompt, src_prompt, tgt_prompt]
77
+ pipeline.unet.latent_store.reset()
78
+ image = pipeline.__call__(image=latent, prompt=prompt).images
79
+ return [x_0_image, image[0], image[2]]
80
+
81
+
82
+ if __name__ == "__main__":
83
+ args = get_args()
84
+
85
+ img_paths_to_prompts = json.load(open(args.prompts_file, "r"))
86
+ eval_dataset_folder = args.eval_dataset_folder
87
+
88
+ img_paths = [
89
+ f"{eval_dataset_folder}/{img_name}" for img_name in img_paths_to_prompts.keys()
90
+ ]
91
+ pipeline = load_pipeline(args.fp16, args.cache_dir)
92
+
93
+ sim_scores_total = 0
94
+ os.makedirs(args.output_dir, exist_ok=True)
95
+
96
+ images_to_plot = []
97
+ output_dir = args.output_dir
98
+
99
+ for i, img_path in enumerate(img_paths):
100
+ args.img_path = img_path
101
+ img_name = img_path.split("/")[-1]
102
+ prompt = img_paths_to_prompts[img_name]["src_prompt"]
103
+ edit_prompts = img_paths_to_prompts[img_name]["tgt_prompt"]
104
+ args.alpha = img_paths_to_prompts[img_name].get("alpha", 0.7)
105
+ args.beta = img_paths_to_prompts[img_name].get("beta", 1)
106
+ masks = img_paths_to_prompts[img_name].get("masks", None)
107
+ args.mask = masks
108
+ args.source_prompt = prompt
109
+ args.target_prompt = edit_prompts[0]
110
+
111
+ res = run(
112
+ img_path,
113
+ prompt,
114
+ edit_prompts[0],
115
+ masks,
116
+ pipeline=pipeline,
117
+ args=args,
118
+ )
119
+
120
+ torch.cuda.empty_cache()
121
+ save_results(
122
+ args=args,
123
+ source_prompt=prompt,
124
+ target_prompt=edit_prompts[0],
125
+ images=res
126
+ )
model/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .directional_attentions import DirectionalAttentionControl
2
+ from .modules.register_attention import register_attention_editor_diffusers
3
+ from .pipeline_sdxl import StableDiffusionXLImg2ImgPipeline
4
+ from .modules.dift_utils import gen_nn_map
5
+ from .modules.freq_filters import freq_exp
model/directional_attentions.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import ctypes
4
+ import numpy as np
5
+
6
+ from einops import rearrange, repeat
7
+ from scipy.optimize import linear_sum_assignment
8
+ from typing import Optional, Union, Tuple, List, Callable, Dict
9
+
10
+ from model.modules.dift_utils import gen_nn_map
11
+
12
+
13
+ class AttentionBase:
14
+ def __init__(self):
15
+ self.cur_step = 0
16
+ self.num_att_layers = -1
17
+ self.cur_att_layer = 0
18
+
19
+ def after_step(self):
20
+ pass
21
+
22
+ def __call__(
23
+ self,
24
+ q: torch.Tensor,
25
+ k: torch.Tensor,
26
+ v: torch.Tensor,
27
+ sim: torch.Tensor,
28
+ attn: torch.Tensor,
29
+ is_cross: bool,
30
+ place_in_unet: str,
31
+ num_heads: int,
32
+ **kwargs
33
+ ) -> torch.Tensor:
34
+ out = self.forward(q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs)
35
+
36
+ self.cur_att_layer += 1
37
+ if self.cur_att_layer == self.num_att_layers:
38
+ self.cur_att_layer = 0
39
+ self.cur_step += 1
40
+ self.after_step()
41
+
42
+ return out
43
+
44
+ def forward(
45
+ self,
46
+ q: torch.Tensor,
47
+ k: torch.Tensor,
48
+ v: torch.Tensor,
49
+ sim: torch.Tensor,
50
+ attn: torch.Tensor,
51
+ is_cross: bool,
52
+ place_in_unet: str,
53
+ num_heads: int,
54
+ **kwargs
55
+ ) -> torch.Tensor:
56
+ out = torch.einsum('b i j, b j d -> b i d', attn, v)
57
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=num_heads)
58
+ return out
59
+
60
+ def reset(self):
61
+ self.cur_step = 0
62
+ self.cur_att_layer = 0
63
+
64
+ class DirectionalAttentionControl(AttentionBase):
65
+ MODEL_TYPE = {"SD": 16, "SDXL": 70}
66
+
67
+ def __init__(
68
+ self,
69
+ start_step: int = 4,
70
+ start_layer: int = 10,
71
+ layer_idx: Optional[List[int]] = None,
72
+ step_idx: Optional[List[int]] = None,
73
+ total_steps: int = 50,
74
+ model_type: str = "SD",
75
+ **kwargs
76
+ ):
77
+ super().__init__()
78
+ self.total_steps = total_steps
79
+ self.total_layers = self.MODEL_TYPE.get(model_type, 16)
80
+ self.start_step = start_step
81
+ self.start_layer = start_layer
82
+ self.layer_idx = layer_idx if layer_idx is not None else list(range(start_layer, self.total_layers))
83
+ self.step_idx = step_idx if step_idx is not None else list(range(start_step, total_steps))
84
+
85
+ self.w = 1.0
86
+ self.structural_alignment = kwargs.get("structural_alignment", False)
87
+ self.style_transfer_only = kwargs.get("style_transfer_only", False)
88
+ self.alpha = kwargs.get("alpha", 0.5)
89
+ self.beta = kwargs.get("beta", 0.5)
90
+ self.newness = kwargs.get("support_new_object", True)
91
+ self.mode = kwargs.get("mode", "normal")
92
+
93
+ def forward(
94
+ self,
95
+ q: torch.Tensor,
96
+ k: torch.Tensor,
97
+ v: torch.Tensor,
98
+ sim: torch.Tensor,
99
+ attn: torch.Tensor,
100
+ is_cross: bool,
101
+ place_in_unet: str,
102
+ num_heads: int,
103
+ **kwargs
104
+ ) -> torch.Tensor:
105
+ if is_cross or self.cur_step not in self.step_idx or self.cur_att_layer // 2 not in self.layer_idx:
106
+ return super().forward(q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs)
107
+
108
+ q_s, q_middle, q_t = q.chunk(3)
109
+ k_s, k_middle, k_t = k.chunk(3)
110
+ v_s, v_middle, v_t = v.chunk(3)
111
+ attn_s, attn_middle, attn_t = attn.chunk(3)
112
+
113
+ out_s = self.attn_batch(q_s, k_s, v_s, sim, attn_s, is_cross, place_in_unet, num_heads, **kwargs)
114
+ out_middle = self.attn_batch(q_middle, k_middle, v_middle, sim, attn_middle, is_cross, place_in_unet, num_heads, **kwargs)
115
+
116
+ if self.cur_step <= 0 and self.beta > 0 and \
117
+ self.structural_alignment:
118
+ q_t = self.align_queries_via_matching(q_s, q_t, beta=self.beta)
119
+
120
+ out_t = self.apply_mode(q_t, k_s, k_t, v_s, v_t, attn_t, sim, is_cross, place_in_unet, num_heads, **kwargs)
121
+
122
+ out = torch.cat([out_s, out_middle, out_t], dim=0)
123
+ return out
124
+
125
+ def apply_mode(
126
+ self,
127
+ q_t: torch.Tensor,
128
+ k_s: torch.Tensor,
129
+ k_t: torch.Tensor,
130
+ v_s: torch.Tensor,
131
+ v_t: torch.Tensor,
132
+ attn_t: torch.Tensor,
133
+ sim: torch.Tensor,
134
+ is_cross: bool,
135
+ place_in_unet: str,
136
+ num_heads: int,
137
+ **kwargs
138
+ ) -> torch.Tensor:
139
+ mode = self.mode
140
+
141
+ if 'dift' in mode and self.cur_step <= 0:
142
+ mode = 'normal'
143
+
144
+ if mode == "concat":
145
+ out_t = self.attn_batch(
146
+ q_t, torch.cat([k_s, 0.85 * k_t]), torch.cat([v_s, v_t]),
147
+ sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs
148
+ )
149
+
150
+ elif mode == "concat_dift":
151
+ updated_k_s, updated_v_s, _ = self.process_dift_features(kwargs.get("dift_features"), k_s, k_t, v_s, v_t)
152
+ out_t = self.attn_batch(
153
+ q_t, torch.cat([updated_k_s, k_t]), torch.cat([updated_v_s, v_t]),
154
+ sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs
155
+ )
156
+
157
+ elif mode == "masa":
158
+ out_t = self.attn_batch(q_t, k_s, v_s, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
159
+
160
+ elif mode == "normal":
161
+ out_t = self.attn_batch(q_t, k_t, v_t, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
162
+
163
+ elif mode == "lerp":
164
+ time = self.alpha
165
+ k_lerp = k_s + time * (k_t - k_s)
166
+ v_lerp = v_s + time * (v_t - v_s)
167
+ out_t = self.attn_batch(q_t, k_lerp, v_lerp, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
168
+
169
+ elif mode == "lerp_dift":
170
+ updated_k_s, updated_v_s, newness = self.process_dift_features(
171
+ kwargs.get("dift_features"), k_s, k_t, v_s, v_t, return_newness=self.newness
172
+ )
173
+ out_t = self.apply_lerp_dift(q_t, k_s, k_t, v_s, v_t, updated_k_s, updated_v_s, newness, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
174
+
175
+ elif mode in ("slerp", "log_slerp"):
176
+ time = self.alpha
177
+ k_slerp = self.slerp_fixed_length_batch(k_s, k_t, t=time)
178
+ v_slerp = self.slerp_batch(v_s, v_t, t=time, log_slerp="log" in mode)
179
+ out_t = self.attn_batch(q_t, k_slerp, v_slerp, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
180
+
181
+ elif mode in ("slerp_dift", "log_slerp_dift"):
182
+ out_t = self.apply_slerp_dift(q_t, k_s, k_t, v_s, v_t, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
183
+
184
+ else:
185
+ out_t = self.attn_batch(q_t, k_t, v_t, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
186
+
187
+ return out_t
188
+
189
+ def attn_batch(
190
+ self,
191
+ q: torch.Tensor,
192
+ k: torch.Tensor,
193
+ v: torch.Tensor,
194
+ sim: torch.Tensor,
195
+ attn: torch.Tensor,
196
+ is_cross: bool,
197
+ place_in_unet: str,
198
+ num_heads: int,
199
+ **kwargs
200
+ ) -> torch.Tensor:
201
+ b = q.shape[0] // num_heads
202
+ q = rearrange(q, "(b h) n d -> h (b n) d", h=num_heads)
203
+ k = rearrange(k, "(b h) n d -> h (b n) d", h=num_heads)
204
+ v = rearrange(v, "(b h) n d -> h (b n) d", h=num_heads)
205
+
206
+ scale = kwargs.get("scale", 1.0)
207
+ sim_batched = torch.einsum("h i d, h j d -> h i j", q, k) * scale
208
+ attn_batched = sim_batched.softmax(-1)
209
+
210
+ out = torch.einsum("h i j, h j d -> h i d", attn_batched, v)
211
+ out = rearrange(out, "h (b n) d -> b n (h d)", b=b)
212
+ return out
213
+
214
+ def slerp(self, x: torch.Tensor, y: torch.Tensor, t: float = 0.5) -> torch.Tensor:
215
+ x_norm = x.norm(p=2)
216
+ y_norm = y.norm(p=2)
217
+ if y_norm < 1e-12:
218
+ return x
219
+
220
+ y_normalized = y / y_norm
221
+ y_same_length = y_normalized * x_norm
222
+ dot_xy = (x * y_same_length).sum()
223
+ cos_theta = torch.clamp(dot_xy / (x_norm * x_norm), -1.0, 1.0)
224
+ theta = torch.acos(cos_theta)
225
+ if torch.isclose(theta, torch.tensor(0.0)):
226
+ return x
227
+
228
+ sin_theta = torch.sin(theta)
229
+ s1 = torch.sin((1.0 - t) * theta) / sin_theta
230
+ s2 = torch.sin(t * theta) / sin_theta
231
+ return s1 * x + s2 * y_same_length
232
+
233
+ def slerp_batch(
234
+ self,
235
+ x: torch.Tensor,
236
+ y: torch.Tensor,
237
+ t: float = 0.5,
238
+ eps: float = 1e-12,
239
+ log_slerp: bool = False
240
+ ) -> torch.Tensor:
241
+ """
242
+ Variation of SLERP for batches that allows for linear or logarithmic interpolation of magnitudes.
243
+ """
244
+ x_norm = x.norm(p=2, dim=-1, keepdim=True)
245
+ y_norm = y.norm(p=2, dim=-1, keepdim=True)
246
+ y_zero_mask = (y_norm < eps)
247
+
248
+ x_unit = x / (x_norm + eps)
249
+ y_unit = y / (y_norm + eps)
250
+ dot_xy = (x_unit * y_unit).sum(dim=-1, keepdim=True)
251
+ cos_theta = torch.clamp(dot_xy, -1.0, 1.0)
252
+
253
+ theta = torch.acos(cos_theta)
254
+ sin_theta = torch.sin(theta)
255
+ theta_zero_mask = (theta.abs() < 1e-7)
256
+
257
+ sin_theta_safe = torch.where(sin_theta.abs() < eps, torch.ones_like(sin_theta), sin_theta)
258
+ s1 = torch.sin((1.0 - t) * theta) / sin_theta_safe
259
+ s2 = torch.sin(t * theta) / sin_theta_safe
260
+ dir_interp = s1 * x_unit + s2 * y_unit
261
+
262
+ if not log_slerp:
263
+ mag_interp = (1.0 - t) * x_norm + t * y_norm
264
+ else:
265
+ mag_interp = (x_norm ** (1.0 - t)) * (y_norm ** t)
266
+
267
+ out = mag_interp * dir_interp
268
+ out = torch.where(y_zero_mask | theta_zero_mask, x, out)
269
+ return out
270
+
271
+
272
+ def slerp_fixed_length_batch(
273
+ self,
274
+ x: torch.Tensor,
275
+ y: torch.Tensor,
276
+ t: float = 0.5,
277
+ eps: float = 1e-12
278
+ ) -> torch.Tensor:
279
+ """
280
+ performing SLERP while preserving the norm of the source tensor x
281
+ """
282
+ x_norm = x.norm(p=2, dim=-1, keepdim=True)
283
+ y_norm = y.norm(p=2, dim=-1, keepdim=True)
284
+ y_zero_mask = (y_norm < eps)
285
+ y_normalized = y / (y_norm + eps)
286
+ y_same_length = y_normalized * x_norm
287
+ dot_xy = (x * y_same_length).sum(dim=-1, keepdim=True)
288
+ cos_theta = torch.clamp(dot_xy / (x_norm * x_norm + eps), -1.0, 1.0)
289
+ theta = torch.acos(cos_theta)
290
+ sin_theta = torch.sin(theta)
291
+
292
+ sin_theta_safe = torch.where(sin_theta.abs() < eps, torch.ones_like(sin_theta), sin_theta)
293
+ s1 = torch.sin((1.0 - t) * theta) / sin_theta_safe
294
+ s2 = torch.sin(t * theta) / sin_theta_safe
295
+ out = s1 * x + s2 * y_same_length
296
+ theta_zero_mask = (theta.abs() < 1e-7)
297
+
298
+ out = torch.where(y_zero_mask | theta_zero_mask, x, out)
299
+ return out
300
+
301
+ def apply_lerp_dift(
302
+ self,
303
+ q_t: torch.Tensor,
304
+ k_s: torch.Tensor,
305
+ k_t: torch.Tensor,
306
+ v_s: torch.Tensor,
307
+ v_t: torch.Tensor,
308
+ updated_k_s: torch.Tensor,
309
+ updated_v_s: torch.Tensor,
310
+ newness: torch.Tensor,
311
+ sim: torch.Tensor,
312
+ attn_t: torch.Tensor,
313
+ is_cross: bool,
314
+ place_in_unet: str,
315
+ num_heads: int,
316
+ **kwargs
317
+ ) -> torch.Tensor:
318
+ alpha = self.alpha
319
+ k_lerp = k_s + alpha * (k_t - k_s)
320
+ v_lerp = v_s + alpha * (v_t - v_s)
321
+ if alpha > 0:
322
+ k_t_new = newness * k_t + (1 - newness) * k_lerp
323
+ v_t_new = newness * v_t + (1 - newness) * v_lerp
324
+ else:
325
+ k_t_new = k_s
326
+ v_t_new = v_s
327
+
328
+ out_t = self.attn_batch(q_t, k_t_new, v_t_new, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
329
+ return out_t
330
+
331
+ def apply_slerp_dift(
332
+ self,
333
+ q_t: torch.Tensor,
334
+ k_s: torch.Tensor,
335
+ k_t: torch.Tensor,
336
+ v_s: torch.Tensor,
337
+ v_t: torch.Tensor,
338
+ sim: torch.Tensor,
339
+ attn_t: torch.Tensor,
340
+ is_cross: bool,
341
+ place_in_unet: str,
342
+ num_heads: int,
343
+ **kwargs
344
+ ) -> torch.Tensor:
345
+ updated_k_s, updated_v_s, newness = self.process_dift_features(
346
+ kwargs.get("dift_features"), k_s, k_t, v_s, v_t, return_newness=self.newness
347
+ )
348
+ alpha = self.alpha
349
+ log_slerp = "log" in self.mode
350
+
351
+ # Interpolate from k_t->updated_k_s so that if alpha=0, we get k_t
352
+ k_slerp = self.slerp_fixed_length_batch(k_t, updated_k_s, t=1-alpha)
353
+ v_slerp = self.slerp_batch(v_t, updated_v_s, t=1-alpha, log_slerp=log_slerp)
354
+
355
+ if alpha > 0:
356
+ k_t_new = newness * k_t + (1 - newness) * k_slerp
357
+ v_t_new = newness * v_t + (1 - newness) * v_slerp
358
+ else:
359
+ k_t_new = k_s
360
+ v_t_new = v_s
361
+
362
+ out_t = self.attn_batch(q_t, k_t_new, v_t_new, sim, attn_t, is_cross, place_in_unet, num_heads, **kwargs)
363
+ return out_t
364
+
365
+ def process_dift_features(
366
+ self,
367
+ dift_features: torch.Tensor,
368
+ k_s: torch.Tensor,
369
+ k_t: torch.Tensor,
370
+ v_s: torch.Tensor,
371
+ v_t: torch.Tensor,
372
+ return_newness: bool = True
373
+ ):
374
+ dift_s, _, dift_t = dift_features.chunk(3)
375
+ k_s1 = k_s.permute(0, 2, 1).reshape(k_s.shape[0], k_s.shape[2], int(k_s.shape[1]**0.5), -1)
376
+ v_s1 = v_s.permute(0, 2, 1).reshape(v_s.shape[0], v_s.shape[2], int(v_s.shape[1]**0.5), -1)
377
+
378
+ k_s1 = k_s1.reshape(-1, k_s1.shape[-2], k_s1.shape[-1])
379
+ v_s1 = v_s1.reshape(-1, v_s1.shape[-2], v_s1.shape[-1])
380
+
381
+ ################# uncomment only for visualization #################
382
+ # result = gen_nn_map(
383
+ # [dift_s[0], dift_s[0]],
384
+ # dift_s[0],
385
+ # dift_t[0],
386
+ # kernel_size=1,
387
+ # stride=1,
388
+ # device=k_s.device,
389
+ # timestep=self.cur_step,
390
+ # visualize=True,
391
+ # return_newness=return_newness
392
+ # )
393
+ #####################################################################
394
+
395
+ resized_src = F.interpolate(dift_s[0].unsqueeze(0), size=k_s1.shape[-1], mode='bilinear', align_corners=False).squeeze(0)
396
+ resized_tgt = F.interpolate(dift_t[0].unsqueeze(0), size=k_s1.shape[-1], mode='bilinear', align_corners=False).squeeze(0)
397
+
398
+ result = gen_nn_map(
399
+ [k_s1, v_s1],
400
+ resized_src,
401
+ resized_tgt,
402
+ kernel_size=1,
403
+ stride=1,
404
+ device=k_s.device,
405
+ timestep=self.cur_step,
406
+ return_newness=return_newness
407
+ )
408
+
409
+ if return_newness:
410
+ updated_k_s, updated_v_s, newness = result
411
+ else:
412
+ updated_k_s, updated_v_s = result
413
+ newness = torch.zeros_like(updated_k_s[:1]).to(k_s.device)
414
+
415
+ newness = newness.view(-1).unsqueeze(0).unsqueeze(-1)
416
+ updated_k_s = updated_k_s.reshape(k_s.shape[0], k_s.shape[2], -1).permute(0, 2, 1)
417
+ updated_v_s = updated_v_s.reshape(v_s.shape[0], v_s.shape[2], -1).permute(0, 2, 1)
418
+
419
+ return updated_k_s, updated_v_s, newness
420
+
421
+ def sinkhorn(self, cost_matrix, max_iter=50, epsilon=1e-8):
422
+ n, m = cost_matrix.shape
423
+ K = torch.exp(-cost_matrix / cost_matrix.std()) # Kernelized cost matrix
424
+ u = torch.ones(n, device=cost_matrix.device) / n
425
+ v = torch.ones(m, device=cost_matrix.device) / m
426
+
427
+ for _ in range(max_iter):
428
+ u_prev = u.clone()
429
+ u = 1.0 / (K @ v)
430
+ v = 1.0 / (K.T @ u)
431
+ if torch.max(torch.abs(u - u_prev)) < epsilon:
432
+ break
433
+
434
+ P = torch.diag(u) @ K @ torch.diag(v)
435
+ return P
436
+
437
+ def align_queries_via_matching(self, q_s: torch.Tensor, q_t: torch.Tensor, beta: float = 0.5, device: str = "cuda"):
438
+ q_s = q_s.to(device)
439
+ q_t = q_t.to(device)
440
+
441
+ B, _, _ = q_s.shape
442
+ q_t_updated = torch.zeros_like(q_t, device=device)
443
+
444
+ for b in range(B):
445
+ ########################### L2 ##############################
446
+ # cost_matrix1 = (q_s[b].unsqueeze(1) - q_t[b].unsqueeze(0)).pow(2).sum(dim=-1)
447
+ ######################### cosine ############################
448
+ cost_matrix1 = - F.cosine_similarity(
449
+ q_s[b].unsqueeze(1), q_t[b].unsqueeze(0), dim=-1)
450
+ #############################################################
451
+ # cost_matrix2 = (q_t[b].unsqueeze(1) - q_t[b].unsqueeze(0)).pow(2).sum(dim=-1)
452
+ cost_matrix2 = torch.abs(torch.arange(q_t[b].shape[0], device=device).unsqueeze(0) -
453
+ torch.arange(q_t[b].shape[0], device=device).unsqueeze(1)).float()
454
+ cost_matrix2 = cost_matrix2 ** 0.5
455
+ # cost_matrix2 = torch.where(cost_matrix2 > 0, 1.0, 0.0)
456
+
457
+ mean1 = cost_matrix1.mean()
458
+ std1 = cost_matrix1.std()
459
+ mean2 = cost_matrix2.mean()
460
+ std2 = cost_matrix2.std()
461
+ cost_func_1_std = (cost_matrix1 - mean1) / (std1 + 1e-8)
462
+ cost_func_2_std = (cost_matrix2 - mean2) / (std2 + 1e-8)
463
+
464
+ cost_matrix = beta * cost_func_1_std + (1.0 - beta) * cost_func_2_std
465
+ cost_np = cost_matrix.detach().cpu().numpy()
466
+ row_ind, col_ind = linear_sum_assignment(cost_np)
467
+ q_t_updated[b] = q_t[b][col_ind]
468
+
469
+ # P = self.sinkhorn(cost_matrix)
470
+ # col_ind = P.argmax(dim=1)
471
+ # idea 1
472
+ # q_t_updated[b] = q_t[b][col_ind]
473
+ # idea 2
474
+ # q_t_updated[b] = P @ q_t[b]
475
+
476
+ return q_t_updated
477
+
478
+
model/modules/dift_utils.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import numpy as np
6
+ from typing import List
7
+ from sklearn.decomposition import PCA
8
+ from typing import Optional, Tuple
9
+ from PIL import Image
10
+ from model.modules.new_object_detection import *
11
+
12
+
13
+ class DIFTLatentStore:
14
+ def __init__(self, steps: List[int], up_ft_indices: List[int]):
15
+ self.steps = steps
16
+ self.up_ft_indices = up_ft_indices
17
+ self.dift_features = {}
18
+ self.smoothed_dift_features = {}
19
+
20
+ def __call__(self, features: torch.Tensor, t: int, layer_index: int):
21
+ if t in self.steps and layer_index in self.up_ft_indices:
22
+ self.dift_features[f'{int(t)}_{layer_index}'] = features
23
+
24
+ def smooth(self, kernel_size=3, sigma=1):
25
+ for key, value in self.dift_features.items():
26
+ if key not in self.smoothed_dift_features:
27
+ self.smoothed_dift_features[key] = torch.stack([gaussian_smooth(x, kernel_size=kernel_size, sigma=sigma) for x in value], dim=0)
28
+
29
+ def copy(self):
30
+ copy_dift = DIFTLatentStore(self.steps, self.up_ft_indices)
31
+
32
+ for key, value in self.dift_features.items():
33
+ copy_dift.dift_features[key] = value.clone()
34
+
35
+ return copy_dift
36
+
37
+ def reset(self):
38
+ self.dift_features = {}
39
+ self.smoothed_dift_features = {}
40
+
41
+ def gaussian_smooth(input_tensor, kernel_size=3, sigma=1):
42
+ kernel = np.fromfunction(
43
+ lambda x, y: (1/ (2 * np.pi * sigma ** 2)) *
44
+ np.exp(-((x - (kernel_size - 1) / 2) ** 2 + (y - (kernel_size - 1) / 2) ** 2) / (2 * sigma ** 2)),
45
+ (kernel_size, kernel_size)
46
+ )
47
+ kernel = torch.Tensor(kernel / kernel.sum()).to(input_tensor.dtype).to(input_tensor.device)
48
+
49
+ kernel = kernel.unsqueeze(0).unsqueeze(0)
50
+
51
+ smoothed_slices = []
52
+ for i in range(input_tensor.size(0)):
53
+ slice_tensor = input_tensor[i, :, :]
54
+ slice_tensor = F.conv2d(slice_tensor.unsqueeze(0).unsqueeze(0), kernel, padding=kernel_size // 2)[0, 0]
55
+ smoothed_slices.append(slice_tensor)
56
+
57
+ smoothed_tensor = torch.stack(smoothed_slices, dim=0)
58
+
59
+ return smoothed_tensor
60
+
61
+ def cos_dist(a, b):
62
+ a_norm = F.normalize(a, dim=-1)
63
+ b_norm = F.normalize(b, dim=-1)
64
+ res = a_norm @ b_norm.T
65
+ return 1 - res
66
+
67
+ def extract_patches(feature_map: torch.Tensor, patch_size: int, stride: int) -> torch.Tensor:
68
+ # feature_map is (C, H, W). Unfold requires (B, C, H, W).
69
+ feature_map = feature_map.unsqueeze(0) # (1, C, H, W)
70
+
71
+ # Unfold: output shape will be (B, C * patch_size^2, num_patches)
72
+ patches = F.unfold(
73
+ feature_map,
74
+ kernel_size=patch_size,
75
+ stride=stride
76
+ )
77
+ # Now patches is (1, C*patch_size^2, num_patches)
78
+
79
+ # Transpose to get shape (num_patches, C*patch_size^2)
80
+ patches = patches.squeeze(0).transpose(0, 1) # (num_patches, C*patch_size^2)
81
+ return patches
82
+
83
+ def reassemble_patches(
84
+ patches: torch.Tensor,
85
+ out_shape: Tuple[int, int, int],
86
+ patch_size: int,
87
+ stride: int
88
+ ) -> torch.Tensor:
89
+ C, H, W = out_shape
90
+
91
+ # 1) Convert from (num_patches, C*patch_size^2) to (B=1, C*patch_size^2, num_patches)
92
+ patches_4d = patches.transpose(0, 1).unsqueeze(0) # (1, C*patch_size^2, num_patches)
93
+
94
+ # 2) fold: reassemble patches to (1, C, H, W)
95
+ reassembled = F.fold(
96
+ patches_4d,
97
+ output_size=(H, W),
98
+ kernel_size=patch_size,
99
+ stride=stride
100
+ )
101
+
102
+ # 3) Create a divisor mask to account for overlapping regions.
103
+ # We do this by folding a "ones" tensor of the same shape as patches_4d.
104
+ ones_input = torch.ones_like(patches_4d)
105
+ overlap_count = F.fold(
106
+ ones_input,
107
+ output_size=(H, W),
108
+ kernel_size=patch_size,
109
+ stride=stride
110
+ )
111
+
112
+ # 4) Divide to normalize overlapping areas
113
+ reassembled = reassembled / overlap_count.clamp_min(1e-8)
114
+
115
+ # 5) Remove the batch dimension -> (C, H, W)
116
+ reassembled = reassembled.squeeze(0)
117
+
118
+ return reassembled
119
+
120
+ def calculate_patch_distance(index1: int, index2: int, grid_size: int, stride: int, patch_size: int) -> float:
121
+ row1, col1 = index1 // grid_size, index1 % grid_size
122
+ row2, col2 = index2 // grid_size, index2 % grid_size
123
+ # print('row1, col1:', row1, col1)
124
+ x_center1, y_center1 = (row1 * stride) + (patch_size / 2), (col1 * stride) + (patch_size / 2)
125
+ x_center2, y_center2 = (row2 * stride) + (patch_size / 2), (col2 * stride) + (patch_size / 2)
126
+ return math.sqrt((x_center2 - x_center1)**2 + (y_center2 - y_center1)**2)
127
+
128
+ def gen_nn_map(
129
+ latent,
130
+ src_features,
131
+ tgt_features,
132
+ device,
133
+ kernel_size=3,
134
+ stride=1,
135
+ return_newness=False,
136
+ **kwargs
137
+ ):
138
+ batch_size = kwargs.get("batch_size", None)
139
+ timestep = kwargs.get("timestep", None)
140
+
141
+ if kwargs.get("visualize", False):
142
+ dift_visualization(src_features, tgt_features, filename_out=f"output/feat_colors_{timestep}.png")
143
+
144
+ src_patches = extract_patches(src_features, kernel_size, stride)
145
+ tgt_patches = extract_patches(tgt_features, kernel_size, stride)
146
+
147
+ if isinstance(latent, list):
148
+ latent_patches = [extract_patches(l, kernel_size, stride) for l in latent]
149
+ else:
150
+ latent_patches = extract_patches(latent, kernel_size, stride)
151
+
152
+ num_tgt = src_patches.size(0)
153
+ batch = batch_size or num_tgt
154
+ nearest_neighbor_indices = torch.empty(num_tgt, dtype=torch.long, device=device)
155
+ nearest_neighbor_distances = torch.empty(num_tgt, dtype=torch.long, device=device)
156
+ dist_chunks = []
157
+
158
+ for start in range(0, num_tgt, batch):
159
+ sims = cos_dist(src_patches, tgt_patches[start : start + batch])
160
+ dist_chunks.append(sims)
161
+ min_distances, best_idx = sims.min(0)
162
+ nearest_neighbor_indices[start : start + batch] = best_idx
163
+ nearest_neighbor_distances[start : start + batch] = min_distances
164
+
165
+ if not isinstance(latent, list):
166
+ aligned_latent = latent_patches[nearest_neighbor_indices]
167
+ aligned_latent = reassemble_patches(aligned_latent, latent.shape, kernel_size, stride)
168
+ else:
169
+ aligned_latent = [latent_patches[i][nearest_neighbor_indices] for i in range(len(latent_patches))]
170
+ aligned_latent = [reassemble_patches(l, latent[0].shape, kernel_size, stride) for l in aligned_latent]
171
+
172
+ if return_newness:
173
+ dist_matrix = torch.cat(dist_chunks, dim=0)
174
+ newness_method = 'two_sided'
175
+ # newness_method = 'distance'
176
+ if newness_method.lower() == "distance":
177
+ newness = detect_newness_distance(nearest_neighbor_distances, quantile=0.97)
178
+
179
+ elif newness_method.lower() == "two_sided":
180
+ newness = detect_newness_two_sided(dist_matrix, k=4)
181
+
182
+ out_shape = latent[0].shape if isinstance(latent, list) else latent.shape
183
+ out_shape = (1, out_shape[1], out_shape[2])
184
+
185
+ newness = reassemble_patches(newness.unsqueeze(-1), out_shape, kernel_size, stride)
186
+
187
+
188
+ del src_patches, tgt_patches, latent_patches, nearest_neighbor_indices, nearest_neighbor_distances
189
+
190
+ ################## visualization of changing source features to match target ##################
191
+ if False:
192
+ updated_src_patches = src_patches[nearest_neighbor_indices]
193
+ updated_src_patches = reassemble_patches(updated_src_patches, src_features.shape, kernel_size, stride)
194
+ dift_visualization(
195
+ updated_src_patches, tgt_features,
196
+ filename_out=f"output/updated_feat_colors_{timestep}.png",
197
+ )
198
+
199
+ if return_newness:
200
+ if isinstance(aligned_latent, list):
201
+ aligned_latent.append(newness)
202
+ else:
203
+ return aligned_latent, newness
204
+ return aligned_latent
205
+
206
+ def dift_visualization(
207
+ src_feature: torch.Tensor,
208
+ tgt_feature: torch.Tensor,
209
+ filename_out: str,
210
+ resize_to: Optional[Tuple[int, int]] = (512, 512)
211
+ ):
212
+ """
213
+ Flatten features, apply PCA for 3D embedding, normalize for RGB, then reshape and save as image
214
+ """
215
+
216
+ C, H_s, W_s = src_feature.shape
217
+ _, H_t, W_t = tgt_feature.shape
218
+
219
+ src_flat = src_feature.permute(1, 2, 0).reshape(-1, C) # (H_s*W_s, C)
220
+ tgt_flat = tgt_feature.permute(1, 2, 0).reshape(-1, C) # (H_t*W_t, C)
221
+
222
+ all_features = torch.cat([src_flat, tgt_flat], dim=0) # shape: (N_total, C)
223
+
224
+ all_features_np = all_features.detach().cpu().numpy()
225
+
226
+ num_components = 3
227
+ pca = PCA(n_components=num_components)
228
+ all_features_3d = pca.fit_transform(all_features_np) # shape: (N_total, 3)
229
+
230
+ # 6) Normalize each dimension to [0,1]
231
+ def normalize_to_01(array_2d):
232
+ min_vals = array_2d.min(axis=0)
233
+ max_vals = array_2d.max(axis=0)
234
+ denom = (max_vals - min_vals) + 1e-8
235
+ return (array_2d - min_vals) / denom
236
+
237
+ all_features_rgb = normalize_to_01(all_features_3d)
238
+
239
+ N_src = H_s * W_s
240
+ src_rgb_flat = all_features_rgb[:N_src] # (N_src, 3)
241
+ tgt_rgb_flat = all_features_rgb[N_src:] # (N_tgt, 3)
242
+
243
+ src_color_map = src_rgb_flat.reshape(H_s, W_s, 3)
244
+ tgt_color_map = tgt_rgb_flat.reshape(H_t, W_t, 3)
245
+
246
+ src_img = Image.fromarray((src_color_map * 255).astype(np.uint8))
247
+ tgt_img = Image.fromarray((tgt_color_map * 255).astype(np.uint8))
248
+
249
+ src_img_resized = src_img.resize(resize_to, Image.Resampling.LANCZOS)
250
+ tgt_img_resized = tgt_img.resize(resize_to, Image.Resampling.LANCZOS)
251
+
252
+ combined_width = resize_to[0] * 2
253
+ combined_height = resize_to[1]
254
+ combined_img = Image.new("RGB", (combined_width, combined_height))
255
+ combined_img.paste(src_img_resized, (0, 0))
256
+ combined_img.paste(tgt_img_resized, (resize_to[0], 0))
257
+
258
+ os.makedirs(os.path.dirname(filename_out), exist_ok=True)
259
+ combined_img.save(filename_out)
260
+
261
+ print(f"Saved visualization to {filename_out}")
262
+
model/modules/freq_filters.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/kookie12/FlexiEdit/blob/main/flexiedit/frequency_utils.py
2
+
3
+ import torch
4
+ import torch.fft as fft
5
+ import math
6
+ import torch.nn.functional as F
7
+
8
+ ''' define hyperparameters '''
9
+ # low-pass filter settings
10
+ filter_type= "gaussian" #"butterworth"
11
+ n= 4 # gaussian parameter
12
+ # Sampling process settings
13
+ global alpha, reinversion_step, d_s, d_t, refined_step, masa_step_original, masa_step_target_branch, masa_step_retarget_branch
14
+ alpha = 0.7
15
+ d_t= 0.3
16
+ d_s= 0.3
17
+ refined_step = 0
18
+ masa_step_original = 4
19
+ masa_step_target_branch = 51
20
+ masa_step_retarget_branch = 0
21
+
22
+ def gaussian_low_pass_filter(shape, d_s=0.25, d_t=0.25):
23
+ T, H, W = shape[-3], shape[-2], shape[-1]
24
+ mask = torch.zeros(shape)
25
+ if d_s==0 or d_t==0:
26
+ return mask
27
+ for t in range(T):
28
+ for h in range(H):
29
+ for w in range(W):
30
+ d_square = (((d_s/d_t)*(2*t/T-1))**2 + (2*h/H-1)**2 + (2*w/W-1)**2)
31
+ mask[..., t,h,w] = math.exp(-1/(2*d_s**2) * d_square)
32
+ return mask
33
+
34
+
35
+ def butterworth_low_pass_filter(shape, n=4, d_s=0.25, d_t=0.25):
36
+ T, H, W = shape[-3], shape[-2], shape[-1]
37
+ mask = torch.zeros(shape)
38
+ if d_s==0 or d_t==0:
39
+ return mask
40
+ for t in range(T):
41
+ for h in range(H):
42
+ for w in range(W):
43
+ d_square = (((d_s/d_t)*(2*t/T-1))**2 + (2*h/H-1)**2 + (2*w/W-1)**2)
44
+ mask[..., t,h,w] = 1 / (1 + (d_square / d_s**2)**n)
45
+ return mask
46
+
47
+
48
+ def ideal_low_pass_filter(shape, d_s=0.25, d_t=0.25):
49
+ T, H, W = shape[-3], shape[-2], shape[-1]
50
+ mask = torch.zeros(shape)
51
+ if d_s==0 or d_t==0:
52
+ return mask
53
+ for t in range(T):
54
+ for h in range(H):
55
+ for w in range(W):
56
+ d_square = (((d_s/d_t)*(2*t/T-1))**2 + (2*h/H-1)**2 + (2*w/W-1)**2)
57
+ mask[..., t,h,w] = 1 if d_square <= d_s*2 else 0
58
+ return mask
59
+
60
+
61
+ def box_low_pass_filter(shape, d_s=0.25, d_t=0.25):
62
+ T, H, W = shape[-3], shape[-2], shape[-1]
63
+ mask = torch.zeros(shape)
64
+ if d_s==0 or d_t==0:
65
+ return mask
66
+
67
+ threshold_s = round(int(H // 2) * d_s)
68
+ threshold_t = round(T // 2 * d_t)
69
+
70
+ cframe, crow, ccol = T // 2, H // 2, W //2
71
+ #mask[..., cframe - threshold_t:cframe + threshold_t, crow - threshold_s:crow + threshold_s, ccol - threshold_s:ccol + threshold_s] = 1.0
72
+ mask[..., crow - threshold_s:crow + threshold_s, ccol - threshold_s:ccol + threshold_s] = 1.0
73
+
74
+ return mask
75
+
76
+ def get_freq_filter(shape, device, filter_type, n, d_s, d_t):
77
+ if filter_type == "gaussian":
78
+ return gaussian_low_pass_filter(shape=shape, d_s=d_s, d_t=d_t).to(device)
79
+ elif filter_type == "ideal":
80
+ return ideal_low_pass_filter(shape=shape, d_s=d_s, d_t=d_t).to(device)
81
+ elif filter_type == "box":
82
+ return box_low_pass_filter(shape=shape, d_s=d_s, d_t=d_t).to(device)
83
+ elif filter_type == "butterworth":
84
+ return butterworth_low_pass_filter(shape=shape, n=n, d_s=d_s, d_t=d_t).to(device)
85
+ else:
86
+ raise NotImplementedError
87
+
88
+ def freq_2d(x, LPF, alpha):
89
+ # FFT
90
+ x_freq = fft.fftn(x, dim=(-3, -2, -1))
91
+ x_freq = fft.fftshift(x_freq, dim=(-3, -2, -1))
92
+
93
+ # frequency mix
94
+ HPF = 1 - LPF
95
+
96
+ x_freq_low = x_freq * LPF
97
+ x_freq_high = x_freq * HPF
98
+
99
+ x_freq_sum = x_freq
100
+
101
+ # IFFT
102
+ _x_freq_low = fft.ifftshift(x_freq_low, dim=(-3, -2, -1))
103
+ x_low = fft.ifftn(_x_freq_low, dim=(-3, -2, -1)).real
104
+ x_low_alpha = fft.ifftn(_x_freq_low*alpha, dim=(-3, -2, -1)).real
105
+
106
+ _x_freq_high = fft.ifftshift(x_freq_high, dim=(-3, -2, -1))
107
+ x_high = fft.ifftn(_x_freq_high, dim=(-3, -2, -1)).real
108
+ x_high_alpha = fft.ifftn(_x_freq_high*alpha, dim=(-3, -2, -1)).real
109
+
110
+ _x_freq_sum = fft.ifftshift(x_freq_sum, dim=(-3, -2, -1))
111
+ x_sum = fft.ifftn(_x_freq_sum, dim=(-3, -2, -1)).real
112
+
113
+ _x_freq_low_alpha_high = fft.ifftshift(x_freq_low + x_freq_high*alpha, dim=(-3, -2, -1))
114
+ x_low_alpha_high = fft.ifftn(_x_freq_low_alpha_high, dim=(-3, -2, -1)).real
115
+
116
+ _x_freq_high_alpha_low = fft.ifftshift(x_freq_low*alpha + x_freq_high, dim=(-3, -2, -1))
117
+ x_high_alpha_low = fft.ifftn(_x_freq_high_alpha_low, dim=(-3, -2, -1)).real
118
+
119
+ _x_freq_alpha_high_alpha_low = fft.ifftshift(x_freq_low*alpha + x_freq_high*alpha, dim=(-3, -2, -1))
120
+ x_alpha_high_alpha_low = fft.ifftn(_x_freq_alpha_high_alpha_low, dim=(-3, -2, -1)).real
121
+
122
+ return x_low, x_high, x_sum, x_low_alpha, x_high_alpha, x_low_alpha_high, x_high_alpha_low, x_alpha_high_alpha_low
123
+
124
+
125
+ def freq_exp(feat, mode, user_mask, auto_mask, movement_intensifier):
126
+ movement_intensifier = 1 - movement_intensifier
127
+ """ Frequency manipulation for latent space. """
128
+ feat = feat.view(4,1,64,64)
129
+ f_shape = feat.shape # 1, 4, 64, 64
130
+ LPF = get_freq_filter(f_shape, feat.device, filter_type, n, d_s, d_t) # d_s, d_t
131
+ f_dtype = feat.dtype
132
+ feat_low, feat_high, feat_sum, feat_low_alpha, feat_high_alpha, feat_low_alpha_high, feat_high_alpha_low, x_alpha_high_alpha_low = freq_2d(feat.to(torch.float64), LPF, movement_intensifier)
133
+ feat_low = feat_low.to(f_dtype)
134
+ feat_high = feat_high.to(f_dtype)
135
+ feat_sum = feat_sum.to(f_dtype)
136
+ feat_low_alpha = feat_low_alpha.to(f_dtype)
137
+ feat_high_alpha = feat_high_alpha.to(f_dtype)
138
+ feat_low_alpha_high = feat_low_alpha_high.to(f_dtype)
139
+ feat_high_alpha_low = feat_high_alpha_low.to(f_dtype)
140
+
141
+ latent_low = feat_low.view(1,4,64,64)
142
+
143
+ latent_high = feat_high.view(1,4,64,64)
144
+
145
+ latent_sum = feat_sum.view(1,4,64,64)
146
+
147
+ latent_low_alpha_high = feat_low_alpha_high.view(1,4,64,64)
148
+ latent_high_alpha_low = feat_high_alpha_low.view(1,4,64,64)
149
+
150
+ mask = torch.zeros_like(latent_sum)
151
+ if mode == "auto_mask":
152
+ auto_mask = auto_mask.unsqueeze(1) # [1,64,64] => [1,1,64,64]
153
+ mask = auto_mask.expand_as(latent_sum) # [1,1,64,64] => [1,4,64,64]
154
+
155
+ elif mode == "user_mask":
156
+ bbx_start_point, bbx_end_point = user_mask
157
+ mask[:, :, bbx_start_point[1]//8:bbx_end_point[1]//8, bbx_start_point[0]//8:bbx_end_point[0]//8] = 1
158
+
159
+ latents_shape = latent_sum.shape
160
+ random_gaussian = torch.randn(latents_shape, device=latent_sum.device)
161
+
162
+ # Apply gaussian scaling
163
+ g_range = random_gaussian.max() - random_gaussian.min()
164
+ l_range = latent_low_alpha_high.max() - latent_low_alpha_high.min()
165
+ random_gaussian = random_gaussian * (l_range/g_range)
166
+
167
+ # No scaling applied. If you wish to apply scaling to the mask, replace the following lines accordingly.
168
+ s_range, r_range, s_range2, r_range2 = 1, 1, 1, 1
169
+
170
+ latent_mask_h = latent_sum * (1 - mask) + (latent_low_alpha_high + (1-movement_intensifier)*random_gaussian) * (s_range/r_range) *mask # edit 할 부분에 high frequency가 줄어들고 가우시안 더하기
171
+ latent_mask_l = latent_sum * (1 - mask) + (latent_high_alpha_low + (1-movement_intensifier)*random_gaussian) * (s_range2/r_range2) *mask # edit 할 부분에 low frequency가 줄어들고 가우시안 더하기
172
+
173
+ return latent_mask_h, latent_mask_l, latent_sum # latent_low, latent_high, latent_sum
model/modules/new_object_detection.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def distance_to_similarity(distances, temperature=1.0):
4
+ """
5
+ Turns a distance matrix into a similarity matrix so it works with distribution-based metrics.
6
+ """
7
+ similarities = torch.exp(-distances / temperature)
8
+ similarities = torch.clamp(similarities, min=1e-8)
9
+ return similarities
10
+
11
+ #################################
12
+ ## "New Object" Detection ##
13
+ #################################
14
+
15
+ def detect_newness_two_sided(distances, k=3, quantile=0.97):
16
+ device = distances.device
17
+ N_src, N_tgt = distances.shape
18
+
19
+ topk_src_idx_t = torch.topk(distances, k, dim=0, largest=False).indices # [k, N_tgt]
20
+ topk_tgt_idx_s = torch.topk(distances, k, dim=1, largest=False).indices # [N_src, k]
21
+
22
+ src_to_tgt_mask = torch.zeros((N_src, N_tgt), device=device)
23
+ tgt_to_src_mask = torch.zeros((N_src, N_tgt), device=device)
24
+
25
+ row_indices = topk_src_idx_t # [k, N_tgt]
26
+ col_indices = torch.arange(N_tgt, device=device).unsqueeze(0).repeat(k, 1) # [k, N_tgt]
27
+ src_to_tgt_mask[row_indices, col_indices] = 1.0 # Assign 1.0 at the top-k positions
28
+
29
+ row_indices = torch.arange(N_src, device=device).unsqueeze(1).repeat(1, k) # [N_src, k]
30
+ col_indices = topk_tgt_idx_s # [N_src, k]
31
+ tgt_to_src_mask[row_indices, col_indices] = 1.0 # Assign 1.0 at the top-k positions
32
+
33
+ overlap_mask = (src_to_tgt_mask * tgt_to_src_mask).sum(dim=0) > 0 # [N_tgt]
34
+
35
+ distances[:, overlap_mask] = 0.0
36
+
37
+ two_sided_mask = (~overlap_mask).float()
38
+
39
+ min_distances, _ = distances.min(dim=0)
40
+ threshold = torch.quantile(min_distances, quantile)
41
+ threshold_mask = (min_distances > threshold).float()
42
+
43
+ combined_mask = two_sided_mask * threshold_mask
44
+ return combined_mask
45
+
46
+ def detect_newness_distance(min_distances, quantile=0.97):
47
+ """
48
+ Old approach: threshold on min distance at a chosen percentile.
49
+ """
50
+ threshold = torch.quantile(min_distances, quantile)
51
+ newness_mask = (min_distances > threshold).float()
52
+ return newness_mask
53
+
54
+ def detect_newness_topk_margin(distances, top_k=2, quantile=0.03):
55
+ """
56
+ Top-k margin approach in distance space.
57
+ distances: [N_src, N_tgt]
58
+ Sort each column ascending => best match is index 0, second best is index 1, etc.
59
+ A smaller margin => ambiguous => likely new.
60
+ We threshold the margin at some percentile.
61
+ """
62
+ sorted_dists, _ = torch.sort(distances, dim=0)
63
+ best = sorted_dists[0] # [N_tgt]
64
+ second_best = sorted_dists[1] if top_k >= 2 else sorted_dists[0] # [N_tgt]
65
+ margin = second_best - best # [N_tgt]
66
+
67
+ # If margin < threshold => ambiguous => "new"
68
+ # We'll pick threshold as a quantile of margin
69
+ threshold = torch.quantile(margin, quantile)
70
+ newness_mask = (margin < threshold).float()
71
+ return newness_mask
72
+
73
+ def detect_newness_entropy(distances, temperature=1.0, quantile=0.97):
74
+ """
75
+ Entropy-based approach. First convert distance->similarity with an exponential.
76
+ Then normalize to get a distribution for each target patch, compute Shannon entropy.
77
+ High entropy => new object (no strong match).
78
+ """
79
+ similarities = distance_to_similarity(distances, temperature=temperature)
80
+ probs = similarities / similarities.sum(dim=0, keepdim=True) # [N_src, N_tgt]
81
+ # Shannon Entropy: -sum(p log p)
82
+ entropy = -torch.sum(probs * torch.log(probs), dim=0) # [N_tgt]
83
+
84
+ # threshold
85
+ threshold = torch.quantile(entropy, quantile)
86
+ newness_mask = (entropy > threshold).float()
87
+ return newness_mask
88
+
89
+ def detect_newness_gini(distances, temperature=1.0, quantile=0.97):
90
+ """
91
+ Gini impurity-based approach. Convert distances to similarities,
92
+ get a distribution, compute Gini.
93
+ High Gini => wide distribution => new object.
94
+ """
95
+ similarities = distance_to_similarity(distances, temperature=temperature)
96
+ probs = similarities / similarities.sum(dim=0, keepdim=True)
97
+ # Gini: sum(p_i*(1-p_i)) => high if spread out
98
+ gini = torch.sum(probs * (1.0 - probs), dim=0) # [N_tgt]
99
+
100
+ threshold = torch.quantile(gini, quantile)
101
+ newness_mask = (gini > threshold).float()
102
+ return newness_mask
103
+
104
+ def detect_newness_kl(distances, temperature=1.0, quantile=0.97):
105
+ """
106
+ KL-based approach. Compare distribution to uniform => if close to uniform => new object.
107
+ 1) Convert distances -> similarities
108
+ 2) p(x) = similarities / sum(similarities)
109
+ 3) KL(p || uniform) => sum p(x) log (p(x)/(1/N_src))
110
+ 4) If p is near uniform => KL small => new object.
111
+ We'll invert it => newness ~ 1/KL.
112
+ """
113
+ similarities = distance_to_similarity(distances, temperature=temperature)
114
+ N_src = distances.shape[0]
115
+ probs = similarities / similarities.sum(dim=0, keepdim=True)
116
+
117
+ uniform_val = 1.0 / float(N_src)
118
+ kl_vals = torch.sum(probs * torch.log(probs / uniform_val), dim=0) # [N_tgt]
119
+ inv_kl = 1.0 / (kl_vals + 1e-8) # big => distribution is near uniform => new
120
+
121
+ threshold = torch.quantile(inv_kl, quantile)
122
+ newness_mask = (inv_kl > threshold).float()
123
+ return newness_mask
124
+
125
+ def detect_newness_variation_ratio(distances, temperature=1.0, quantile=0.97):
126
+ """
127
+ Variation Ratio: 1 - max(prob).
128
+ 1) Convert distance->similarity
129
+ 2) p(x) = sim(x) / sum_x'(sim(x'))
130
+ 3) var_ratio = 1 - max(p)
131
+ High var_ratio => new object.
132
+ """
133
+ similarities = distance_to_similarity(distances, temperature=temperature)
134
+ probs = similarities / similarities.sum(dim=0, keepdim=True)
135
+ max_prob, _ = torch.max(probs, dim=0) # [N_tgt]
136
+ var_ratio = 1.0 - max_prob
137
+
138
+ threshold = torch.quantile(var_ratio, quantile)
139
+ newness_mask = (var_ratio > threshold).float()
140
+ return newness_mask
141
+
142
+
143
+ def detect_newness_two_sided_ratio(
144
+ distances,
145
+ top_k_ratio_quantile=0.03,
146
+ two_sided=True
147
+ ):
148
+ """
149
+ Two-sided matching + ratio test in distance space.
150
+
151
+ Ratio test: For each t, let d0 = best distance, d1 = second best.
152
+ ratio = d0 / (d1 + 1e-8).
153
+ If ratio < ratio_threshold => ambiguous => new.
154
+ (Typically a smaller ratio means a better match, but we invert logic:
155
+ a patch can be "new" if the ratio is extremely small or ambiguous.)
156
+ """
157
+
158
+ N_src, N_tgt = distances.shape
159
+
160
+ # Target → Source: best match
161
+ min_vals_t, best_s_for_t = torch.min(distances, dim=0)
162
+
163
+ # Source → Target: best match
164
+ min_vals_s, best_t_for_s = torch.min(distances, dim=1)
165
+
166
+ # Two-sided consistency check
167
+ twosided_mask = torch.zeros(N_tgt, device=distances.device)
168
+ if two_sided:
169
+ for t in range(N_tgt):
170
+ s = best_s_for_t[t]
171
+ if best_t_for_s[s] != t:
172
+ twosided_mask[t] = 1.0
173
+
174
+ # Ratio test: ambiguous if best match is not clearly better than second best
175
+ sorted_dists, _ = torch.sort(distances, dim=0)
176
+ d0 = sorted_dists[0]
177
+ d1 = sorted_dists[1]
178
+ ratio = d0 / (d1 + 1e-8)
179
+ ratio_threshold = torch.quantile(ratio, top_k_ratio_quantile)
180
+ ratio_mask = (ratio < ratio_threshold).float()
181
+
182
+ # Combine checks (currently using only two-sided result)
183
+ newness_mask = twosided_mask
184
+
185
+ return newness_mask
186
+
187
+
model/modules/register_attention.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from einops import rearrange, repeat
4
+
5
+ from typing import Any
6
+ from model.directional_attentions import DirectionalAttentionControl, AttentionBase
7
+ from utils.utils import find_smallest_key_with_suffix
8
+
9
+
10
+ def register_attention_editor_diffusers(model: Any, editor: AttentionBase):
11
+ def ca_forward(self, place_in_unet):
12
+ def forward(
13
+ x: torch.Tensor,
14
+ encoder_hidden_states: torch.Tensor = None,
15
+ attention_mask: torch.Tensor = None,
16
+ context: torch.Tensor = None,
17
+ mask: torch.Tensor = None
18
+ ):
19
+ if encoder_hidden_states is not None:
20
+ context = encoder_hidden_states
21
+ if attention_mask is not None:
22
+ mask = attention_mask
23
+
24
+ h = self.heads
25
+ is_cross = context is not None
26
+ context = context if is_cross else x
27
+
28
+ q = self.to_q(x)
29
+ k = self.to_k(context)
30
+ v = self.to_v(context)
31
+
32
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
33
+ sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale
34
+
35
+ if mask is not None:
36
+ mask = rearrange(mask, 'b ... -> b (...)')
37
+ max_neg_value = -torch.finfo(sim.dtype).max
38
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
39
+ sim.masked_fill_(~mask, max_neg_value)
40
+
41
+ dift_features_dict = getattr(model.unet.latent_store, 'dift_features', {})
42
+ dift_features_key = find_smallest_key_with_suffix(dift_features_dict, suffix='_1')
43
+ dift_features = dift_features_dict.get(dift_features_key, None)
44
+
45
+ attn = sim.softmax(dim=-1)
46
+ out = editor(
47
+ q, k, v, sim, attn, is_cross, place_in_unet,
48
+ self.heads,
49
+ scale=self.scale,
50
+ dift_features=dift_features
51
+ )
52
+
53
+ to_out = self.to_out
54
+ if isinstance(to_out, nn.modules.container.ModuleList):
55
+ to_out = self.to_out[0]
56
+
57
+ return to_out(out)
58
+ return forward
59
+
60
+ def register_editor(net, count, place_in_unet):
61
+ for name, subnet in net.named_children():
62
+ if net.__class__.__name__ == 'Attention': # spatial Transformer layer
63
+ net.forward = ca_forward(net, place_in_unet)
64
+ return count + 1
65
+ elif hasattr(net, 'children'):
66
+ count = register_editor(subnet, count, place_in_unet)
67
+ return count
68
+
69
+ cross_att_count = 0
70
+ for net_name, net in model.unet.named_children():
71
+ if "down" in net_name:
72
+ cross_att_count += register_editor(net, 0, "down")
73
+ elif "mid" in net_name:
74
+ cross_att_count += register_editor(net, 0, "mid")
75
+ elif "up" in net_name:
76
+ cross_att_count += register_editor(net, 0, "up")
77
+ editor.num_att_layers = cross_att_count
model/pipeline_sdxl.py ADDED
@@ -0,0 +1,1440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified only lines 1360–1370; search for 'changed section' to locate the update easily.
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import PIL.Image
7
+ import torch
8
+ from transformers import (
9
+ CLIPImageProcessor,
10
+ CLIPTextModel,
11
+ CLIPTextModelWithProjection,
12
+ CLIPTokenizer,
13
+ CLIPVisionModelWithProjection,
14
+ )
15
+
16
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
17
+ from diffusers.loaders import (
18
+ FromSingleFileMixin,
19
+ IPAdapterMixin,
20
+ StableDiffusionXLLoraLoaderMixin,
21
+ TextualInversionLoaderMixin,
22
+ )
23
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
24
+ from diffusers.models.attention_processor import (
25
+ AttnProcessor2_0,
26
+ LoRAAttnProcessor2_0,
27
+ LoRAXFormersAttnProcessor,
28
+ XFormersAttnProcessor,
29
+ )
30
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
31
+ from diffusers.schedulers import KarrasDiffusionSchedulers
32
+ from diffusers.utils import (
33
+ USE_PEFT_BACKEND,
34
+ deprecate,
35
+ is_invisible_watermark_available,
36
+ is_torch_xla_available,
37
+ logging,
38
+ replace_example_docstring,
39
+ scale_lora_layers,
40
+ unscale_lora_layers,
41
+ )
42
+ from diffusers.utils.torch_utils import randn_tensor
43
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
44
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
45
+
46
+ from model.modules.dift_utils import gaussian_smooth, gen_nn_map
47
+
48
+
49
+ if is_invisible_watermark_available():
50
+ from .watermark import StableDiffusionXLWatermarker
51
+
52
+ if is_torch_xla_available():
53
+ import torch_xla.core.xla_model as xm
54
+
55
+ XLA_AVAILABLE = True
56
+ else:
57
+ XLA_AVAILABLE = False
58
+
59
+
60
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
61
+
62
+ EXAMPLE_DOC_STRING = """
63
+ Examples:
64
+ ```py
65
+ >>> import torch
66
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
67
+ >>> from diffusers.utils import load_image
68
+
69
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
70
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
71
+ ... )
72
+ >>> pipe = pipe.to("cuda")
73
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
74
+
75
+ >>> init_image = load_image(url).convert("RGB")
76
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
77
+ >>> image = pipe(prompt, image=init_image).images[0]
78
+ ```
79
+ """
80
+
81
+
82
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
83
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
84
+ """
85
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
86
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
87
+ """
88
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
89
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
90
+ # rescale the results from guidance (fixes overexposure)
91
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
92
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
93
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
94
+ return noise_cfg
95
+
96
+
97
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
98
+ def retrieve_latents(
99
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
100
+ ):
101
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
102
+ return encoder_output.latent_dist.sample(generator)
103
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
104
+ return encoder_output.latent_dist.mode()
105
+ elif hasattr(encoder_output, "latents"):
106
+ return encoder_output.latents
107
+ else:
108
+ raise AttributeError("Could not access latents of provided encoder_output")
109
+
110
+
111
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
112
+ def retrieve_timesteps(
113
+ scheduler,
114
+ num_inference_steps: Optional[int] = None,
115
+ device: Optional[Union[str, torch.device]] = None,
116
+ timesteps: Optional[List[int]] = None,
117
+ **kwargs,
118
+ ):
119
+ """
120
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
121
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
122
+
123
+ Args:
124
+ scheduler (`SchedulerMixin`):
125
+ The scheduler to get timesteps from.
126
+ num_inference_steps (`int`):
127
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
128
+ `timesteps` must be `None`.
129
+ device (`str` or `torch.device`, *optional*):
130
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
131
+ timesteps (`List[int]`, *optional*):
132
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
133
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
134
+ must be `None`.
135
+
136
+ Returns:
137
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
138
+ second element is the number of inference steps.
139
+ """
140
+ if timesteps is not None:
141
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
142
+ if not accepts_timesteps:
143
+ raise ValueError(
144
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
145
+ f" timestep schedules. Please check whether you are using the correct scheduler."
146
+ )
147
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
148
+ timesteps = scheduler.timesteps
149
+ num_inference_steps = len(timesteps)
150
+ else:
151
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
152
+ timesteps = scheduler.timesteps
153
+ return timesteps, num_inference_steps
154
+
155
+
156
+ class StableDiffusionXLImg2ImgPipeline(
157
+ DiffusionPipeline,
158
+ StableDiffusionMixin,
159
+ TextualInversionLoaderMixin,
160
+ FromSingleFileMixin,
161
+ StableDiffusionXLLoraLoaderMixin,
162
+ IPAdapterMixin,
163
+ ):
164
+ r"""
165
+ Pipeline for text-to-image generation using Stable Diffusion XL.
166
+
167
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
168
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
169
+
170
+ The pipeline also inherits the following loading methods:
171
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
172
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
173
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
174
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
175
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
176
+
177
+ Args:
178
+ vae ([`AutoencoderKL`]):
179
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
180
+ text_encoder ([`CLIPTextModel`]):
181
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
182
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
183
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
184
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
185
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
186
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
187
+ specifically the
188
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
189
+ variant.
190
+ tokenizer (`CLIPTokenizer`):
191
+ Tokenizer of class
192
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
193
+ tokenizer_2 (`CLIPTokenizer`):
194
+ Second Tokenizer of class
195
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
196
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
197
+ scheduler ([`SchedulerMixin`]):
198
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
199
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
200
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
201
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
202
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
203
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
204
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
205
+ `stabilityai/stable-diffusion-xl-base-1-0`.
206
+ add_watermarker (`bool`, *optional*):
207
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
208
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
209
+ watermarker will be used.
210
+ """
211
+
212
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
213
+ _optional_components = [
214
+ "tokenizer",
215
+ "tokenizer_2",
216
+ "text_encoder",
217
+ "text_encoder_2",
218
+ "image_encoder",
219
+ "feature_extractor",
220
+ ]
221
+ _callback_tensor_inputs = [
222
+ "latents",
223
+ "prompt_embeds",
224
+ "negative_prompt_embeds",
225
+ "add_text_embeds",
226
+ "add_time_ids",
227
+ "negative_pooled_prompt_embeds",
228
+ "add_neg_time_ids",
229
+ ]
230
+
231
+ def __init__(
232
+ self,
233
+ vae: AutoencoderKL,
234
+ text_encoder: CLIPTextModel,
235
+ text_encoder_2: CLIPTextModelWithProjection,
236
+ tokenizer: CLIPTokenizer,
237
+ tokenizer_2: CLIPTokenizer,
238
+ unet: UNet2DConditionModel,
239
+ scheduler: KarrasDiffusionSchedulers,
240
+ image_encoder: CLIPVisionModelWithProjection = None,
241
+ feature_extractor: CLIPImageProcessor = None,
242
+ requires_aesthetics_score: bool = False,
243
+ force_zeros_for_empty_prompt: bool = True,
244
+ add_watermarker: Optional[bool] = None,
245
+ ):
246
+ super().__init__()
247
+
248
+ self.register_modules(
249
+ vae=vae,
250
+ text_encoder=text_encoder,
251
+ text_encoder_2=text_encoder_2,
252
+ tokenizer=tokenizer,
253
+ tokenizer_2=tokenizer_2,
254
+ unet=unet,
255
+ image_encoder=image_encoder,
256
+ feature_extractor=feature_extractor,
257
+ scheduler=scheduler,
258
+ )
259
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
260
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
261
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
262
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
263
+
264
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
265
+
266
+ if add_watermarker:
267
+ self.watermark = StableDiffusionXLWatermarker()
268
+ else:
269
+ self.watermark = None
270
+
271
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
272
+ def encode_prompt(
273
+ self,
274
+ prompt: str,
275
+ prompt_2: Optional[str] = None,
276
+ device: Optional[torch.device] = None,
277
+ num_images_per_prompt: int = 1,
278
+ do_classifier_free_guidance: bool = True,
279
+ negative_prompt: Optional[str] = None,
280
+ negative_prompt_2: Optional[str] = None,
281
+ prompt_embeds: Optional[torch.FloatTensor] = None,
282
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
283
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
284
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
285
+ lora_scale: Optional[float] = None,
286
+ clip_skip: Optional[int] = None,
287
+ ):
288
+ r"""
289
+ Encodes the prompt into text encoder hidden states.
290
+
291
+ Args:
292
+ prompt (`str` or `List[str]`, *optional*):
293
+ prompt to be encoded
294
+ prompt_2 (`str` or `List[str]`, *optional*):
295
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
296
+ used in both text-encoders
297
+ device: (`torch.device`):
298
+ torch device
299
+ num_images_per_prompt (`int`):
300
+ number of images that should be generated per prompt
301
+ do_classifier_free_guidance (`bool`):
302
+ whether to use classifier free guidance or not
303
+ negative_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
305
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
306
+ less than `1`).
307
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
308
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
309
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
310
+ prompt_embeds (`torch.FloatTensor`, *optional*):
311
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
312
+ provided, text embeddings will be generated from `prompt` input argument.
313
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
314
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
315
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
316
+ argument.
317
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
318
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
319
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
320
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
321
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
322
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
323
+ input argument.
324
+ lora_scale (`float`, *optional*):
325
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
326
+ clip_skip (`int`, *optional*):
327
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
328
+ the output of the pre-final layer will be used for computing the prompt embeddings.
329
+ """
330
+ device = device or self._execution_device
331
+
332
+ # set lora scale so that monkey patched LoRA
333
+ # function of text encoder can correctly access it
334
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
335
+ self._lora_scale = lora_scale
336
+
337
+ # dynamically adjust the LoRA scale
338
+ if self.text_encoder is not None:
339
+ if not USE_PEFT_BACKEND:
340
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
341
+ else:
342
+ scale_lora_layers(self.text_encoder, lora_scale)
343
+
344
+ if self.text_encoder_2 is not None:
345
+ if not USE_PEFT_BACKEND:
346
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
347
+ else:
348
+ scale_lora_layers(self.text_encoder_2, lora_scale)
349
+
350
+ prompt = [prompt] if isinstance(prompt, str) else prompt
351
+
352
+ if prompt is not None:
353
+ batch_size = len(prompt)
354
+ else:
355
+ batch_size = prompt_embeds.shape[0]
356
+
357
+ # Define tokenizers and text encoders
358
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
359
+ text_encoders = (
360
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
361
+ )
362
+
363
+ if prompt_embeds is None:
364
+ prompt_2 = prompt_2 or prompt
365
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
366
+
367
+ # textual inversion: process multi-vector tokens if necessary
368
+ prompt_embeds_list = []
369
+ prompts = [prompt, prompt_2]
370
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
371
+ if isinstance(self, TextualInversionLoaderMixin):
372
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
373
+
374
+ text_inputs = tokenizer(
375
+ prompt,
376
+ padding="max_length",
377
+ max_length=tokenizer.model_max_length,
378
+ truncation=True,
379
+ return_tensors="pt",
380
+ )
381
+
382
+ text_input_ids = text_inputs.input_ids
383
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
384
+
385
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
386
+ text_input_ids, untruncated_ids
387
+ ):
388
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
389
+ logger.warning(
390
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
391
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
392
+ )
393
+
394
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
395
+
396
+ # We are only ALWAYS interested in the pooled output of the final text encoder
397
+ pooled_prompt_embeds = prompt_embeds[0]
398
+ if clip_skip is None:
399
+ prompt_embeds = prompt_embeds.hidden_states[-2]
400
+ else:
401
+ # "2" because SDXL always indexes from the penultimate layer.
402
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
403
+
404
+ prompt_embeds_list.append(prompt_embeds)
405
+
406
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
407
+
408
+ # get unconditional embeddings for classifier free guidance
409
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
410
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
411
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
412
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
413
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
414
+ negative_prompt = negative_prompt or ""
415
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
416
+
417
+ # normalize str to list
418
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
419
+ negative_prompt_2 = (
420
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
421
+ )
422
+
423
+ uncond_tokens: List[str]
424
+ if prompt is not None and type(prompt) is not type(negative_prompt):
425
+ raise TypeError(
426
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
427
+ f" {type(prompt)}."
428
+ )
429
+ elif batch_size != len(negative_prompt):
430
+ raise ValueError(
431
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
432
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
433
+ " the batch size of `prompt`."
434
+ )
435
+ else:
436
+ uncond_tokens = [negative_prompt, negative_prompt_2]
437
+
438
+ negative_prompt_embeds_list = []
439
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
440
+ if isinstance(self, TextualInversionLoaderMixin):
441
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
442
+
443
+ max_length = prompt_embeds.shape[1]
444
+ uncond_input = tokenizer(
445
+ negative_prompt,
446
+ padding="max_length",
447
+ max_length=max_length,
448
+ truncation=True,
449
+ return_tensors="pt",
450
+ )
451
+
452
+ negative_prompt_embeds = text_encoder(
453
+ uncond_input.input_ids.to(device),
454
+ output_hidden_states=True,
455
+ )
456
+ # We are only ALWAYS interested in the pooled output of the final text encoder
457
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
458
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
459
+
460
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
461
+
462
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
463
+
464
+ if self.text_encoder_2 is not None:
465
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
466
+ else:
467
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
468
+
469
+ bs_embed, seq_len, _ = prompt_embeds.shape
470
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
471
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
472
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
473
+
474
+ if do_classifier_free_guidance:
475
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
476
+ seq_len = negative_prompt_embeds.shape[1]
477
+
478
+ if self.text_encoder_2 is not None:
479
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
480
+ else:
481
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
482
+
483
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
484
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
485
+
486
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
487
+ bs_embed * num_images_per_prompt, -1
488
+ )
489
+ if do_classifier_free_guidance:
490
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
491
+ bs_embed * num_images_per_prompt, -1
492
+ )
493
+
494
+ if self.text_encoder is not None:
495
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
496
+ # Retrieve the original scale by scaling back the LoRA layers
497
+ unscale_lora_layers(self.text_encoder, lora_scale)
498
+
499
+ if self.text_encoder_2 is not None:
500
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
501
+ # Retrieve the original scale by scaling back the LoRA layers
502
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
503
+
504
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
505
+
506
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
507
+ def prepare_extra_step_kwargs(self, generator, eta):
508
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
509
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
510
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
511
+ # and should be between [0, 1]
512
+
513
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
514
+ extra_step_kwargs = {}
515
+ if accepts_eta:
516
+ extra_step_kwargs["eta"] = eta
517
+
518
+ # check if the scheduler accepts generator
519
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
520
+ if accepts_generator:
521
+ extra_step_kwargs["generator"] = generator
522
+ return extra_step_kwargs
523
+
524
+ def check_inputs(
525
+ self,
526
+ prompt,
527
+ prompt_2,
528
+ strength,
529
+ num_inference_steps,
530
+ callback_steps,
531
+ negative_prompt=None,
532
+ negative_prompt_2=None,
533
+ prompt_embeds=None,
534
+ negative_prompt_embeds=None,
535
+ ip_adapter_image=None,
536
+ ip_adapter_image_embeds=None,
537
+ callback_on_step_end_tensor_inputs=None,
538
+ ):
539
+ if strength < 0 or strength > 1:
540
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
541
+ if num_inference_steps is None:
542
+ raise ValueError("`num_inference_steps` cannot be None.")
543
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
544
+ raise ValueError(
545
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
546
+ f" {type(num_inference_steps)}."
547
+ )
548
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
549
+ raise ValueError(
550
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
551
+ f" {type(callback_steps)}."
552
+ )
553
+
554
+ if callback_on_step_end_tensor_inputs is not None and not all(
555
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
556
+ ):
557
+ raise ValueError(
558
+ 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]}"
559
+ )
560
+
561
+ if prompt is not None and prompt_embeds is not None:
562
+ raise ValueError(
563
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
564
+ " only forward one of the two."
565
+ )
566
+ elif prompt_2 is not None and prompt_embeds is not None:
567
+ raise ValueError(
568
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
569
+ " only forward one of the two."
570
+ )
571
+ elif prompt is None and prompt_embeds is None:
572
+ raise ValueError(
573
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
574
+ )
575
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
576
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
577
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
578
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
579
+
580
+ if negative_prompt is not None and negative_prompt_embeds is not None:
581
+ raise ValueError(
582
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
583
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
584
+ )
585
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
586
+ raise ValueError(
587
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
588
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
589
+ )
590
+
591
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
592
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
593
+ raise ValueError(
594
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
595
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
596
+ f" {negative_prompt_embeds.shape}."
597
+ )
598
+
599
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
600
+ raise ValueError(
601
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
602
+ )
603
+
604
+ if ip_adapter_image_embeds is not None:
605
+ if not isinstance(ip_adapter_image_embeds, list):
606
+ raise ValueError(
607
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
608
+ )
609
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
610
+ raise ValueError(
611
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
612
+ )
613
+
614
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
615
+ # get the original timestep using init_timestep
616
+ if denoising_start is None:
617
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
618
+ t_start = max(num_inference_steps - init_timestep, 0)
619
+ else:
620
+ t_start = 0
621
+
622
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
623
+
624
+ # Strength is irrelevant if we directly request a timestep to start at;
625
+ # that is, strength is determined by the denoising_start instead.
626
+ if denoising_start is not None:
627
+ discrete_timestep_cutoff = int(
628
+ round(
629
+ self.scheduler.config.num_train_timesteps
630
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
631
+ )
632
+ )
633
+
634
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
635
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
636
+ # if the scheduler is a 2nd order scheduler we might have to do +1
637
+ # because `num_inference_steps` might be even given that every timestep
638
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
639
+ # mean that we cut the timesteps in the middle of the denoising step
640
+ # (between 1st and 2nd devirative) which leads to incorrect results. By adding 1
641
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
642
+ num_inference_steps = num_inference_steps + 1
643
+
644
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
645
+ timesteps = timesteps[-num_inference_steps:]
646
+ return timesteps, num_inference_steps
647
+
648
+ return timesteps, num_inference_steps - t_start
649
+
650
+ def prepare_latents(
651
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
652
+ ):
653
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
654
+ raise ValueError(
655
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
656
+ )
657
+
658
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
659
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
660
+ self.text_encoder_2.to("cpu")
661
+ torch.cuda.empty_cache()
662
+
663
+ image = image.to(device=device, dtype=dtype)
664
+
665
+ batch_size = batch_size * num_images_per_prompt
666
+
667
+ if image.shape[1] == 4:
668
+ init_latents = image
669
+
670
+ else:
671
+ # make sure the VAE is in float32 mode, as it overflows in float16
672
+ if self.vae.config.force_upcast:
673
+ image = image.float()
674
+ self.vae.to(dtype=torch.float32)
675
+
676
+ if isinstance(generator, list) and len(generator) != batch_size:
677
+ raise ValueError(
678
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
679
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
680
+ )
681
+
682
+ elif isinstance(generator, list):
683
+ init_latents = [
684
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
685
+ for i in range(batch_size)
686
+ ]
687
+ init_latents = torch.cat(init_latents, dim=0)
688
+ else:
689
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
690
+
691
+ if self.vae.config.force_upcast:
692
+ self.vae.to(dtype)
693
+
694
+ init_latents = init_latents.to(dtype)
695
+ init_latents = self.vae.config.scaling_factor * init_latents
696
+
697
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
698
+ # expand init_latents for batch_size
699
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
700
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
701
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
702
+ raise ValueError(
703
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
704
+ )
705
+ else:
706
+ init_latents = torch.cat([init_latents], dim=0)
707
+
708
+ if add_noise:
709
+ shape = init_latents.shape
710
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
711
+ # get latents
712
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
713
+
714
+ latents = init_latents
715
+
716
+ return latents
717
+
718
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
719
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
720
+ dtype = next(self.image_encoder.parameters()).dtype
721
+
722
+ if not isinstance(image, torch.Tensor):
723
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
724
+
725
+ image = image.to(device=device, dtype=dtype)
726
+ if output_hidden_states:
727
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
728
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
729
+ uncond_image_enc_hidden_states = self.image_encoder(
730
+ torch.zeros_like(image), output_hidden_states=True
731
+ ).hidden_states[-2]
732
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
733
+ num_images_per_prompt, dim=0
734
+ )
735
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
736
+ else:
737
+ image_embeds = self.image_encoder(image).image_embeds
738
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
739
+ uncond_image_embeds = torch.zeros_like(image_embeds)
740
+
741
+ return image_embeds, uncond_image_embeds
742
+
743
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
744
+ def prepare_ip_adapter_image_embeds(
745
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
746
+ ):
747
+ if ip_adapter_image_embeds is None:
748
+ if not isinstance(ip_adapter_image, list):
749
+ ip_adapter_image = [ip_adapter_image]
750
+
751
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
752
+ raise ValueError(
753
+ 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."
754
+ )
755
+
756
+ image_embeds = []
757
+ for single_ip_adapter_image, image_proj_layer in zip(
758
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
759
+ ):
760
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
761
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
762
+ single_ip_adapter_image, device, 1, output_hidden_state
763
+ )
764
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
765
+ single_negative_image_embeds = torch.stack(
766
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
767
+ )
768
+
769
+ if do_classifier_free_guidance:
770
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
771
+ single_image_embeds = single_image_embeds.to(device)
772
+
773
+ image_embeds.append(single_image_embeds)
774
+ else:
775
+ repeat_dims = [1]
776
+ image_embeds = []
777
+ for single_image_embeds in ip_adapter_image_embeds:
778
+ if do_classifier_free_guidance:
779
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
780
+ single_image_embeds = single_image_embeds.repeat(
781
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
782
+ )
783
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
784
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
785
+ )
786
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
787
+ else:
788
+ single_image_embeds = single_image_embeds.repeat(
789
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
790
+ )
791
+ image_embeds.append(single_image_embeds)
792
+
793
+ return image_embeds
794
+
795
+ def _get_add_time_ids(
796
+ self,
797
+ original_size,
798
+ crops_coords_top_left,
799
+ target_size,
800
+ aesthetic_score,
801
+ negative_aesthetic_score,
802
+ negative_original_size,
803
+ negative_crops_coords_top_left,
804
+ negative_target_size,
805
+ dtype,
806
+ text_encoder_projection_dim=None,
807
+ ):
808
+ if self.config.requires_aesthetics_score:
809
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
810
+ add_neg_time_ids = list(
811
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
812
+ )
813
+ else:
814
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
815
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
816
+
817
+ passed_add_embed_dim = (
818
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
819
+ )
820
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
821
+
822
+ if (
823
+ expected_add_embed_dim > passed_add_embed_dim
824
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
825
+ ):
826
+ raise ValueError(
827
+ 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."
828
+ )
829
+ elif (
830
+ expected_add_embed_dim < passed_add_embed_dim
831
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
832
+ ):
833
+ raise ValueError(
834
+ 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."
835
+ )
836
+ elif expected_add_embed_dim != passed_add_embed_dim:
837
+ raise ValueError(
838
+ 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`."
839
+ )
840
+
841
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
842
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
843
+
844
+ return add_time_ids, add_neg_time_ids
845
+
846
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
847
+ def upcast_vae(self):
848
+ dtype = self.vae.dtype
849
+ self.vae.to(dtype=torch.float32)
850
+ use_torch_2_0_or_xformers = isinstance(
851
+ self.vae.decoder.mid_block.attentions[0].processor,
852
+ (
853
+ AttnProcessor2_0,
854
+ XFormersAttnProcessor,
855
+ LoRAXFormersAttnProcessor,
856
+ LoRAAttnProcessor2_0,
857
+ ),
858
+ )
859
+ # if xformers or torch_2_0 is used attention block does not need
860
+ # to be in float32 which can save lots of memory
861
+ if use_torch_2_0_or_xformers:
862
+ self.vae.post_quant_conv.to(dtype)
863
+ self.vae.decoder.conv_in.to(dtype)
864
+ self.vae.decoder.mid_block.to(dtype)
865
+
866
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
867
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
868
+ """
869
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
870
+
871
+ Args:
872
+ timesteps (`torch.Tensor`):
873
+ generate embedding vectors at these timesteps
874
+ embedding_dim (`int`, *optional*, defaults to 512):
875
+ dimension of the embeddings to generate
876
+ dtype:
877
+ data type of the generated embeddings
878
+
879
+ Returns:
880
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
881
+ """
882
+ assert len(w.shape) == 1
883
+ w = w * 1000.0
884
+
885
+ half_dim = embedding_dim // 2
886
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
887
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
888
+ emb = w.to(dtype)[:, None] * emb[None, :]
889
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
890
+ if embedding_dim % 2 == 1: # zero pad
891
+ emb = torch.nn.functional.pad(emb, (0, 1))
892
+ assert emb.shape == (w.shape[0], embedding_dim)
893
+ return emb
894
+
895
+ @property
896
+ def guidance_scale(self):
897
+ return self._guidance_scale
898
+
899
+ @property
900
+ def guidance_rescale(self):
901
+ return self._guidance_rescale
902
+
903
+ @property
904
+ def clip_skip(self):
905
+ return self._clip_skip
906
+
907
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
908
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
909
+ # corresponds to doing no classifier free guidance.
910
+ @property
911
+ def do_classifier_free_guidance(self):
912
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
913
+
914
+ @property
915
+ def cross_attention_kwargs(self):
916
+ return self._cross_attention_kwargs
917
+
918
+ @property
919
+ def denoising_end(self):
920
+ return self._denoising_end
921
+
922
+ @property
923
+ def denoising_start(self):
924
+ return self._denoising_start
925
+
926
+ @property
927
+ def num_timesteps(self):
928
+ return self._num_timesteps
929
+
930
+ @property
931
+ def interrupt(self):
932
+ return self._interrupt
933
+
934
+ @torch.no_grad()
935
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
936
+ def __call__(
937
+ self,
938
+ prompt: Union[str, List[str]] = None,
939
+ prompt_2: Optional[Union[str, List[str]]] = None,
940
+ image: PipelineImageInput = None,
941
+ strength: float = 0.3,
942
+ num_inference_steps: int = 50,
943
+ timesteps: List[int] = None,
944
+ denoising_start: Optional[float] = None,
945
+ denoising_end: Optional[float] = None,
946
+ guidance_scale: float = 5.0,
947
+ negative_prompt: Optional[Union[str, List[str]]] = None,
948
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
949
+ num_images_per_prompt: Optional[int] = 1,
950
+ eta: float = 0.0,
951
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
952
+ latents: Optional[torch.FloatTensor] = None,
953
+ prompt_embeds: Optional[torch.FloatTensor] = None,
954
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
955
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
956
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
957
+ ip_adapter_image: Optional[PipelineImageInput] = None,
958
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
959
+ output_type: Optional[str] = "pil",
960
+ return_dict: bool = True,
961
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
962
+ guidance_rescale: float = 0.0,
963
+ original_size: Tuple[int, int] = None,
964
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
965
+ target_size: Tuple[int, int] = None,
966
+ negative_original_size: Optional[Tuple[int, int]] = None,
967
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
968
+ negative_target_size: Optional[Tuple[int, int]] = None,
969
+ aesthetic_score: float = 6.0,
970
+ negative_aesthetic_score: float = 2.5,
971
+ clip_skip: Optional[int] = None,
972
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
973
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
974
+ **kwargs,
975
+ ):
976
+ r"""
977
+ Function invoked when calling the pipeline for generation.
978
+
979
+ Args:
980
+ prompt (`str` or `List[str]`, *optional*):
981
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
982
+ instead.
983
+ prompt_2 (`str` or `List[str]`, *optional*):
984
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
985
+ used in both text-encoders
986
+ image (`torch.FloatTensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.FloatTensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
987
+ The image(s) to modify with the pipeline.
988
+ strength (`float`, *optional*, defaults to 0.3):
989
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
990
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
991
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
992
+ be maximum and the denoising process will run for the full number of iterations specified in
993
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
994
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
995
+ num_inference_steps (`int`, *optional*, defaults to 50):
996
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
997
+ expense of slower inference.
998
+ timesteps (`List[int]`, *optional*):
999
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1000
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1001
+ passed will be used. Must be in descending order.
1002
+ denoising_start (`float`, *optional*):
1003
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1004
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1005
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1006
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1007
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
1008
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1009
+ denoising_end (`float`, *optional*):
1010
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1011
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1012
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1013
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1014
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1015
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refine Image
1016
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1017
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1018
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1019
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1020
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1021
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1022
+ usually at the expense of lower image quality.
1023
+ negative_prompt (`str` or `List[str]`, *optional*):
1024
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1025
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1026
+ less than `1`).
1027
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1028
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1029
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1030
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1031
+ The number of images to generate per prompt.
1032
+ eta (`float`, *optional*, defaults to 0.0):
1033
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1034
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1035
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1036
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1037
+ to make generation deterministic.
1038
+ latents (`torch.FloatTensor`, *optional*):
1039
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1040
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1041
+ tensor will ge generated by sampling using the supplied random `generator`.
1042
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1043
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1044
+ provided, text embeddings will be generated from `prompt` input argument.
1045
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1046
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1047
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1048
+ argument.
1049
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1050
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1051
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1052
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1053
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1054
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1055
+ input argument.
1056
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1057
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
1058
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
1059
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
1060
+ if `do_classifier_free_guidance` is set to `True`.
1061
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
1062
+ output_type (`str`, *optional*, defaults to `"pil"`):
1063
+ The output format of the generate image. Choose between
1064
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1065
+ return_dict (`bool`, *optional*, defaults to `True`):
1066
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1067
+ plain tuple.
1068
+ cross_attention_kwargs (`dict`, *optional*):
1069
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1070
+ `self.processor` in
1071
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1072
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1073
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1074
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1075
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1076
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1077
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1078
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1079
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1080
+ explained in section 2.2 of
1081
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1082
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1083
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1084
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1085
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1086
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1087
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1088
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1089
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1090
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1091
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1092
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1093
+ micro-conditioning as explained in section 2.2 of
1094
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1095
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1096
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1097
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1098
+ micro-conditioning as explained in section 2.2 of
1099
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1100
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1101
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1102
+ To negatively condition the generation process based on a target image resolution. It should be as same
1103
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1104
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1105
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1106
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1107
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1108
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1109
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1110
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1111
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1112
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1113
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1114
+ clip_skip (`int`, *optional*):
1115
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1116
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1117
+ callback_on_step_end (`Callable`, *optional*):
1118
+ A function that calls at the end of each denoising steps during the inference. The function is called
1119
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1120
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1121
+ `callback_on_step_end_tensor_inputs`.
1122
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1123
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1124
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1125
+ `._callback_tensor_inputs` attribute of your pipeline class.
1126
+
1127
+ Examples:
1128
+
1129
+ Returns:
1130
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1131
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1132
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1133
+ """
1134
+
1135
+ callback = kwargs.pop("callback", None)
1136
+ callback_steps = kwargs.pop("callback_steps", None)
1137
+
1138
+ if callback is not None:
1139
+ deprecate(
1140
+ "callback",
1141
+ "1.0.0",
1142
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1143
+ )
1144
+ if callback_steps is not None:
1145
+ deprecate(
1146
+ "callback_steps",
1147
+ "1.0.0",
1148
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1149
+ )
1150
+
1151
+ # 1. Check inputs. Raise error if not correct
1152
+ self.check_inputs(
1153
+ prompt,
1154
+ prompt_2,
1155
+ strength,
1156
+ num_inference_steps,
1157
+ callback_steps,
1158
+ negative_prompt,
1159
+ negative_prompt_2,
1160
+ prompt_embeds,
1161
+ negative_prompt_embeds,
1162
+ ip_adapter_image,
1163
+ ip_adapter_image_embeds,
1164
+ callback_on_step_end_tensor_inputs,
1165
+ )
1166
+
1167
+ self._guidance_scale = guidance_scale
1168
+ self._guidance_rescale = guidance_rescale
1169
+ self._clip_skip = clip_skip
1170
+ self._cross_attention_kwargs = cross_attention_kwargs
1171
+ self._denoising_end = denoising_end
1172
+ self._denoising_start = denoising_start
1173
+ self._interrupt = False
1174
+ # 2. Define call parameters
1175
+ if prompt is not None and isinstance(prompt, str):
1176
+ batch_size = 1
1177
+ elif prompt is not None and isinstance(prompt, list):
1178
+ batch_size = len(prompt)
1179
+ else:
1180
+ batch_size = prompt_embeds.shape[0]
1181
+
1182
+ device = self._execution_device
1183
+
1184
+ # 3. Encode input prompt
1185
+ text_encoder_lora_scale = (
1186
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1187
+ )
1188
+ (
1189
+ prompt_embeds,
1190
+ negative_prompt_embeds,
1191
+ pooled_prompt_embeds,
1192
+ negative_pooled_prompt_embeds,
1193
+ ) = self.encode_prompt(
1194
+ prompt=prompt,
1195
+ prompt_2=prompt_2,
1196
+ device=device,
1197
+ num_images_per_prompt=num_images_per_prompt,
1198
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1199
+ negative_prompt=negative_prompt,
1200
+ negative_prompt_2=negative_prompt_2,
1201
+ prompt_embeds=prompt_embeds,
1202
+ negative_prompt_embeds=negative_prompt_embeds,
1203
+ pooled_prompt_embeds=pooled_prompt_embeds,
1204
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1205
+ lora_scale=text_encoder_lora_scale,
1206
+ clip_skip=self.clip_skip,
1207
+ )
1208
+ # 4. Preprocess image
1209
+ image = self.image_processor.preprocess(image)
1210
+
1211
+ # 5. Prepare timesteps
1212
+ def denoising_value_valid(dnv):
1213
+ return isinstance(dnv, float) and 0 < dnv < 1
1214
+
1215
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1216
+ timesteps, num_inference_steps = self.get_timesteps(
1217
+ num_inference_steps,
1218
+ strength,
1219
+ device,
1220
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1221
+ )
1222
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1223
+
1224
+ add_noise = True if self.denoising_start is None else False
1225
+ # 6. Prepare latent variables
1226
+ latents = self.prepare_latents(
1227
+ image,
1228
+ latent_timestep,
1229
+ batch_size,
1230
+ num_images_per_prompt,
1231
+ prompt_embeds.dtype,
1232
+ device,
1233
+ generator,
1234
+ add_noise,
1235
+ )
1236
+ # 7. Prepare extra step kwargs.
1237
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1238
+
1239
+ height, width = latents.shape[-2:]
1240
+ height = height * self.vae_scale_factor
1241
+ width = width * self.vae_scale_factor
1242
+
1243
+ original_size = original_size or (height, width)
1244
+ target_size = target_size or (height, width)
1245
+
1246
+ # 8. Prepare added time ids & embeddings
1247
+ if negative_original_size is None:
1248
+ negative_original_size = original_size
1249
+ if negative_target_size is None:
1250
+ negative_target_size = target_size
1251
+
1252
+ add_text_embeds = pooled_prompt_embeds
1253
+ if self.text_encoder_2 is None:
1254
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1255
+ else:
1256
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1257
+
1258
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1259
+ original_size,
1260
+ crops_coords_top_left,
1261
+ target_size,
1262
+ aesthetic_score,
1263
+ negative_aesthetic_score,
1264
+ negative_original_size,
1265
+ negative_crops_coords_top_left,
1266
+ negative_target_size,
1267
+ dtype=prompt_embeds.dtype,
1268
+ text_encoder_projection_dim=text_encoder_projection_dim,
1269
+ )
1270
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1271
+
1272
+ if self.do_classifier_free_guidance:
1273
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1274
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1275
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1276
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1277
+
1278
+ prompt_embeds = prompt_embeds.to(device)
1279
+ add_text_embeds = add_text_embeds.to(device)
1280
+ add_time_ids = add_time_ids.to(device)
1281
+
1282
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1283
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1284
+ ip_adapter_image,
1285
+ ip_adapter_image_embeds,
1286
+ device,
1287
+ batch_size * num_images_per_prompt,
1288
+ self.do_classifier_free_guidance,
1289
+ )
1290
+
1291
+ # 9. Denoising loop
1292
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1293
+
1294
+ # 9.1 Apply denoising_end
1295
+ if (
1296
+ self.denoising_end is not None
1297
+ and self.denoising_start is not None
1298
+ and denoising_value_valid(self.denoising_end)
1299
+ and denoising_value_valid(self.denoising_start)
1300
+ and self.denoising_start >= self.denoising_end
1301
+ ):
1302
+ raise ValueError(
1303
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1304
+ + f" {self.denoising_end} when using type float."
1305
+ )
1306
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1307
+ discrete_timestep_cutoff = int(
1308
+ round(
1309
+ self.scheduler.config.num_train_timesteps
1310
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1311
+ )
1312
+ )
1313
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1314
+ timesteps = timesteps[:num_inference_steps]
1315
+
1316
+ # 9.2 Optionally get Guidance Scale Embedding
1317
+ timestep_cond = None
1318
+ if self.unet.config.time_cond_proj_dim is not None:
1319
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1320
+ timestep_cond = self.get_guidance_scale_embedding(
1321
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1322
+ ).to(device=device, dtype=latents.dtype)
1323
+
1324
+ self._num_timesteps = len(timesteps)
1325
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1326
+ for i, t in enumerate(timesteps):
1327
+ if self.interrupt:
1328
+ continue
1329
+
1330
+ # expand the latents if we are doing classifier free guidance
1331
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1332
+
1333
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1334
+
1335
+ # predict the noise residual
1336
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1337
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1338
+ added_cond_kwargs["image_embeds"] = image_embeds
1339
+ noise_pred = self.unet(
1340
+ latent_model_input,
1341
+ t,
1342
+ encoder_hidden_states=prompt_embeds,
1343
+ timestep_cond=timestep_cond,
1344
+ cross_attention_kwargs=self.cross_attention_kwargs,
1345
+ added_cond_kwargs=added_cond_kwargs,
1346
+ return_dict=False,
1347
+ )[0]
1348
+
1349
+ # perform guidance
1350
+ if self.do_classifier_free_guidance:
1351
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1352
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1353
+
1354
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1355
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1356
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1357
+
1358
+ # compute the previous noisy sample x_t -> x_t-1
1359
+
1360
+ ########################## changed section ##########################
1361
+ # dift_features = self.unet.latent_store.dift_features[f'{t.item()}_0']
1362
+ dift_features = self.unet.latent_store.smoothed_dift_features[f'{t.item()}_1']
1363
+
1364
+
1365
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs,
1366
+ noise_pred_uncond= noise_pred_uncond if self.do_classifier_free_guidance else noise_pred,
1367
+ dift_features=dift_features,
1368
+ return_dict=False)[0]
1369
+ #####################################################################
1370
+
1371
+ if callback_on_step_end is not None:
1372
+ callback_kwargs = {}
1373
+ for k in callback_on_step_end_tensor_inputs:
1374
+ callback_kwargs[k] = locals()[k]
1375
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1376
+
1377
+ latents = callback_outputs.pop("latents", latents)
1378
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1379
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1380
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1381
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1382
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1383
+ )
1384
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1385
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1386
+
1387
+ # call the callback, if provided
1388
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1389
+ progress_bar.update()
1390
+ if callback is not None and i % callback_steps == 0:
1391
+ step_idx = i // getattr(self.scheduler, "order", 1)
1392
+ callback(step_idx, t, latents)
1393
+
1394
+ if XLA_AVAILABLE:
1395
+ xm.mark_step()
1396
+
1397
+ if not output_type == "latent":
1398
+ # make sure the VAE is in float32 mode, as it overflows in float16
1399
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1400
+
1401
+ if needs_upcasting:
1402
+ self.upcast_vae()
1403
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1404
+
1405
+ # unscale/denormalize the latents
1406
+ # denormalize with the mean and std if available and not None
1407
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1408
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1409
+ if has_latents_mean and has_latents_std:
1410
+ latents_mean = (
1411
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1412
+ )
1413
+ latents_std = (
1414
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1415
+ )
1416
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1417
+ else:
1418
+ latents = latents / self.vae.config.scaling_factor
1419
+
1420
+ image = self.vae.decode(latents, return_dict=False)[0]
1421
+
1422
+ # cast back to fp16 if needed
1423
+ if needs_upcasting:
1424
+ self.vae.to(dtype=torch.float16)
1425
+ else:
1426
+ image = latents
1427
+
1428
+ # apply watermark if available
1429
+ if self.watermark is not None:
1430
+ image = self.watermark.apply_watermark(image)
1431
+
1432
+ image = self.image_processor.postprocess(image, output_type=output_type)
1433
+
1434
+ # Offload all models
1435
+ self.maybe_free_model_hooks()
1436
+
1437
+ if not return_dict:
1438
+ return (image,)
1439
+
1440
+ return StableDiffusionXLPipelineOutput(images=image)
model/unet_sdxl.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified only lines 360–365; search for 'changed section' to locate the update easily.
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.utils.checkpoint
9
+
10
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
11
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
12
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
13
+ from diffusers.models.activations import get_activation
14
+ from diffusers.models.attention_processor import (
15
+ ADDED_KV_ATTENTION_PROCESSORS,
16
+ CROSS_ATTENTION_PROCESSORS,
17
+ Attention,
18
+ AttentionProcessor,
19
+ AttnAddedKVProcessor,
20
+ AttnProcessor,
21
+ )
22
+ from diffusers.models.embeddings import (
23
+ GaussianFourierProjection,
24
+ GLIGENTextBoundingboxProjection,
25
+ ImageHintTimeEmbedding,
26
+ ImageProjection,
27
+ ImageTimeEmbedding,
28
+ TextImageProjection,
29
+ TextImageTimeEmbedding,
30
+ TextTimeEmbedding,
31
+ TimestepEmbedding,
32
+ Timesteps,
33
+ )
34
+ from diffusers.models.modeling_utils import ModelMixin
35
+ from diffusers.models.unets.unet_2d_blocks import (
36
+ get_down_block,
37
+ get_mid_block,
38
+ get_up_block,
39
+ )
40
+
41
+ from diffusers.models.unets import UNet2DConditionModel
42
+ from model.modules.dift_utils import DIFTLatentStore
43
+
44
+
45
+ @dataclass
46
+ class UNet2DConditionOutput(BaseOutput):
47
+ sample: torch.FloatTensor = None
48
+
49
+ class OursUNet2DConditionModel(UNet2DConditionModel):
50
+ _supports_gradient_checkpointing = True
51
+
52
+ @register_to_config
53
+ def __init__(
54
+ self,
55
+ sample_size: Optional[int] = None,
56
+ in_channels: int = 4,
57
+ out_channels: int = 4,
58
+ center_input_sample: bool = False,
59
+ flip_sin_to_cos: bool = True,
60
+ freq_shift: int = 0,
61
+ down_block_types: Tuple[str] = (
62
+ "CrossAttnDownBlock2D",
63
+ "CrossAttnDownBlock2D",
64
+ "CrossAttnDownBlock2D",
65
+ "DownBlock2D",
66
+ ),
67
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
68
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
69
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
70
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
71
+ layers_per_block: Union[int, Tuple[int]] = 2,
72
+ downsample_padding: int = 1,
73
+ mid_block_scale_factor: float = 1,
74
+ dropout: float = 0.0,
75
+ act_fn: str = "silu",
76
+ norm_num_groups: Optional[int] = 32,
77
+ norm_eps: float = 1e-5,
78
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
79
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
80
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
81
+ encoder_hid_dim: Optional[int] = None,
82
+ encoder_hid_dim_type: Optional[str] = None,
83
+ attention_head_dim: Union[int, Tuple[int]] = 8,
84
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
85
+ dual_cross_attention: bool = False,
86
+ use_linear_projection: bool = False,
87
+ class_embed_type: Optional[str] = None,
88
+ addition_embed_type: Optional[str] = None,
89
+ addition_time_embed_dim: Optional[int] = None,
90
+ num_class_embeds: Optional[int] = None,
91
+ upcast_attention: bool = False,
92
+ resnet_time_scale_shift: str = "default",
93
+ resnet_skip_time_act: bool = False,
94
+ resnet_out_scale_factor: float = 1.0,
95
+ time_embedding_type: str = "positional",
96
+ time_embedding_dim: Optional[int] = None,
97
+ time_embedding_act_fn: Optional[str] = None,
98
+ timestep_post_act: Optional[str] = None,
99
+ time_cond_proj_dim: Optional[int] = None,
100
+ conv_in_kernel: int = 3,
101
+ conv_out_kernel: int = 3,
102
+ projection_class_embeddings_input_dim: Optional[int] = None,
103
+ attention_type: str = "default",
104
+ class_embeddings_concat: bool = False,
105
+ mid_block_only_cross_attention: Optional[bool] = None,
106
+ cross_attention_norm: Optional[str] = None,
107
+ addition_embed_type_num_heads: int = 64,
108
+ steps: List[int] = list(range(1, 1000)),
109
+ ):
110
+ super().__init__(
111
+ sample_size=sample_size,
112
+ in_channels=in_channels,
113
+ out_channels=out_channels,
114
+ center_input_sample=center_input_sample,
115
+ flip_sin_to_cos=flip_sin_to_cos,
116
+ freq_shift=freq_shift,
117
+ down_block_types=down_block_types,
118
+ mid_block_type=mid_block_type,
119
+ up_block_types=up_block_types,
120
+ only_cross_attention=only_cross_attention,
121
+ block_out_channels=block_out_channels,
122
+ layers_per_block=layers_per_block,
123
+ downsample_padding=downsample_padding,
124
+ mid_block_scale_factor=mid_block_scale_factor,
125
+ dropout=dropout,
126
+ act_fn=act_fn,
127
+ norm_num_groups=norm_num_groups,
128
+ norm_eps=norm_eps,
129
+ cross_attention_dim=cross_attention_dim,
130
+ transformer_layers_per_block=transformer_layers_per_block,
131
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
132
+ encoder_hid_dim=encoder_hid_dim,
133
+ encoder_hid_dim_type=encoder_hid_dim_type,
134
+ attention_head_dim=attention_head_dim,
135
+ num_attention_heads=num_attention_heads,
136
+ dual_cross_attention=dual_cross_attention,
137
+ use_linear_projection=use_linear_projection,
138
+ class_embed_type=class_embed_type,
139
+ addition_embed_type=addition_embed_type,
140
+ addition_time_embed_dim=addition_time_embed_dim,
141
+ num_class_embeds=num_class_embeds,
142
+ upcast_attention=upcast_attention,
143
+ resnet_time_scale_shift=resnet_time_scale_shift,
144
+ resnet_skip_time_act=resnet_skip_time_act,
145
+ resnet_out_scale_factor=resnet_out_scale_factor,
146
+ time_embedding_type=time_embedding_type,
147
+ time_embedding_dim=time_embedding_dim,
148
+ time_embedding_act_fn=time_embedding_act_fn,
149
+ timestep_post_act=timestep_post_act,
150
+ time_cond_proj_dim=time_cond_proj_dim,
151
+ conv_in_kernel=conv_in_kernel,
152
+ conv_out_kernel=conv_out_kernel,
153
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
154
+ attention_type=attention_type,
155
+ class_embeddings_concat=class_embeddings_concat,
156
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
157
+ cross_attention_norm=cross_attention_norm,
158
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
159
+ )
160
+
161
+ self.latent_store = DIFTLatentStore(steps=steps, up_ft_indices=[0, 1, 2])
162
+
163
+ def forward(
164
+ self,
165
+ sample: torch.FloatTensor,
166
+ timestep: Union[torch.Tensor, float, int],
167
+ encoder_hidden_states: torch.Tensor,
168
+ class_labels: Optional[torch.Tensor] = None,
169
+ timestep_cond: Optional[torch.Tensor] = None,
170
+ attention_mask: Optional[torch.Tensor] = None,
171
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
172
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
173
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
174
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
175
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
176
+ encoder_attention_mask: Optional[torch.Tensor] = None,
177
+ return_dict: bool = True,
178
+ ) -> Union[UNet2DConditionOutput, Tuple]:
179
+ default_overall_up_factor = 2**self.num_upsamplers
180
+
181
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
182
+ forward_upsample_size = False
183
+ upsample_size = None
184
+
185
+ for dim in sample.shape[-2:]:
186
+ if dim % default_overall_up_factor != 0:
187
+ # Forward upsample size to force interpolation output size.
188
+ forward_upsample_size = True
189
+ break
190
+
191
+ if attention_mask is not None:
192
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
193
+ attention_mask = attention_mask.unsqueeze(1)
194
+
195
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
196
+ if encoder_attention_mask is not None:
197
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
198
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
199
+
200
+ # 0. center input if necessary
201
+ if self.config.center_input_sample:
202
+ sample = 2 * sample - 1.0
203
+
204
+ # 1. time
205
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
206
+ emb = self.time_embedding(t_emb, timestep_cond)
207
+ aug_emb = None
208
+
209
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
210
+ if class_emb is not None:
211
+ if self.config.class_embeddings_concat:
212
+ emb = torch.cat([emb, class_emb], dim=-1)
213
+ else:
214
+ emb = emb + class_emb
215
+
216
+ aug_emb = self.get_aug_embed(
217
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
218
+ )
219
+ if self.config.addition_embed_type == "image_hint":
220
+ aug_emb, hint = aug_emb
221
+ sample = torch.cat([sample, hint], dim=1)
222
+
223
+ emb = emb + aug_emb if aug_emb is not None else emb
224
+
225
+ if self.time_embed_act is not None:
226
+ emb = self.time_embed_act(emb)
227
+
228
+ encoder_hidden_states = self.process_encoder_hidden_states(
229
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
230
+ )
231
+
232
+ # 2. pre-process
233
+ sample = self.conv_in(sample)
234
+
235
+ # 2.5 GLIGEN position net
236
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
237
+ cross_attention_kwargs = cross_attention_kwargs.copy()
238
+ gligen_args = cross_attention_kwargs.pop("gligen")
239
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
240
+
241
+ # 3. down
242
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
243
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
244
+ if cross_attention_kwargs is not None:
245
+ cross_attention_kwargs = cross_attention_kwargs.copy()
246
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
247
+ else:
248
+ lora_scale = 1.0
249
+
250
+ if USE_PEFT_BACKEND:
251
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
252
+ scale_lora_layers(self, lora_scale)
253
+
254
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
255
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
256
+ is_adapter = down_intrablock_additional_residuals is not None
257
+
258
+ if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
259
+ deprecate(
260
+ "T2I should not use down_block_additional_residuals",
261
+ "1.3.0",
262
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
263
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
264
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
265
+ standard_warn=False,
266
+ )
267
+ down_intrablock_additional_residuals = down_block_additional_residuals
268
+ is_adapter = True
269
+
270
+ down_block_res_samples = (sample,)
271
+ for downsample_block in self.down_blocks:
272
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
273
+ # For t2i-adapter CrossAttnDownBlock2D
274
+ additional_residuals = {}
275
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
276
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
277
+
278
+ sample, res_samples = downsample_block(
279
+ hidden_states=sample,
280
+ temb=emb,
281
+ encoder_hidden_states=encoder_hidden_states,
282
+ attention_mask=attention_mask,
283
+ cross_attention_kwargs=cross_attention_kwargs,
284
+ encoder_attention_mask=encoder_attention_mask,
285
+ **additional_residuals,
286
+ )
287
+ else:
288
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
289
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
290
+ sample += down_intrablock_additional_residuals.pop(0)
291
+
292
+ down_block_res_samples += res_samples
293
+
294
+ if is_controlnet:
295
+ new_down_block_res_samples = ()
296
+
297
+ for down_block_res_sample, down_block_additional_residual in zip(
298
+ down_block_res_samples, down_block_additional_residuals
299
+ ):
300
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
301
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
302
+
303
+ down_block_res_samples = new_down_block_res_samples
304
+
305
+ # 4. mid
306
+ if self.mid_block is not None:
307
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
308
+ sample = self.mid_block(
309
+ sample,
310
+ emb,
311
+ encoder_hidden_states=encoder_hidden_states,
312
+ attention_mask=attention_mask,
313
+ cross_attention_kwargs=cross_attention_kwargs,
314
+ encoder_attention_mask=encoder_attention_mask,
315
+ )
316
+ else:
317
+ sample = self.mid_block(sample, emb)
318
+
319
+ # To support T2I-Adapter-XL
320
+ if (
321
+ is_adapter
322
+ and len(down_intrablock_additional_residuals) > 0
323
+ and sample.shape == down_intrablock_additional_residuals[0].shape
324
+ ):
325
+ sample += down_intrablock_additional_residuals.pop(0)
326
+
327
+ if is_controlnet:
328
+ sample = sample + mid_block_additional_residual
329
+
330
+ # 5. up
331
+ for i, upsample_block in enumerate(self.up_blocks):
332
+ is_final_block = i == len(self.up_blocks) - 1
333
+
334
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
335
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
336
+
337
+ # if we have not reached the final block and need to forward the
338
+ # upsample size, we do it here
339
+ if not is_final_block and forward_upsample_size:
340
+ upsample_size = down_block_res_samples[-1].shape[2:]
341
+
342
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
343
+ sample = upsample_block(
344
+ hidden_states=sample,
345
+ temb=emb,
346
+ res_hidden_states_tuple=res_samples,
347
+ encoder_hidden_states=encoder_hidden_states,
348
+ cross_attention_kwargs=cross_attention_kwargs,
349
+ upsample_size=upsample_size,
350
+ attention_mask=attention_mask,
351
+ encoder_attention_mask=encoder_attention_mask,
352
+ )
353
+ else:
354
+ sample = upsample_block(
355
+ hidden_states=sample,
356
+ temb=emb,
357
+ res_hidden_states_tuple=res_samples,
358
+ upsample_size=upsample_size,
359
+ )
360
+
361
+ ########################## changed section ##########################
362
+ self.latent_store(sample.detach(), t=timestep, layer_index=i)
363
+ self.latent_store.smooth(kernel_size=3, sigma=1)
364
+ #####################################################################
365
+
366
+ # 6. post-process
367
+ if self.conv_norm_out:
368
+ sample = self.conv_norm_out(sample)
369
+ sample = self.conv_act(sample)
370
+ sample = self.conv_out(sample)
371
+
372
+ if USE_PEFT_BACKEND:
373
+ # remove `lora_scale` from each PEFT layer
374
+ unscale_lora_layers(self, lora_scale)
375
+
376
+ if not return_dict:
377
+ return (sample,)
378
+
379
+ return UNet2DConditionOutput(sample=sample)
380
+
381
+
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.5.1
2
+ torchvision==0.20.1
3
+ ml-collections==0.1.1
4
+ diffusers>=0.29.0
5
+ transformers>=4.46
6
+ accelerate==0.33.0
7
+ json-with-comments==1.2.7
8
+ gradio
9
+ spaces
10
+ scipy
11
+ einops
12
+ scikit-learn
13
+ opencv-python
14
+ rembg
15
+ onnxruntime
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .ddpm_inversion import get_ddpm_inversion_scheduler
src/ddpm_inversion.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor
3
+ import torch.nn.functional as F
4
+ from typing import Optional, Union, Tuple
5
+ from utils import normalize
6
+ from model import freq_exp, gen_nn_map
7
+ from src.ddpm_step import deterministic_ddpm_step
8
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
9
+
10
+
11
+ # Kernel sizes for the DIFT correction at successive time-ranges
12
+ DIFT_KERNELS: Tuple[int, int, int, int] = (12, 7, 5, 3)
13
+
14
+ def _get_kernel_for_timestep(timestep: int) -> Tuple[int, int]:
15
+ if timestep >= 799:
16
+ return DIFT_KERNELS[0], 1
17
+ if timestep >= 599:
18
+ return DIFT_KERNELS[1], 1
19
+ if timestep >= 299:
20
+ return DIFT_KERNELS[2], 1
21
+ return DIFT_KERNELS[3], 1
22
+
23
+ def step_save_latents(
24
+ self,
25
+ model_output: torch.FloatTensor,
26
+ timestep: int,
27
+ sample: torch.FloatTensor,
28
+ return_dict: bool = True,
29
+ noise_pred_uncond: Optional[torch.FloatTensor] = None,
30
+ **kwargs,
31
+ ):
32
+ timestep_index = self._timesteps.index(timestep)
33
+ next_timestep_index = timestep_index + 1
34
+
35
+ u_hat_t, beta_coef = deterministic_ddpm_step(
36
+ model_output=model_output,
37
+ timestep=timestep,
38
+ sample=sample,
39
+ scheduler=self,
40
+ )
41
+
42
+ x_t_minus_1 = self.x_ts[next_timestep_index]
43
+ self.x_ts_c_predicted.append(u_hat_t)
44
+
45
+ z_t = x_t_minus_1 - u_hat_t
46
+ self.latents.append(z_t)
47
+
48
+ z_t, _ = normalize(z_t, timestep_index, self._config.max_norm_zs)
49
+
50
+ x_t_minus_1_predicted = u_hat_t + z_t
51
+
52
+ if not return_dict:
53
+ return (x_t_minus_1_predicted,)
54
+
55
+ return DDIMSchedulerOutput(prev_sample=x_t_minus_1, pred_original_sample=None)
56
+
57
+
58
+ def step_use_latents(
59
+ self,
60
+ model_output: torch.FloatTensor,
61
+ timestep: int,
62
+ sample: torch.FloatTensor,
63
+ return_dict: bool = True,
64
+ noise_pred_uncond: Optional[torch.FloatTensor] = None,
65
+ **kwargs,
66
+ ):
67
+ timestep_index = self._timesteps.index(timestep)
68
+ next_timestep_index = timestep_index + 1
69
+
70
+ z_t = self.latents[next_timestep_index]
71
+ _, normalize_coefficient = normalize(
72
+ z_t,
73
+ timestep_index,
74
+ self._config.max_norm_zs,
75
+ )
76
+
77
+ x_t_hat_c_hat, beta_coef = deterministic_ddpm_step(
78
+ model_output=model_output,
79
+ timestep=timestep,
80
+ sample=sample,
81
+ scheduler=self,
82
+ )
83
+
84
+ x_t_minus_1_exact = self.x_ts[next_timestep_index]
85
+ x_t_minus_1_exact = x_t_minus_1_exact.expand_as(x_t_hat_c_hat)
86
+
87
+ x_t_c_predicted: torch.Tensor = self.x_ts_c_predicted[next_timestep_index]
88
+
89
+ x_t_c = x_t_c_predicted[0].expand_as(x_t_hat_c_hat)
90
+
91
+ mask: Optional[Tensor] = kwargs.get("mask", None)
92
+ if mask is not None and timestep > 300:
93
+ mask = mask.to(x_t_hat_c_hat.device)
94
+ movement_intensifier = kwargs.get("movement_intensifier", 0.0)
95
+
96
+ if timestep > 900 and movement_intensifier > 0.0:
97
+ latent_mask_h, *_ = freq_exp(
98
+ x_t_hat_c_hat[1:],
99
+ "auto_mask",
100
+ None,
101
+ mask.unsqueeze(0),
102
+ movement_intensifier
103
+ )
104
+ x_t_hat_c_hat[1:] = latent_mask_h
105
+
106
+ x_t_hat_c_hat[-1] = x_t_hat_c_hat[-1] * mask + (1-mask) * x_t_c[-1]
107
+
108
+ edit_prompts_num = model_output.size(0) // 2
109
+ x_t_hat_c_indices = (
110
+ 0,
111
+ edit_prompts_num,
112
+ )
113
+ edit_images_indices = (
114
+ edit_prompts_num,
115
+ (model_output.size(0)),
116
+ )
117
+
118
+ x_t_hat_c = torch.zeros_like(x_t_hat_c_hat)
119
+ x_t_hat_c[edit_images_indices[0] : edit_images_indices[1]] = x_t_hat_c_hat[
120
+ x_t_hat_c_indices[0] : x_t_hat_c_indices[1]
121
+ ]
122
+
123
+ w1 = kwargs.get("w1", 1.9)
124
+ cross_prompt_term = x_t_hat_c_hat - x_t_hat_c
125
+ cross_trajectory_term = x_t_hat_c - normalize_coefficient * x_t_c
126
+
127
+ x_t_minus_1_hat_ = (
128
+ normalize_coefficient * x_t_minus_1_exact
129
+ + cross_trajectory_term
130
+ + w1 * cross_prompt_term
131
+ )
132
+
133
+ x_t_minus_1_hat_[x_t_hat_c_indices[0] : x_t_hat_c_indices[1]] = x_t_minus_1_hat_[
134
+ edit_images_indices[0] : edit_images_indices[1]
135
+ ]
136
+
137
+ dift_timestep = kwargs.get("dift_timestep", 700)
138
+
139
+ if timestep < dift_timestep and kwargs.get("apply_dift_correction", False):
140
+ z_t = torch.cat([z_t]*x_t_hat_c_hat.shape[0], dim=0)
141
+
142
+ dift_features: Optional[Tensor] = kwargs.get("dift_features", None)
143
+ dift_s, _, dift_t = dift_features.chunk(3)
144
+
145
+ resized_src_features = F.interpolate(dift_s[0].unsqueeze(0), size=z_t.shape[-1], mode='bilinear', align_corners=False).squeeze(0)
146
+ resized_tgt_features = F.interpolate(dift_t[0].unsqueeze(0), size=z_t.shape[-1], mode='bilinear', align_corners=False).squeeze(0)
147
+
148
+ kernel_size, stride = _get_kernel_for_timestep(timestep)
149
+ torch.cuda.empty_cache()
150
+
151
+ updated_z_t = gen_nn_map(z_t[1], resized_src_features, resized_tgt_features,
152
+ kernel_size=kernel_size, stride=stride,
153
+ device=z_t.device, timestep=timestep)
154
+
155
+ alpha = 1.0
156
+ z_t[1] = alpha * updated_z_t + (1 - alpha) * z_t[1]
157
+
158
+ x_t_minus_1_hat = x_t_hat_c_hat + z_t * normalize_coefficient
159
+ else:
160
+ x_t_minus_1_hat = x_t_minus_1_hat_
161
+
162
+ if not return_dict:
163
+ return (x_t_minus_1_hat,)
164
+
165
+ return DDIMSchedulerOutput(
166
+ prev_sample=x_t_minus_1_hat,
167
+ pred_original_sample=None,
168
+ )
169
+
170
+
171
+ def get_ddpm_inversion_scheduler(
172
+ scheduler,
173
+ config,
174
+ timesteps,
175
+ latents,
176
+ x_ts,
177
+ **kwargs,
178
+ ):
179
+ def step(
180
+ model_output: torch.FloatTensor,
181
+ timestep: int,
182
+ sample: torch.FloatTensor,
183
+ eta: float = 0.0,
184
+ use_clipped_model_output: bool = False,
185
+ generator=None,
186
+ variance_noise: Optional[torch.FloatTensor] = None,
187
+ noise_pred_uncond: Optional[torch.FloatTensor] = None,
188
+ dift_features: Optional[torch.FloatTensor] = None,
189
+ return_dict: bool = True,
190
+ ):
191
+ # predict and save x_t_c
192
+ res_inv = step_save_latents(
193
+ scheduler,
194
+ model_output[:1, :, :, :],
195
+ timestep,
196
+ sample[:1, :, :, :],
197
+ return_dict,
198
+ noise_pred_uncond[:1, :, :, :],
199
+ **kwargs,
200
+ )
201
+
202
+ res_inf = step_use_latents(
203
+ scheduler,
204
+ model_output[1:, :, :, :],
205
+ timestep,
206
+ sample[1:, :, :, :],
207
+ return_dict,
208
+ noise_pred_uncond[1:, :, :, :],
209
+ dift_features=dift_features,
210
+ **kwargs,
211
+ )
212
+ res = (torch.cat((res_inv[0], res_inf[0]), dim=0),)
213
+ return res
214
+
215
+ scheduler._timesteps = timesteps
216
+ scheduler._config = config
217
+ scheduler.latents = latents
218
+ scheduler.x_ts = x_ts
219
+ scheduler.x_ts_c_predicted = [None]
220
+ scheduler.step = step
221
+ return scheduler
222
+
src/ddpm_step.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Union
3
+
4
+ def deterministic_ddpm_step(
5
+ model_output: torch.FloatTensor,
6
+ timestep: Union[float, torch.FloatTensor],
7
+ sample: torch.FloatTensor,
8
+ scheduler,
9
+ ):
10
+ """
11
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
12
+ process from the learned model outputs (most often the predicted noise).
13
+ """
14
+ t = timestep
15
+
16
+ prev_t = scheduler.previous_timestep(t)
17
+
18
+ if model_output.shape[1] == sample.shape[1] * 2 and scheduler.variance_type in [
19
+ "learned",
20
+ "learned_range",
21
+ ]:
22
+ model_output, predicted_variance = torch.split(
23
+ model_output, sample.shape[1], dim=1
24
+ )
25
+ else:
26
+ predicted_variance = None
27
+
28
+ # 1. compute alphas, betas
29
+ alpha_prod_t = scheduler.alphas_cumprod[t]
30
+ alpha_prod_t_prev = (
31
+ scheduler.alphas_cumprod[prev_t] if prev_t >= 0 else scheduler.one
32
+ )
33
+ beta_prod_t = 1 - alpha_prod_t
34
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
35
+ current_alpha_t = alpha_prod_t / alpha_prod_t_prev
36
+ current_beta_t = 1 - current_alpha_t
37
+
38
+ # 2. compute predicted original sample from predicted noise also called
39
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
40
+ if scheduler.config.prediction_type == "epsilon":
41
+ pred_original_sample = (
42
+ sample - beta_prod_t ** (0.5) * model_output
43
+ ) / alpha_prod_t ** (0.5)
44
+ elif scheduler.config.prediction_type == "sample":
45
+ pred_original_sample = model_output
46
+ elif scheduler.config.prediction_type == "v_prediction":
47
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (
48
+ beta_prod_t**0.5
49
+ ) * model_output
50
+ else:
51
+ raise ValueError(
52
+ f"prediction_type given as {scheduler.config.prediction_type} must be one of `epsilon`, `sample` or"
53
+ " `v_prediction` for the DDPMScheduler."
54
+ )
55
+
56
+ # 3. Clip or threshold "predicted x_0"
57
+ if scheduler.config.thresholding:
58
+ pred_original_sample = scheduler._threshold_sample(pred_original_sample)
59
+ elif scheduler.config.clip_sample:
60
+ pred_original_sample = pred_original_sample.clamp(
61
+ -scheduler.config.clip_sample_range, scheduler.config.clip_sample_range
62
+ )
63
+
64
+ current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t
65
+ coef_D = current_sample_coeff * (beta_prod_t ** (0.5)) ## it is equal to coef_D
66
+ pred_prev_sample = (alpha_prod_t_prev ** (0.5) * pred_original_sample) + (
67
+ coef_D * model_output
68
+ )
69
+
70
+ return pred_prev_sample, coef_D
utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .args import get_args
2
+ from .pipeline_utils import load_pipeline, set_pipeline, encode_image, create_xts
3
+ from .utils import extract_mask, find_smallest_key_with_suffix, normalize
utils/args.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ def add_general_arguments(parser: argparse.ArgumentParser) -> None:
4
+ parser.add_argument("--cache_dir", type=str, default=None)
5
+ parser.add_argument("--prompts_file", type=str, default="")
6
+ parser.set_defaults(fp16=False)
7
+ parser.add_argument("--fp16", action="store_true")
8
+ # parser.add_argument("--seeds", type=int, nargs='+', default=[7], help="List of seed values (e.g., --seed 22 42)")
9
+ parser.add_argument("--seed", type=int, default=7, help="Seed value for random number generation.")
10
+ parser.add_argument("--output_dir", type=str, default="output")
11
+ parser.add_argument("--eval_dataset_folder", type=str, default="dataset")
12
+ parser.add_argument("--num_of_timesteps", type=int, default=5) # 3 or 4
13
+
14
+ def add_extra_arguments(parser: argparse.ArgumentParser) -> None:
15
+ parser.add_argument("--guidance_scale", type=float, default=0.0, help="Guidance scale value.")
16
+ parser.add_argument("--apply_dift_correction", action="store_true", help="Apply DIFT correction.")
17
+ parser.set_defaults(apply_dift_correction=False)
18
+ parser.add_argument("--w1", type=float, default=1.9, help="Weight for CTRL-X mode.")
19
+ parser.add_argument("--support_new_object", action="store_true", help="Enable support for new object detection.")
20
+ parser.add_argument("--mode", type=str, default="slerp_dift", help="Attention Type (e.g., normal, slerp, lerp, ...).")
21
+ parser.add_argument("--dift_timestep", type=int, default=400, help="DIFT timestep.")
22
+ parser.add_argument("--movement_intensifier", type=float, default=0.2, help="Movement intensifier factor.")
23
+ parser.add_argument("--structural_alignment", action="store_true", help="Enable structural alignment.")
24
+
25
+ def add_editing_arguments(parser: argparse.ArgumentParser) -> None:
26
+ parser.add_argument("--max_norm_zs", type=float, nargs="+", default=[-1, -1, -1, 15.5],
27
+ help="A list of floats for max_norm_zs.")
28
+ parser.add_argument("--noise_shift_delta", type=float, default=1)
29
+ parser.add_argument("--noise_timesteps", type=int, nargs="+", default=[799, 499, 199, 0],
30
+ help="A list of ints for noise_timesteps.")
31
+ parser.add_argument("--timesteps", type=int, nargs="+", default=[999, 799, 499, 199],
32
+ help="A list of ints for timesteps.")
33
+ parser.add_argument("--num_steps_inversion", type=int, default=5)
34
+ parser.add_argument("--step_start", type=int, default=1)
35
+
36
+ def check_args(args):
37
+ if args.num_of_timesteps not in [3, 4, 5, 10]:
38
+ raise ValueError("num_timesteps must be 3, 4, or 5 or 10")
39
+
40
+ if args.timesteps is not None:
41
+ num_steps_actual = len(args.timesteps)
42
+ else:
43
+ num_steps_actual = args.num_steps_inversion - args.step_start
44
+
45
+ if isinstance(args.max_norm_zs, (int, float)):
46
+ args.max_norm_zs = [args.max_norm_zs] * num_steps_actual
47
+
48
+ assert (
49
+ len(args.max_norm_zs) == num_steps_actual
50
+ ), f"len(args.max_norm_zs) ({len(args.max_norm_zs)}) != num_steps_actual ({num_steps_actual})"
51
+
52
+ assert args.noise_timesteps is None or len(args.noise_timesteps) == (
53
+ num_steps_actual
54
+ ), f"len(args.noise_timesteps) ({len(args.noise_timesteps)}) != num_steps_actual ({num_steps_actual})"
55
+
56
+
57
+ def get_args():
58
+ parser = argparse.ArgumentParser()
59
+ add_general_arguments(parser)
60
+ add_editing_arguments(parser)
61
+ add_extra_arguments(parser)
62
+ args = parser.parse_args()
63
+ check_args(args)
64
+ return args
65
+
utils/dino_utils.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+
4
+ class DINOv2Processor:
5
+ def __init__(self, model_name="dinov2_vitb14", device="cpu", image_size=518):
6
+ self.model_name = model_name
7
+ self.device = device
8
+ self.image_size = image_size
9
+ self.model = self._load_model()
10
+
11
+ def _load_model(self):
12
+ model = torch.hub.load('facebookresearch/dinov2', self.model_name)
13
+ model.eval()
14
+ model.to(self.device)
15
+ return model
16
+
17
+ def _preprocess_image(self, image):
18
+ preprocess = transforms.Compose([
19
+ transforms.Resize(self.image_size, interpolation=transforms.InterpolationMode.BICUBIC),
20
+ transforms.CenterCrop(self.image_size),
21
+ transforms.ToTensor(),
22
+ transforms.Normalize(
23
+ mean=[0.485, 0.456, 0.406],
24
+ std=[0.229, 0.224, 0.225]
25
+ ),
26
+ ])
27
+ return preprocess(image)
28
+
29
+ def compute_similarity(self, pil_image1, pil_image2):
30
+ img1_t = self._preprocess_image(pil_image1).unsqueeze(0).to(self.device)
31
+ img2_t = self._preprocess_image(pil_image2).unsqueeze(0).to(self.device)
32
+ with torch.no_grad():
33
+ feat1 = self.model(img1_t)
34
+ feat2 = self.model(img2_t)
35
+ feat1 = feat1 / feat1.norm(dim=1, keepdim=True)
36
+ feat2 = feat2 / feat2.norm(dim=1, keepdim=True)
37
+ similarity = (feat1 * feat2).sum(dim=1)
38
+ return similarity.item()
utils/general_utils.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import io
4
+ import cv2
5
+ import numpy as np
6
+ from PIL import Image
7
+ from rembg import remove
8
+
9
+
10
+ def normalize(
11
+ z_t,
12
+ i,
13
+ max_norm_zs,
14
+ ):
15
+ max_norm = max_norm_zs[i]
16
+ if max_norm < 0:
17
+ return z_t, 1
18
+
19
+ norm = torch.norm(z_t)
20
+ if norm < max_norm:
21
+ return z_t, 1
22
+
23
+ coeff = max_norm / norm
24
+ z_t = z_t * coeff
25
+ return z_t, coeff
26
+
27
+ def normalize2(x, dim):
28
+ x_mean = x.mean(dim=dim, keepdim=True)
29
+ x_std = x.std(dim=dim, keepdim=True)
30
+ x_normalized = (x - x_mean) / x_std
31
+ return x_normalized
32
+
33
+ def find_lambda_via_newton_batched(Qp, K_source, K_target, max_iter=50, tol=1e-7):
34
+ dot_QpK_source = torch.einsum("bcd,bmd->bcm", Qp, K_source) # shape [B]
35
+ dot_QpK_target = torch.einsum("bcd,bmd->bcm", Qp, K_target) # shape [B]
36
+ X = torch.exp(dot_QpK_source)
37
+
38
+ lmbd = torch.zeros([1], device=Qp.device, dtype=Qp.dtype) + 0.7
39
+ for it in range(max_iter):
40
+ y = torch.exp(lmbd * dot_QpK_target)
41
+ Z = (X + y).sum(dim=(2), keepdim=True)
42
+ x = X / Z
43
+ y = y / Z
44
+ val = (x.sum(dim=(1,2)) - y.sum(dim=(1,2))).sum()
45
+
46
+ grad = - (dot_QpK_target * y).sum()
47
+
48
+ if not (val.abs() > tol and grad.abs() > 1e-12):
49
+ break
50
+
51
+ lmbd = lmbd - val / grad
52
+ if lmbd.item() < 0.4:
53
+ return 0.1
54
+ elif lmbd.item() > 0.9:
55
+ return 0.65
56
+
57
+ return lmbd.item()
58
+
59
+ def find_lambda_via_super_halley(Qp, K_source, K_target, max_iter=50, tol=1e-7):
60
+ dot_QpK_source = torch.einsum("bcd,bmd->bcm", Qp, K_source)
61
+ dot_QpK_target = torch.einsum("bcd,bmd->bcm", Qp, K_target)
62
+ X = torch.exp(dot_QpK_source)
63
+
64
+ lmbd = torch.zeros([], device=Qp.device, dtype=Qp.dtype) + 0.8
65
+
66
+ for it in range(max_iter):
67
+ y = torch.exp(lmbd * dot_QpK_target)
68
+
69
+ Z = (X + y).sum(dim=2, keepdim=True)
70
+ x = X / Z
71
+ y = y / Z
72
+
73
+ val = (x.sum(dim=(1,2)) - y.sum(dim=(1,2))).sum()
74
+
75
+ grad = - (dot_QpK_target * y).sum()
76
+
77
+ f2 = - (dot_QpK_target**2 * y).sum()
78
+
79
+ if not (val.abs() > tol and grad.abs() > 1e-12):
80
+ break
81
+
82
+ denom = grad**2 - val * f2
83
+ if denom.abs() < 1e-20:
84
+ break
85
+
86
+ update = (val * grad) / denom
87
+ lmbd = lmbd - update
88
+
89
+ print(f"iter={it}, λ={lmbd.item():.6f}, val={val.item():.6e}, grad={grad.item():.6e}")
90
+
91
+ return lmbd
92
+
93
+ def find_smallest_key_with_suffix(features_dict: dict, suffix: str = "_1") -> str:
94
+ smallest_key = None
95
+ smallest_number = float('inf')
96
+ for key in features_dict.keys():
97
+ if key.endswith(suffix):
98
+ try:
99
+ number = int(key.split('_')[0])
100
+ if number < smallest_number:
101
+ smallest_number = number
102
+ smallest_key = key
103
+ except ValueError:
104
+ continue
105
+ return smallest_key
106
+
107
+ def extract_mask(masks, original_width, original_height):
108
+ if not masks:
109
+ return None
110
+
111
+ combined_mask = torch.zeros(512, 512)
112
+ scale_x = 512 / original_width
113
+ scale_y = 512 / original_height
114
+
115
+ for mask in masks:
116
+ start_x, start_y = mask["start_point"]
117
+ end_x, end_y = mask["end_point"]
118
+
119
+ start_x, end_x = min(start_x, end_x), max(start_x, end_x)
120
+ start_y, end_y = min(start_y, end_y), max(start_y, end_y)
121
+
122
+ scaled_start_x, scaled_start_y = int(start_x * scale_x), int(start_y * scale_y)
123
+ scaled_end_x, scaled_end_y = int(end_x * scale_x), int(end_y * scale_y)
124
+ combined_mask[scaled_start_y:scaled_end_y, scaled_start_x:scaled_end_x] += 1
125
+
126
+ binary_mask = (combined_mask > 0).float()
127
+ resized_mask = F.interpolate(binary_mask[None, None, :, :], size=(64, 64), mode="nearest")[0, 0]
128
+
129
+ return resized_mask
130
+
131
+ def remove_foreground(pil_image, threshold=128):
132
+ try:
133
+ with io.BytesIO() as input_buffer:
134
+ pil_image.save(input_buffer, format="PNG")
135
+ input_image_bytes = input_buffer.getvalue()
136
+
137
+ output_image_bytes = remove(input_image_bytes, alpha_matting=True)
138
+
139
+ output_image = Image.open(io.BytesIO(output_image_bytes))
140
+
141
+ mask = output_image.split()[-1]
142
+
143
+ mask_array = np.array(mask)
144
+ binary_mask = (mask_array >= threshold).astype(np.float32)
145
+
146
+ kernel = np.ones((15, 15), np.uint8)
147
+ binary_mask = cv2.erode(binary_mask, kernel, iterations=1)
148
+
149
+ mask_tensor = torch.from_numpy(binary_mask)
150
+ resized_mask = F.interpolate(mask_tensor[None, None, :, :], size=(64, 64), mode="nearest")[0, 0]
151
+
152
+ return resized_mask
153
+ except Exception as e:
154
+ print(f"Error while removing foreground: {e}")
155
+ return None
utils/pipeline_utils.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img import (
3
+ retrieve_timesteps,
4
+ retrieve_latents,
5
+ )
6
+
7
+ import torch
8
+ from functools import partial
9
+ from diffusers import DDPMScheduler
10
+ from model.pipeline_sdxl import StableDiffusionXLImg2ImgPipeline
11
+
12
+ SAMPLING_DEVICE = "cpu" # "cuda"
13
+ VAE_SAMPLE = "argmax" # "argmax" or "sample"
14
+ RESIZE_TYPE = None # Image.LANCZOS
15
+
16
+ device = "cuda" if torch.cuda.is_available() else "cpu"
17
+
18
+ def encode_image(image, pipe, generator):
19
+ pipe_dtype = pipe.dtype
20
+ image = pipe.image_processor.preprocess(image)
21
+ image = image.to(device=device, dtype=pipe.dtype)
22
+
23
+ if pipe.vae.config.force_upcast:
24
+ image = image.float()
25
+ pipe.vae.to(dtype=torch.float32)
26
+
27
+ init_latents = retrieve_latents(
28
+ pipe.vae.encode(image), generator=generator, sample_mode=VAE_SAMPLE
29
+ )
30
+
31
+ if pipe.vae.config.force_upcast:
32
+ pipe.vae.to(pipe_dtype)
33
+
34
+ init_latents = init_latents.to(pipe_dtype)
35
+ init_latents = pipe.vae.config.scaling_factor * init_latents
36
+
37
+ return init_latents
38
+
39
+ def create_xts(
40
+ noise_shift_delta,
41
+ noise_timesteps,
42
+ generator,
43
+ scheduler,
44
+ timesteps,
45
+ x_0,
46
+ ):
47
+ if noise_timesteps is None:
48
+ noising_delta = noise_shift_delta * (timesteps[0] - timesteps[1])
49
+ noise_timesteps = [timestep - int(noising_delta) for timestep in timesteps]
50
+ # noise_timesteps = [timestep for timestep in timesteps]
51
+
52
+ # print(noise_timesteps, timesteps)
53
+ first_x_0_idx = len(noise_timesteps)
54
+ for i in range(len(noise_timesteps)):
55
+ if noise_timesteps[i] <= 0:
56
+ first_x_0_idx = i
57
+ break
58
+
59
+ noise_timesteps = noise_timesteps[:first_x_0_idx]
60
+
61
+ x_0_expanded = x_0.expand(len(noise_timesteps), -1, -1, -1)
62
+ noise = torch.randn(
63
+ x_0_expanded.size(), generator=generator, device=SAMPLING_DEVICE
64
+ ).to(x_0.device)
65
+
66
+ x_ts = scheduler.add_noise(
67
+ x_0_expanded,
68
+ noise,
69
+ torch.IntTensor(noise_timesteps),
70
+ )
71
+ x_ts = [t.unsqueeze(dim=0) for t in list(x_ts)]
72
+ x_ts += [x_0] * (len(timesteps) - first_x_0_idx)
73
+ x_ts += [x_0]
74
+ return x_ts
75
+
76
+ def load_pipeline(fp16, cache_dir):
77
+ kwargs = (
78
+ {
79
+ "torch_dtype": torch.float16,
80
+ "variant": "fp16",
81
+ }
82
+ if fp16
83
+ else {}
84
+ )
85
+ from model.unet_sdxl import OursUNet2DConditionModel
86
+ unet = OursUNet2DConditionModel.from_pretrained(
87
+ "stabilityai/sdxl-turbo",
88
+ subfolder="unet",
89
+ cache_dir=cache_dir,
90
+ safety_checker=None,
91
+ **kwargs,
92
+ )
93
+
94
+ pipeline = StableDiffusionXLImg2ImgPipeline.from_pretrained(
95
+ "stabilityai/sdxl-turbo",
96
+ unet=unet,
97
+ cache_dir=cache_dir,
98
+ safety_checker=None,
99
+ **kwargs,
100
+ )
101
+
102
+ pipeline = pipeline.to(device)
103
+ pipeline.scheduler = DDPMScheduler.from_pretrained( # type: ignore
104
+ "stabilityai/sdxl-turbo",
105
+ subfolder="scheduler",
106
+ )
107
+
108
+ return pipeline
109
+
110
+ def set_pipeline(pipeline: StableDiffusionXLImg2ImgPipeline, num_timesteps, generator, config):
111
+ if config.timesteps is None:
112
+ denoising_start = config.step_start / config.num_steps_inversion
113
+ timesteps, num_inference_steps = retrieve_timesteps(
114
+ pipeline.scheduler, config.num_steps_inversion, device, None
115
+ )
116
+ timesteps, num_inference_steps = pipeline.get_timesteps(
117
+ num_inference_steps=num_inference_steps,
118
+ device=device,
119
+ denoising_start=denoising_start,
120
+ strength=0,
121
+ )
122
+ timesteps = timesteps.type(torch.int64)
123
+ pipeline.__call__ = partial(
124
+ pipeline.__call__,
125
+ num_inference_steps=config.num_steps_inversion,
126
+ guidance_scale=config.guidance_scale,
127
+ generator=generator,
128
+ denoising_start=denoising_start,
129
+ strength=0,
130
+ )
131
+ pipeline.scheduler.set_timesteps(
132
+ timesteps=timesteps.cpu(),
133
+ )
134
+ else:
135
+ timesteps = torch.tensor(config.timesteps, dtype=torch.int64)
136
+ pipeline.__call__ = partial(
137
+ pipeline.__call__,
138
+ timesteps=timesteps,
139
+ guidance_scale=config.guidance_scale,
140
+ denoising_start=0,
141
+ strength=1,
142
+ )
143
+ pipeline.scheduler.set_timesteps(
144
+ timesteps=config.timesteps, # device=pipeline.device
145
+ )
146
+ timesteps = [torch.tensor(t) for t in timesteps.tolist()]
147
+ return timesteps, config
148
+
utils/utils.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import io
4
+ import cv2
5
+ import numpy as np
6
+ from PIL import Image
7
+
8
+
9
+ def normalize(
10
+ z_t,
11
+ i,
12
+ max_norm_zs,
13
+ ):
14
+ max_norm = max_norm_zs[i]
15
+ if max_norm < 0:
16
+ return z_t, 1
17
+
18
+ norm = torch.norm(z_t)
19
+ if norm < max_norm:
20
+ return z_t, 1
21
+
22
+ coeff = max_norm / norm
23
+ z_t = z_t * coeff
24
+ return z_t, coeff
25
+
26
+ def normalize2(x, dim):
27
+ x_mean = x.mean(dim=dim, keepdim=True)
28
+ x_std = x.std(dim=dim, keepdim=True)
29
+ x_normalized = (x - x_mean) / x_std
30
+ return x_normalized
31
+
32
+ def find_lambda_via_newton_batched(Qp, K_source, K_target, max_iter=50, tol=1e-7):
33
+ dot_QpK_source = torch.einsum("bcd,bmd->bcm", Qp, K_source) # shape [B]
34
+ dot_QpK_target = torch.einsum("bcd,bmd->bcm", Qp, K_target) # shape [B]
35
+ X = torch.exp(dot_QpK_source)
36
+
37
+ lmbd = torch.zeros([1], device=Qp.device, dtype=Qp.dtype) + 0.7
38
+ for it in range(max_iter):
39
+ y = torch.exp(lmbd * dot_QpK_target)
40
+ Z = (X + y).sum(dim=(2), keepdim=True)
41
+ x = X / Z
42
+ y = y / Z
43
+ val = (x.sum(dim=(1,2)) - y.sum(dim=(1,2))).sum()
44
+
45
+ grad = - (dot_QpK_target * y).sum()
46
+
47
+ if not (val.abs() > tol and grad.abs() > 1e-12):
48
+ break
49
+
50
+ lmbd = lmbd - val / grad
51
+ if lmbd.item() < 0.4:
52
+ return 0.1
53
+ elif lmbd.item() > 0.9:
54
+ return 0.65
55
+
56
+ return lmbd.item()
57
+
58
+ def find_lambda_via_super_halley(Qp, K_source, K_target, max_iter=50, tol=1e-7):
59
+ dot_QpK_source = torch.einsum("bcd,bmd->bcm", Qp, K_source)
60
+ dot_QpK_target = torch.einsum("bcd,bmd->bcm", Qp, K_target)
61
+ X = torch.exp(dot_QpK_source)
62
+
63
+ lmbd = torch.zeros([], device=Qp.device, dtype=Qp.dtype) + 0.8
64
+
65
+ for it in range(max_iter):
66
+ y = torch.exp(lmbd * dot_QpK_target)
67
+
68
+ Z = (X + y).sum(dim=2, keepdim=True)
69
+ x = X / Z
70
+ y = y / Z
71
+
72
+ val = (x.sum(dim=(1,2)) - y.sum(dim=(1,2))).sum()
73
+
74
+ grad = - (dot_QpK_target * y).sum()
75
+
76
+ f2 = - (dot_QpK_target**2 * y).sum()
77
+
78
+ if not (val.abs() > tol and grad.abs() > 1e-12):
79
+ break
80
+
81
+ denom = grad**2 - val * f2
82
+ if denom.abs() < 1e-20:
83
+ break
84
+
85
+ update = (val * grad) / denom
86
+ lmbd = lmbd - update
87
+
88
+ print(f"iter={it}, λ={lmbd.item():.6f}, val={val.item():.6e}, grad={grad.item():.6e}")
89
+
90
+ return lmbd
91
+
92
+ def find_smallest_key_with_suffix(features_dict: dict, suffix: str = "_1") -> str:
93
+ smallest_key = None
94
+ smallest_number = float('inf')
95
+ for key in features_dict.keys():
96
+ if key.endswith(suffix):
97
+ try:
98
+ number = int(key.split('_')[0])
99
+ if number < smallest_number:
100
+ smallest_number = number
101
+ smallest_key = key
102
+ except ValueError:
103
+ continue
104
+ return smallest_key
105
+
106
+ def extract_mask(masks, original_width, original_height):
107
+ if not masks:
108
+ return None
109
+
110
+ combined_mask = torch.zeros(512, 512)
111
+ scale_x = 512 / original_width
112
+ scale_y = 512 / original_height
113
+
114
+ for mask in masks:
115
+ start_x, start_y = mask["start_point"]
116
+ end_x, end_y = mask["end_point"]
117
+
118
+ start_x, end_x = min(start_x, end_x), max(start_x, end_x)
119
+ start_y, end_y = min(start_y, end_y), max(start_y, end_y)
120
+
121
+ scaled_start_x, scaled_start_y = int(start_x * scale_x), int(start_y * scale_y)
122
+ scaled_end_x, scaled_end_y = int(end_x * scale_x), int(end_y * scale_y)
123
+ combined_mask[scaled_start_y:scaled_end_y, scaled_start_x:scaled_end_x] += 1
124
+
125
+ binary_mask = (combined_mask > 0).float()
126
+ resized_mask = F.interpolate(binary_mask[None, None, :, :], size=(64, 64), mode="nearest")[0, 0]
127
+
128
+ return resized_mask
129
+
visualization/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .image_utils import save_results
visualization/draw_box.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+
3
+ bbox_start = (-1, -1)
4
+ bbox_end = (-1, -1)
5
+ drawing = False
6
+
7
+ image_path = 'images/fatty-corgi.jpg'
8
+
9
+ image = cv2.resize(cv2.imread(image_path), (512, 512))
10
+ image_copy = image.copy()
11
+
12
+ def draw_bbox(event, x, y, flags, param):
13
+ global bbox_start, bbox_end, drawing, image
14
+
15
+ if event == cv2.EVENT_LBUTTONDOWN:
16
+ drawing = True
17
+ bbox_start = (x, y)
18
+ bbox_end = bbox_start
19
+
20
+ elif event == cv2.EVENT_MOUSEMOVE:
21
+ if drawing:
22
+ image = image_copy.copy()
23
+ cv2.rectangle(image, bbox_start, (x, y), (0, 0, 255), 2)
24
+
25
+ elif event == cv2.EVENT_LBUTTONUP:
26
+ drawing = False
27
+ bbox_end = (x, y)
28
+ cv2.rectangle(image, bbox_start, bbox_end, (0, 0, 255), 2)
29
+ # print(f"BBox Coordinates: Start: {bbox_start}, End: {bbox_end}\n")
30
+ print(f"bbx_start_point= ({bbox_start[0]}, {bbox_start[1]}), ")
31
+ print(f"bbx_end_point= ({bbox_end[0]}, {bbox_end[1]})")
32
+
33
+ x1, y1 = bbox_start
34
+ x2, y2 = bbox_end
35
+
36
+ cv2.namedWindow("Image")
37
+ cv2.setMouseCallback("Image", draw_bbox)
38
+
39
+ while True:
40
+ cv2.imshow("Image", image)
41
+ if cv2.waitKey(1) & 0xFF == ord('q'):
42
+ break
43
+
44
+ cv2.destroyAllWindows()
visualization/image_utils.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ import os
5
+ import re
6
+ import jsonc as json
7
+ from PIL import Image
8
+
9
+
10
+ def img_list_to_pil(img_list, cond_image = None, seperation = 10):
11
+ if cond_image is not None:
12
+ img_list.append(cond_image)
13
+
14
+ widths, heights = zip(*(i.size for i in img_list))
15
+ total_width = sum(widths) + seperation * len(img_list)
16
+ max_height = max(heights)
17
+
18
+ new_im = Image.new('RGB', (total_width, max_height))
19
+
20
+ x_offset = 0
21
+ for im in img_list:
22
+ new_im.paste(im, (x_offset, 0))
23
+ x_offset += im.size[0] + seperation
24
+
25
+ return new_im
26
+
27
+
28
+ def grid_image_visualize(images, row_size):
29
+ widths, heights = zip(*(i.size for i in images))
30
+ total_width = max(widths) * row_size + 10 * (row_size - 1)
31
+ max_height = max(heights) * ((len(images) + row_size - 1) // row_size)
32
+ new_im = Image.new('RGB', (total_width, max_height))
33
+
34
+ x_offset = 0
35
+ y_offset = 0
36
+ for i, im in enumerate(images):
37
+ new_im.paste(im, (x_offset, y_offset))
38
+ x_offset += im.size[0] + 10
39
+ if (i + 1) % row_size == 0:
40
+ x_offset = 0
41
+ y_offset += im.size[1]
42
+
43
+ return new_im
44
+
45
+ def process_images(images, res=512):
46
+ res_images = []
47
+ for image in images:
48
+ crop_size = min(image.size)
49
+
50
+ left = (image.size[0] - crop_size) // 2
51
+ top = (image.size[1] - crop_size) // 2
52
+ right = (image.size[0] + crop_size) // 2
53
+ bottom = (image.size[1] + crop_size) // 2
54
+
55
+ image = image.crop((left, top, right, bottom))
56
+ image = image.resize((res, res), Image.BILINEAR)
57
+ res_images.append(image)
58
+ return res_images
59
+
60
+ def sanitize_prompt(prompt: str, max_len: int = 50) -> str:
61
+ sanitized = re.sub(r'[^a-zA-Z0-9_\-]+', '_', prompt)
62
+ return sanitized[:max_len].strip("_")
63
+
64
+ def get_next_index(folder_path: str) -> int:
65
+ if not os.path.exists(folder_path):
66
+ return 0
67
+
68
+ pattern = re.compile(r'.*_(\d+)\.(?:png|json)$')
69
+ max_index = -1
70
+
71
+ for filename in os.listdir(folder_path):
72
+ match = pattern.match(filename)
73
+ if match:
74
+ idx = int(match.group(1))
75
+ if idx > max_index:
76
+ max_index = idx
77
+
78
+ return max_index + 1
79
+
80
+ def save_results(
81
+ args,
82
+ source_prompt: str,
83
+ target_prompt: str,
84
+ images: Image.Image,
85
+ ):
86
+ src_name = sanitize_prompt(source_prompt)
87
+ tgt_name = sanitize_prompt(target_prompt)
88
+ folder_name = f"{src_name}#{tgt_name}"
89
+
90
+ output_dir = os.path.join(args.output_dir, folder_name)
91
+ os.makedirs(output_dir, exist_ok=True)
92
+
93
+ next_idx = get_next_index(output_dir)
94
+
95
+ concated_image = img_list_to_pil([images[0], images[-1]], cond_image=None, seperation=10)
96
+ concated_image.save(os.path.join(output_dir, f"concat_{next_idx}.png"))
97
+ images[0].save(os.path.join(output_dir, f"input_{next_idx}.png"))
98
+ images[-1].save(os.path.join(output_dir, f"output_{next_idx}.png"))
99
+
100
+ args_filename = f"args_{next_idx}.json"
101
+ args_path = os.path.join(output_dir, args_filename)
102
+
103
+ with open(args_path, "w") as f:
104
+ json.dump(vars(args), f, indent=4)
105
+
106
+ print(f"Saved image to {output_dir} and args to {args_path}")