Eugeoter commited on
Commit
9892334
1 Parent(s): 1433427
Files changed (9) hide show
  1. .gitignore +162 -0
  2. README.md +0 -2
  3. app.py +161 -136
  4. models/controlnet.py +495 -0
  5. models/unet.py +1387 -0
  6. pipeline/pipeline_controlnext.py +1378 -0
  7. utils/preprocess.py +38 -0
  8. utils/tools.py +146 -0
  9. utils/utils.py +225 -0
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
README.md CHANGED
@@ -9,5 +9,3 @@ app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
9
  pinned: false
10
  license: apache-2.0
11
  ---
 
 
app.py CHANGED
@@ -1,146 +1,171 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
-
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
-
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
22
-
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
-
60
- with gr.Column(elem_id="col-container"):
61
  gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
  """)
65
-
66
  with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
117
- with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
- )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
  )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
 
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
144
- )
 
 
 
145
 
146
- demo.queue().launch()
 
 
 
1
  import gradio as gr
 
 
 
2
  import torch
3
+ import numpy as np
4
+ from huggingface_hub import hf_hub_download
5
+ from utils import utils, tools, preprocess
6
+
7
+ # BASE_MODEL_PATH = "stablediffusionapi/neta-art-xl-v2"
8
+ VAE_PATH = "madebyollin/sdxl-vae-fp16-fix"
9
+ REPO_ID = "Pbihao/ControlNeXt"
10
+ UNET_FILENAME = "ControlAny-SDXL/anime_canny/unet.safetensors"
11
+ CONTROLNET_FILENAME = "ControlAny-SDXL/anime_canny/controlnet.safetensors"
12
+ CACHE_DIR = None
13
+
14
+
15
+ def ui():
16
+ device = "cuda" if torch.cuda.is_available() else "cpu"
17
+ model_file = hf_hub_download(
18
+ repo_id='Lykon/AAM_XL_AnimeMix',
19
+ filename='AAM_XL_Anime_Mix.safetensors',
20
+ cache_dir=CACHE_DIR,
21
+ )
22
+ unet_file = hf_hub_download(
23
+ repo_id=REPO_ID,
24
+ filename=UNET_FILENAME,
25
+ cache_dir=CACHE_DIR,
26
+ )
27
+ controlnet_file = hf_hub_download(
28
+ repo_id=REPO_ID,
29
+ filename=CONTROLNET_FILENAME,
30
+ cache_dir=CACHE_DIR,
31
+ )
32
+ pipeline = tools.get_pipeline(
33
+ pretrained_model_name_or_path=model_file,
34
+ unet_model_name_or_path=unet_file,
35
+ controlnet_model_name_or_path=controlnet_file,
36
+ vae_model_name_or_path=VAE_PATH,
37
+
38
+ load_weight_increasement=True,
39
+ device=device,
40
+ hf_cache_dir=CACHE_DIR,
41
+ use_safetensors=True,
42
+ enable_xformers_memory_efficient_attention=True,
43
+ )
44
+
45
+ preprocessors = ['canny']
46
+ schedulers = ['Euler A', 'UniPC', 'Euler', 'DDIM', 'DDPM']
47
 
48
+ css = """
49
+ #col-container {
50
+ margin: 0 auto;
51
+ max-width: 520px;
52
+ }
53
+ """
54
+
55
+ with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  gr.Markdown(f"""
57
+ # [ControlNeXt](https://github.com/dvlab-research/ControlNeXt) Official Demo
 
58
  """)
 
59
  with gr.Row():
60
+ with gr.Column(scale=9):
61
+ prompt = gr.Textbox(lines=3, placeholder='prompt', container=False)
62
+ negative_prompt = gr.Textbox(lines=3, placeholder='negative prompt', container=False)
63
+ with gr.Column(scale=1):
64
+ generate_button = gr.Button("Generate", variant='primary', min_width=96)
65
+ with gr.Row():
66
+ with gr.Column(scale=1):
67
+ with gr.Row():
68
+ control_image = gr.Image(
69
+ value=None,
70
+ label='Condition',
71
+ sources=['upload'],
72
+ type='pil',
73
+ height=512,
74
+ show_download_button=True,
75
+ show_share_button=True,
76
+ )
77
+ with gr.Row():
78
+ scheduler = gr.Dropdown(
79
+ label='Scheduler',
80
+ choices=schedulers,
81
+ value='Euler A',
82
+ multiselect=False,
83
+ allow_custom_value=False,
84
+ filterable=True,
85
+ )
86
+ num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, value=20, label='Steps')
87
+ with gr.Row():
88
+ cfg_scale = gr.Slider(minimum=1, maximum=30, step=1, value=7.5, label='CFG Scale')
89
+ controlnet_scale = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.5, label='ControlNet Scale')
90
+ with gr.Row():
91
+ seed = gr.Number(label='Seed', step=1, precision=0, value=-1)
92
+ with gr.Row():
93
+ processor = gr.Dropdown(
94
+ label='Image Preprocessor',
95
+ choices=preprocessors,
96
+ value='canny',
97
+ )
98
+ process_button = gr.Button("Process", variant='primary', min_width=96, scale=0)
99
+ with gr.Column(scale=1):
100
+ output = gr.Gallery(
101
+ label='Output',
102
+ value=None,
103
+ object_fit='scale-down',
104
+ columns=4,
105
+ height=512,
106
+ show_download_button=True,
107
+ show_share_button=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  )
109
+
110
+ def generate(
111
+ prompt,
112
+ control_image,
113
+ negative_prompt,
114
+ cfg_scale,
115
+ controlnet_scale,
116
+ num_inference_steps,
117
+ scheduler,
118
+ seed,
119
+ ):
120
+ pipeline.scheduler = tools.get_scheduler(scheduler, pipeline.scheduler.config)
121
+
122
+ generator = torch.Generator(device=device).manual_seed(max(0, min(seed, np.iinfo(np.int32).max))) if seed != -1 else None
123
+
124
+ if control_image is None:
125
+ raise gr.Error('Please upload an image.')
126
+ width, height = utils.around_reso(control_image.width, control_image.height, reso=1024, max_width=2048, max_height=2048, divisible=32)
127
+ control_image = control_image.resize((width, height)).convert('RGB')
128
+
129
+ with torch.autocast(device):
130
+ output_images = pipeline.__call__(
131
+ prompt=prompt,
132
+ negative_prompt=negative_prompt,
133
+ controlnet_image=control_image,
134
+ controlnet_scale=controlnet_scale,
135
+ width=width,
136
+ height=height,
137
+ generator=generator,
138
+ guidance_scale=cfg_scale,
139
+ num_inference_steps=num_inference_steps,
140
+ ).images
141
+
142
+ return output_images
143
+
144
+ def process(
145
+ image,
146
+ processor,
147
+ ):
148
+ if image is None:
149
+ raise gr.Error('Please upload an image.')
150
+ processor = preprocess.get_extractor(processor)
151
+ image = processor(image)
152
+ return image
153
+
154
+ generate_button.click(
155
+ fn=generate,
156
+ inputs=[prompt, control_image, negative_prompt, cfg_scale, controlnet_scale, num_inference_steps, scheduler, seed],
157
+ outputs=[output],
158
  )
159
 
160
+ process_button.click(
161
+ fn=process,
162
+ inputs=[control_image, processor],
163
+ outputs=[control_image],
164
+ )
165
+
166
+ return demo
167
+
168
 
169
+ if __name__ == '__main__':
170
+ demo = ui()
171
+ demo.queue().launch()
models/controlnet.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
21
+ from diffusers.utils import BaseOutput, logging
22
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
23
+ from diffusers.models.modeling_utils import ModelMixin
24
+ from diffusers.models.resnet import Downsample2D, ResnetBlock2D
25
+ from einops import rearrange
26
+
27
+
28
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
29
+
30
+
31
+ @dataclass
32
+ class ControlNetOutput(BaseOutput):
33
+ """
34
+ The output of [`ControlNetModel`].
35
+
36
+ Args:
37
+ down_block_res_samples (`tuple[torch.Tensor]`):
38
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
39
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
40
+ used to condition the original UNet's downsampling activations.
41
+ mid_down_block_re_sample (`torch.Tensor`):
42
+ The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
43
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
44
+ Output can be used to condition the original UNet's middle block activation.
45
+ """
46
+
47
+ down_block_res_samples: Tuple[torch.Tensor]
48
+ mid_block_res_sample: torch.Tensor
49
+
50
+
51
+ class Block2D(nn.Module):
52
+ def __init__(
53
+ self,
54
+ in_channels: int,
55
+ out_channels: int,
56
+ temb_channels: int,
57
+ dropout: float = 0.0,
58
+ num_layers: int = 1,
59
+ resnet_eps: float = 1e-6,
60
+ resnet_time_scale_shift: str = "default",
61
+ resnet_act_fn: str = "swish",
62
+ resnet_groups: int = 32,
63
+ resnet_pre_norm: bool = True,
64
+ output_scale_factor: float = 1.0,
65
+ add_downsample: bool = True,
66
+ downsample_padding: int = 1,
67
+ ):
68
+ super().__init__()
69
+ resnets = []
70
+
71
+ for i in range(num_layers):
72
+ in_channels = in_channels if i == 0 else out_channels
73
+ resnets.append(
74
+ ResnetBlock2D(
75
+ in_channels=in_channels,
76
+ out_channels=out_channels,
77
+ temb_channels=temb_channels,
78
+ eps=resnet_eps,
79
+ groups=resnet_groups,
80
+ dropout=dropout,
81
+ time_embedding_norm=resnet_time_scale_shift,
82
+ non_linearity=resnet_act_fn,
83
+ output_scale_factor=output_scale_factor,
84
+ pre_norm=resnet_pre_norm,
85
+ )
86
+ )
87
+
88
+ self.resnets = nn.ModuleList(resnets)
89
+
90
+ if add_downsample:
91
+ self.downsamplers = nn.ModuleList(
92
+ [
93
+ Downsample2D(
94
+ out_channels,
95
+ use_conv=True,
96
+ out_channels=out_channels,
97
+ padding=downsample_padding,
98
+ name="op",
99
+ )
100
+ ]
101
+ )
102
+ else:
103
+ self.downsamplers = None
104
+
105
+ self.gradient_checkpointing = False
106
+
107
+ def forward(
108
+ self,
109
+ hidden_states: torch.FloatTensor,
110
+ temb: Optional[torch.FloatTensor] = None,
111
+ ) -> Union[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
112
+ output_states = ()
113
+
114
+ for resnet in zip(self.resnets):
115
+ hidden_states = resnet(hidden_states, temb)
116
+ output_states += (hidden_states,)
117
+
118
+ if self.downsamplers is not None:
119
+ for downsampler in self.downsamplers:
120
+ hidden_states = downsampler(hidden_states)
121
+
122
+ output_states += (hidden_states,)
123
+
124
+ return hidden_states, output_states
125
+
126
+
127
+ class IdentityModule(nn.Module):
128
+ def __init__(self):
129
+ super(IdentityModule, self).__init__()
130
+
131
+ def forward(self, *args):
132
+ if len(args) > 0:
133
+ return args[0]
134
+ else:
135
+ return None
136
+
137
+
138
+ class BasicBlock(nn.Module):
139
+ def __init__(self,
140
+ in_channels: int,
141
+ out_channels: Optional[int] = None,
142
+ stride=1,
143
+ conv_shortcut: bool = False,
144
+ dropout: float = 0.0,
145
+ temb_channels: int = 512,
146
+ groups: int = 32,
147
+ groups_out: Optional[int] = None,
148
+ pre_norm: bool = True,
149
+ eps: float = 1e-6,
150
+ non_linearity: str = "swish",
151
+ skip_time_act: bool = False,
152
+ time_embedding_norm: str = "default", # default, scale_shift, ada_group, spatial
153
+ kernel: Optional[torch.FloatTensor] = None,
154
+ output_scale_factor: float = 1.0,
155
+ use_in_shortcut: Optional[bool] = None,
156
+ up: bool = False,
157
+ down: bool = False,
158
+ conv_shortcut_bias: bool = True,
159
+ conv_2d_out_channels: Optional[int] = None,):
160
+ super(BasicBlock, self).__init__()
161
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)
162
+ self.bn1 = nn.BatchNorm2d(out_channels)
163
+ self.relu = nn.ReLU(inplace=True)
164
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
165
+ self.bn2 = nn.BatchNorm2d(out_channels)
166
+
167
+ self.downsample = None
168
+ if stride != 1 or in_channels != out_channels:
169
+ self.downsample = nn.Sequential(
170
+ nn.Conv2d(in_channels,
171
+ out_channels,
172
+ kernel_size=3 if stride != 1 else 1,
173
+ stride=stride,
174
+ padding=1 if stride != 1 else 0,
175
+ bias=False),
176
+ nn.BatchNorm2d(out_channels)
177
+ )
178
+
179
+ def forward(self, x, *args):
180
+ residual = x
181
+ out = self.conv1(x)
182
+ out = self.bn1(out)
183
+ out = self.relu(out)
184
+
185
+ out = self.conv2(out)
186
+ out = self.bn2(out)
187
+
188
+ if self.downsample is not None:
189
+ residual = self.downsample(x)
190
+
191
+ out += residual
192
+ out = self.relu(out)
193
+
194
+ return out
195
+
196
+
197
+ class Block2D(nn.Module):
198
+ def __init__(
199
+ self,
200
+ in_channels: int,
201
+ out_channels: int,
202
+ temb_channels: int,
203
+ dropout: float = 0.0,
204
+ num_layers: int = 1,
205
+ resnet_eps: float = 1e-6,
206
+ resnet_time_scale_shift: str = "default",
207
+ resnet_act_fn: str = "swish",
208
+ resnet_groups: int = 32,
209
+ resnet_pre_norm: bool = True,
210
+ output_scale_factor: float = 1.0,
211
+ add_downsample: bool = True,
212
+ downsample_padding: int = 1,
213
+ ):
214
+ super().__init__()
215
+ resnets = []
216
+
217
+ for i in range(num_layers):
218
+ # in_channels = in_channels if i == 0 else out_channels
219
+ resnets.append(
220
+ # ResnetBlock2D(
221
+ # in_channels=in_channels,
222
+ # out_channels=out_channels,
223
+ # temb_channels=temb_channels,
224
+ # eps=resnet_eps,
225
+ # groups=resnet_groups,
226
+ # dropout=dropout,
227
+ # time_embedding_norm=resnet_time_scale_shift,
228
+ # non_linearity=resnet_act_fn,
229
+ # output_scale_factor=output_scale_factor,
230
+ # pre_norm=resnet_pre_norm,
231
+ BasicBlock(
232
+ in_channels=in_channels,
233
+ out_channels=out_channels,
234
+ temb_channels=temb_channels,
235
+ eps=resnet_eps,
236
+ groups=resnet_groups,
237
+ dropout=dropout,
238
+ time_embedding_norm=resnet_time_scale_shift,
239
+ non_linearity=resnet_act_fn,
240
+ output_scale_factor=output_scale_factor,
241
+ pre_norm=resnet_pre_norm,
242
+ ) if i == num_layers - 1 else \
243
+ IdentityModule()
244
+ )
245
+
246
+ self.resnets = nn.ModuleList(resnets)
247
+
248
+ if add_downsample:
249
+ self.downsamplers = nn.ModuleList(
250
+ [
251
+ # Downsample2D(
252
+ # out_channels,
253
+ # use_conv=True,
254
+ # out_channels=out_channels,
255
+ # padding=downsample_padding,
256
+ # name="op",
257
+ # )
258
+ BasicBlock(
259
+ in_channels=out_channels,
260
+ out_channels=out_channels,
261
+ temb_channels=temb_channels,
262
+ stride=2,
263
+ eps=resnet_eps,
264
+ groups=resnet_groups,
265
+ dropout=dropout,
266
+ time_embedding_norm=resnet_time_scale_shift,
267
+ non_linearity=resnet_act_fn,
268
+ output_scale_factor=output_scale_factor,
269
+ pre_norm=resnet_pre_norm,
270
+ )
271
+ ]
272
+ )
273
+ else:
274
+ self.downsamplers = None
275
+
276
+ self.gradient_checkpointing = False
277
+
278
+ def forward(
279
+ self,
280
+ hidden_states: torch.FloatTensor,
281
+ temb: Optional[torch.FloatTensor] = None,
282
+ ) -> Union[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
283
+ output_states = ()
284
+
285
+ for resnet in self.resnets:
286
+ hidden_states = resnet(hidden_states, temb)
287
+ output_states += (hidden_states,)
288
+
289
+ if self.downsamplers is not None:
290
+ for downsampler in self.downsamplers:
291
+ hidden_states = downsampler(hidden_states)
292
+
293
+ output_states += (hidden_states,)
294
+
295
+ return hidden_states, output_states
296
+
297
+
298
+ class ControlProject(nn.Module):
299
+ def __init__(self, num_channels, scale=8, is_empty=False) -> None:
300
+ super().__init__()
301
+ assert scale and scale & (scale - 1) == 0
302
+ self.is_empty = is_empty
303
+ self.scale = scale
304
+ if not is_empty:
305
+ if scale > 1:
306
+ self.down_scale = nn.AvgPool2d(scale, scale)
307
+ else:
308
+ self.down_scale = nn.Identity()
309
+ self.out = nn.Conv2d(num_channels, num_channels, kernel_size=1, stride=1, bias=False)
310
+ for p in self.out.parameters():
311
+ nn.init.zeros_(p)
312
+
313
+ def forward(
314
+ self,
315
+ hidden_states: torch.FloatTensor):
316
+ if self.is_empty:
317
+ shape = list(hidden_states.shape)
318
+ shape[-2] = shape[-2] // self.scale
319
+ shape[-1] = shape[-1] // self.scale
320
+ return torch.zeros(shape).to(hidden_states)
321
+
322
+ if len(hidden_states.shape) == 5:
323
+ B, F, C, H, W = hidden_states.shape
324
+ hidden_states = rearrange(hidden_states, "B F C H W -> (B F) C H W")
325
+ hidden_states = self.down_scale(hidden_states)
326
+ hidden_states = self.out(hidden_states)
327
+ hidden_states = rearrange(hidden_states, "(B F) C H W -> B F C H W", F=F)
328
+ else:
329
+ hidden_states = self.down_scale(hidden_states)
330
+ hidden_states = self.out(hidden_states)
331
+ return hidden_states
332
+
333
+
334
+ class ControlNetModel(ModelMixin, ConfigMixin):
335
+
336
+ _supports_gradient_checkpointing = True
337
+
338
+ @register_to_config
339
+ def __init__(
340
+ self,
341
+ in_channels: List[int] = [128, 128],
342
+ out_channels: List[int] = [128, 256],
343
+ groups: List[int] = [4, 8],
344
+ time_embed_dim: int = 256,
345
+ final_out_channels: int = 320,
346
+ ):
347
+ super().__init__()
348
+
349
+ self.time_proj = Timesteps(128, True, downscale_freq_shift=0)
350
+ self.time_embedding = TimestepEmbedding(128, time_embed_dim)
351
+
352
+ self.embedding = nn.Sequential(
353
+ nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1),
354
+ nn.GroupNorm(2, 64),
355
+ nn.ReLU(),
356
+ nn.Conv2d(64, 64, kernel_size=3, padding=1),
357
+ nn.GroupNorm(2, 64),
358
+ nn.ReLU(),
359
+ nn.Conv2d(64, 128, kernel_size=3, padding=1),
360
+ nn.GroupNorm(2, 128),
361
+ nn.ReLU(),
362
+ )
363
+
364
+ self.down_res = nn.ModuleList()
365
+ self.down_sample = nn.ModuleList()
366
+ for i in range(len(in_channels)):
367
+ self.down_res.append(
368
+ ResnetBlock2D(
369
+ in_channels=in_channels[i],
370
+ out_channels=out_channels[i],
371
+ temb_channels=time_embed_dim,
372
+ groups=groups[i]
373
+ ),
374
+ )
375
+ self.down_sample.append(
376
+ Downsample2D(
377
+ out_channels[i],
378
+ use_conv=True,
379
+ out_channels=out_channels[i],
380
+ padding=1,
381
+ name="op",
382
+ )
383
+ )
384
+
385
+ self.mid_convs = nn.ModuleList()
386
+ self.mid_convs.append(nn.Sequential(
387
+ nn.Conv2d(
388
+ in_channels=out_channels[-1],
389
+ out_channels=out_channels[-1],
390
+ kernel_size=3,
391
+ stride=1,
392
+ padding=1
393
+ ),
394
+ nn.ReLU(),
395
+ nn.GroupNorm(8, out_channels[-1]),
396
+ nn.Conv2d(
397
+ in_channels=out_channels[-1],
398
+ out_channels=out_channels[-1],
399
+ kernel_size=3,
400
+ stride=1,
401
+ padding=1
402
+ ),
403
+ nn.GroupNorm(8, out_channels[-1]),
404
+ ))
405
+ self.mid_convs.append(
406
+ nn.Conv2d(
407
+ in_channels=out_channels[-1],
408
+ out_channels=final_out_channels,
409
+ kernel_size=1,
410
+ stride=1,
411
+ ))
412
+ self.scale = 1.0 # nn.Parameter(torch.tensor(1.))
413
+
414
+ def _set_gradient_checkpointing(self, module, value=False):
415
+ if hasattr(module, "gradient_checkpointing"):
416
+ module.gradient_checkpointing = value
417
+
418
+ # Copied from diffusers.models.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
419
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
420
+ """
421
+ Sets the attention processor to use [feed forward
422
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
423
+
424
+ Parameters:
425
+ chunk_size (`int`, *optional*):
426
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
427
+ over each tensor of dim=`dim`.
428
+ dim (`int`, *optional*, defaults to `0`):
429
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
430
+ or dim=1 (sequence length).
431
+ """
432
+ if dim not in [0, 1]:
433
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
434
+
435
+ # By default chunk size is 1
436
+ chunk_size = chunk_size or 1
437
+
438
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
439
+ if hasattr(module, "set_chunk_feed_forward"):
440
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
441
+
442
+ for child in module.children():
443
+ fn_recursive_feed_forward(child, chunk_size, dim)
444
+
445
+ for module in self.children():
446
+ fn_recursive_feed_forward(module, chunk_size, dim)
447
+
448
+ def forward(
449
+ self,
450
+ sample: torch.FloatTensor,
451
+ timestep: Union[torch.Tensor, float, int],
452
+ ) -> Union[ControlNetOutput, Tuple]:
453
+
454
+ timesteps = timestep
455
+ if not torch.is_tensor(timesteps):
456
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
457
+ # This would be a good case for the `match` statement (Python 3.10+)
458
+ is_mps = sample.device.type == "mps"
459
+ if isinstance(timestep, float):
460
+ dtype = torch.float32 if is_mps else torch.float64
461
+ else:
462
+ dtype = torch.int32 if is_mps else torch.int64
463
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
464
+ elif len(timesteps.shape) == 0:
465
+ timesteps = timesteps[None].to(sample.device)
466
+
467
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
468
+ batch_size = sample.shape[0]
469
+ timesteps = timesteps.expand(batch_size)
470
+ t_emb = self.time_proj(timesteps)
471
+ # `Timesteps` does not contain any weights and will always return f32 tensors
472
+ # but time_embedding might actually be running in fp16. so we need to cast here.
473
+ # there might be better ways to encapsulate this.
474
+ t_emb = t_emb.to(dtype=sample.dtype)
475
+ emb_batch = self.time_embedding(t_emb)
476
+
477
+ # Repeat the embeddings num_video_frames times
478
+ # emb: [batch, channels] -> [batch * frames, channels]
479
+ emb = emb_batch
480
+ sample = self.embedding(sample)
481
+ for res, downsample in zip(self.down_res, self.down_sample):
482
+ sample = res(sample, emb)
483
+ sample = downsample(sample, emb)
484
+ sample = self.mid_convs[0](sample) + sample
485
+ sample = self.mid_convs[1](sample)
486
+ return {
487
+ 'out': sample,
488
+ 'scale': self.scale,
489
+ }
490
+
491
+
492
+ def zero_module(module):
493
+ for p in module.parameters():
494
+ nn.init.zeros_(p)
495
+ return module
models/unet.py ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
23
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin
24
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
25
+ from diffusers.models.activations import get_activation
26
+ from diffusers.models.attention_processor import (
27
+ ADDED_KV_ATTENTION_PROCESSORS,
28
+ CROSS_ATTENTION_PROCESSORS,
29
+ Attention,
30
+ AttentionProcessor,
31
+ AttnAddedKVProcessor,
32
+ AttnProcessor,
33
+ )
34
+ from diffusers.models.embeddings import (
35
+ GaussianFourierProjection,
36
+ GLIGENTextBoundingboxProjection,
37
+ ImageHintTimeEmbedding,
38
+ ImageProjection,
39
+ ImageTimeEmbedding,
40
+ TextImageProjection,
41
+ TextImageTimeEmbedding,
42
+ TextTimeEmbedding,
43
+ TimestepEmbedding,
44
+ Timesteps,
45
+ )
46
+ from diffusers.models.modeling_utils import ModelMixin
47
+ from diffusers.models.unets.unet_2d_blocks import (
48
+ get_down_block,
49
+ get_mid_block,
50
+ get_up_block,
51
+ )
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ UNET_CONFIG = {
57
+ "_class_name": "UNet2DConditionModel",
58
+ "_diffusers_version": "0.19.0.dev0",
59
+ "act_fn": "silu",
60
+ "addition_embed_type": "text_time",
61
+ "addition_embed_type_num_heads": 64,
62
+ "addition_time_embed_dim": 256,
63
+ "attention_head_dim": [
64
+ 5,
65
+ 10,
66
+ 20
67
+ ],
68
+ "block_out_channels": [
69
+ 320,
70
+ 640,
71
+ 1280
72
+ ],
73
+ "center_input_sample": False,
74
+ "class_embed_type": None,
75
+ "class_embeddings_concat": False,
76
+ "conv_in_kernel": 3,
77
+ "conv_out_kernel": 3,
78
+ "cross_attention_dim": 2048,
79
+ "cross_attention_norm": None,
80
+ "down_block_types": [
81
+ "DownBlock2D",
82
+ "CrossAttnDownBlock2D",
83
+ "CrossAttnDownBlock2D"
84
+ ],
85
+ "downsample_padding": 1,
86
+ "dual_cross_attention": False,
87
+ "encoder_hid_dim": None,
88
+ "encoder_hid_dim_type": None,
89
+ "flip_sin_to_cos": True,
90
+ "freq_shift": 0,
91
+ "in_channels": 4,
92
+ "layers_per_block": 2,
93
+ "mid_block_only_cross_attention": None,
94
+ "mid_block_scale_factor": 1,
95
+ "mid_block_type": "UNetMidBlock2DCrossAttn",
96
+ "norm_eps": 1e-05,
97
+ "norm_num_groups": 32,
98
+ "num_attention_heads": None,
99
+ "num_class_embeds": None,
100
+ "only_cross_attention": False,
101
+ "out_channels": 4,
102
+ "projection_class_embeddings_input_dim": 2816,
103
+ "resnet_out_scale_factor": 1.0,
104
+ "resnet_skip_time_act": False,
105
+ "resnet_time_scale_shift": "default",
106
+ "sample_size": 128,
107
+ "time_cond_proj_dim": None,
108
+ "time_embedding_act_fn": None,
109
+ "time_embedding_dim": None,
110
+ "time_embedding_type": "positional",
111
+ "timestep_post_act": None,
112
+ "transformer_layers_per_block": [
113
+ 1,
114
+ 2,
115
+ 10
116
+ ],
117
+ "up_block_types": [
118
+ "CrossAttnUpBlock2D",
119
+ "CrossAttnUpBlock2D",
120
+ "UpBlock2D"
121
+ ],
122
+ "upcast_attention": None,
123
+ "use_linear_projection": True
124
+ }
125
+
126
+
127
+ @dataclass
128
+ class UNet2DConditionOutput(BaseOutput):
129
+ """
130
+ The output of [`UNet2DConditionModel`].
131
+
132
+ Args:
133
+ sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
134
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
135
+ """
136
+
137
+ sample: torch.Tensor = None
138
+
139
+
140
+ class UNet2DConditionModel(
141
+ ModelMixin, ConfigMixin, FromOriginalModelMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin
142
+ ):
143
+ r"""
144
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
145
+ shaped output.
146
+
147
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
148
+ for all models (such as downloading or saving).
149
+
150
+ Parameters:
151
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
152
+ Height and width of input/output sample.
153
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
154
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
155
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
156
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
157
+ Whether to flip the sin to cos in the time embedding.
158
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
159
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
160
+ The tuple of downsample blocks to use.
161
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
162
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
163
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
164
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
165
+ The tuple of upsample blocks to use.
166
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
167
+ Whether to include self-attention in the basic transformer blocks, see
168
+ [`~models.attention.BasicTransformerBlock`].
169
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
170
+ The tuple of output channels for each block.
171
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
172
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
173
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
174
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
175
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
176
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
177
+ If `None`, normalization and activation layers is skipped in post-processing.
178
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
179
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
180
+ The dimension of the cross attention features.
181
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
182
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
183
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
184
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
185
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
186
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
187
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
188
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
189
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
190
+ encoder_hid_dim (`int`, *optional*, defaults to None):
191
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
192
+ dimension to `cross_attention_dim`.
193
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
194
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
195
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
196
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
197
+ num_attention_heads (`int`, *optional*):
198
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
199
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
200
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
201
+ class_embed_type (`str`, *optional*, defaults to `None`):
202
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
203
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
204
+ addition_embed_type (`str`, *optional*, defaults to `None`):
205
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
206
+ "text". "text" will use the `TextTimeEmbedding` layer.
207
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
208
+ Dimension for the timestep embeddings.
209
+ num_class_embeds (`int`, *optional*, defaults to `None`):
210
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
211
+ class conditioning with `class_embed_type` equal to `None`.
212
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
213
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
214
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
215
+ An optional override for the dimension of the projected time embedding.
216
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
217
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
218
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
219
+ timestep_post_act (`str`, *optional*, defaults to `None`):
220
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
221
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
222
+ The dimension of `cond_proj` layer in the timestep embedding.
223
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
224
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
225
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
226
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
227
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
228
+ embeddings with the class embeddings.
229
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
230
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
231
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
232
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
233
+ otherwise.
234
+ """
235
+
236
+ _supports_gradient_checkpointing = True
237
+ _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
238
+
239
+ @register_to_config
240
+ def __init__(
241
+ self,
242
+ sample_size: Optional[int] = None,
243
+ in_channels: int = 4,
244
+ out_channels: int = 4,
245
+ center_input_sample: bool = False,
246
+ flip_sin_to_cos: bool = True,
247
+ freq_shift: int = 0,
248
+ down_block_types: Tuple[str] = (
249
+ "CrossAttnDownBlock2D",
250
+ "CrossAttnDownBlock2D",
251
+ "CrossAttnDownBlock2D",
252
+ "DownBlock2D",
253
+ ),
254
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
255
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
256
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
257
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
258
+ layers_per_block: Union[int, Tuple[int]] = 2,
259
+ downsample_padding: int = 1,
260
+ mid_block_scale_factor: float = 1,
261
+ dropout: float = 0.0,
262
+ act_fn: str = "silu",
263
+ norm_num_groups: Optional[int] = 32,
264
+ norm_eps: float = 1e-5,
265
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
266
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
267
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
268
+ encoder_hid_dim: Optional[int] = None,
269
+ encoder_hid_dim_type: Optional[str] = None,
270
+ attention_head_dim: Union[int, Tuple[int]] = 8,
271
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
272
+ dual_cross_attention: bool = False,
273
+ use_linear_projection: bool = False,
274
+ class_embed_type: Optional[str] = None,
275
+ addition_embed_type: Optional[str] = None,
276
+ addition_time_embed_dim: Optional[int] = None,
277
+ num_class_embeds: Optional[int] = None,
278
+ upcast_attention: bool = False,
279
+ resnet_time_scale_shift: str = "default",
280
+ resnet_skip_time_act: bool = False,
281
+ resnet_out_scale_factor: float = 1.0,
282
+ time_embedding_type: str = "positional",
283
+ time_embedding_dim: Optional[int] = None,
284
+ time_embedding_act_fn: Optional[str] = None,
285
+ timestep_post_act: Optional[str] = None,
286
+ time_cond_proj_dim: Optional[int] = None,
287
+ conv_in_kernel: int = 3,
288
+ conv_out_kernel: int = 3,
289
+ projection_class_embeddings_input_dim: Optional[int] = None,
290
+ attention_type: str = "default",
291
+ class_embeddings_concat: bool = False,
292
+ mid_block_only_cross_attention: Optional[bool] = None,
293
+ cross_attention_norm: Optional[str] = None,
294
+ addition_embed_type_num_heads: int = 64,
295
+ ):
296
+ super().__init__()
297
+
298
+ self.sample_size = sample_size
299
+
300
+ if num_attention_heads is not None:
301
+ raise ValueError(
302
+ "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
303
+ )
304
+
305
+ # If `num_attention_heads` is not defined (which is the case for most models)
306
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
307
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
308
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
309
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
310
+ # which is why we correct for the naming here.
311
+ num_attention_heads = num_attention_heads or attention_head_dim
312
+
313
+ # Check inputs
314
+ self._check_config(
315
+ down_block_types=down_block_types,
316
+ up_block_types=up_block_types,
317
+ only_cross_attention=only_cross_attention,
318
+ block_out_channels=block_out_channels,
319
+ layers_per_block=layers_per_block,
320
+ cross_attention_dim=cross_attention_dim,
321
+ transformer_layers_per_block=transformer_layers_per_block,
322
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
323
+ attention_head_dim=attention_head_dim,
324
+ num_attention_heads=num_attention_heads,
325
+ )
326
+
327
+ # input
328
+ conv_in_padding = (conv_in_kernel - 1) // 2
329
+ self.conv_in = nn.Conv2d(
330
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
331
+ )
332
+
333
+ # time
334
+ time_embed_dim, timestep_input_dim = self._set_time_proj(
335
+ time_embedding_type,
336
+ block_out_channels=block_out_channels,
337
+ flip_sin_to_cos=flip_sin_to_cos,
338
+ freq_shift=freq_shift,
339
+ time_embedding_dim=time_embedding_dim,
340
+ )
341
+
342
+ self.time_embedding = TimestepEmbedding(
343
+ timestep_input_dim,
344
+ time_embed_dim,
345
+ act_fn=act_fn,
346
+ post_act_fn=timestep_post_act,
347
+ cond_proj_dim=time_cond_proj_dim,
348
+ )
349
+
350
+ self._set_encoder_hid_proj(
351
+ encoder_hid_dim_type,
352
+ cross_attention_dim=cross_attention_dim,
353
+ encoder_hid_dim=encoder_hid_dim,
354
+ )
355
+
356
+ # class embedding
357
+ self._set_class_embedding(
358
+ class_embed_type,
359
+ act_fn=act_fn,
360
+ num_class_embeds=num_class_embeds,
361
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
362
+ time_embed_dim=time_embed_dim,
363
+ timestep_input_dim=timestep_input_dim,
364
+ )
365
+
366
+ self._set_add_embedding(
367
+ addition_embed_type,
368
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
369
+ addition_time_embed_dim=addition_time_embed_dim,
370
+ cross_attention_dim=cross_attention_dim,
371
+ encoder_hid_dim=encoder_hid_dim,
372
+ flip_sin_to_cos=flip_sin_to_cos,
373
+ freq_shift=freq_shift,
374
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
375
+ time_embed_dim=time_embed_dim,
376
+ )
377
+
378
+ if time_embedding_act_fn is None:
379
+ self.time_embed_act = None
380
+ else:
381
+ self.time_embed_act = get_activation(time_embedding_act_fn)
382
+
383
+ self.down_blocks = nn.ModuleList([])
384
+ self.up_blocks = nn.ModuleList([])
385
+
386
+ if isinstance(only_cross_attention, bool):
387
+ if mid_block_only_cross_attention is None:
388
+ mid_block_only_cross_attention = only_cross_attention
389
+
390
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
391
+
392
+ if mid_block_only_cross_attention is None:
393
+ mid_block_only_cross_attention = False
394
+
395
+ if isinstance(num_attention_heads, int):
396
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
397
+
398
+ if isinstance(attention_head_dim, int):
399
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
400
+
401
+ if isinstance(cross_attention_dim, int):
402
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
403
+
404
+ if isinstance(layers_per_block, int):
405
+ layers_per_block = [layers_per_block] * len(down_block_types)
406
+
407
+ if isinstance(transformer_layers_per_block, int):
408
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
409
+
410
+ if class_embeddings_concat:
411
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
412
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
413
+ # regular time embeddings
414
+ blocks_time_embed_dim = time_embed_dim * 2
415
+ else:
416
+ blocks_time_embed_dim = time_embed_dim
417
+
418
+ # down
419
+ output_channel = block_out_channels[0]
420
+ for i, down_block_type in enumerate(down_block_types):
421
+ input_channel = output_channel
422
+ output_channel = block_out_channels[i]
423
+ is_final_block = i == len(block_out_channels) - 1
424
+
425
+ down_block = get_down_block(
426
+ down_block_type,
427
+ num_layers=layers_per_block[i],
428
+ transformer_layers_per_block=transformer_layers_per_block[i],
429
+ in_channels=input_channel,
430
+ out_channels=output_channel,
431
+ temb_channels=blocks_time_embed_dim,
432
+ add_downsample=not is_final_block,
433
+ resnet_eps=norm_eps,
434
+ resnet_act_fn=act_fn,
435
+ resnet_groups=norm_num_groups,
436
+ cross_attention_dim=cross_attention_dim[i],
437
+ num_attention_heads=num_attention_heads[i],
438
+ downsample_padding=downsample_padding,
439
+ dual_cross_attention=dual_cross_attention,
440
+ use_linear_projection=use_linear_projection,
441
+ only_cross_attention=only_cross_attention[i],
442
+ upcast_attention=upcast_attention,
443
+ resnet_time_scale_shift=resnet_time_scale_shift,
444
+ attention_type=attention_type,
445
+ resnet_skip_time_act=resnet_skip_time_act,
446
+ resnet_out_scale_factor=resnet_out_scale_factor,
447
+ cross_attention_norm=cross_attention_norm,
448
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
449
+ dropout=dropout,
450
+ )
451
+ self.down_blocks.append(down_block)
452
+
453
+ # mid
454
+ self.mid_block = get_mid_block(
455
+ mid_block_type,
456
+ temb_channels=blocks_time_embed_dim,
457
+ in_channels=block_out_channels[-1],
458
+ resnet_eps=norm_eps,
459
+ resnet_act_fn=act_fn,
460
+ resnet_groups=norm_num_groups,
461
+ output_scale_factor=mid_block_scale_factor,
462
+ transformer_layers_per_block=transformer_layers_per_block[-1],
463
+ num_attention_heads=num_attention_heads[-1],
464
+ cross_attention_dim=cross_attention_dim[-1],
465
+ dual_cross_attention=dual_cross_attention,
466
+ use_linear_projection=use_linear_projection,
467
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
468
+ upcast_attention=upcast_attention,
469
+ resnet_time_scale_shift=resnet_time_scale_shift,
470
+ attention_type=attention_type,
471
+ resnet_skip_time_act=resnet_skip_time_act,
472
+ cross_attention_norm=cross_attention_norm,
473
+ attention_head_dim=attention_head_dim[-1],
474
+ dropout=dropout,
475
+ )
476
+
477
+ # count how many layers upsample the images
478
+ self.num_upsamplers = 0
479
+
480
+ # up
481
+ reversed_block_out_channels = list(reversed(block_out_channels))
482
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
483
+ reversed_layers_per_block = list(reversed(layers_per_block))
484
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
485
+ reversed_transformer_layers_per_block = (
486
+ list(reversed(transformer_layers_per_block))
487
+ if reverse_transformer_layers_per_block is None
488
+ else reverse_transformer_layers_per_block
489
+ )
490
+ only_cross_attention = list(reversed(only_cross_attention))
491
+
492
+ output_channel = reversed_block_out_channels[0]
493
+ for i, up_block_type in enumerate(up_block_types):
494
+ is_final_block = i == len(block_out_channels) - 1
495
+
496
+ prev_output_channel = output_channel
497
+ output_channel = reversed_block_out_channels[i]
498
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
499
+
500
+ # add upsample block for all BUT final layer
501
+ if not is_final_block:
502
+ add_upsample = True
503
+ self.num_upsamplers += 1
504
+ else:
505
+ add_upsample = False
506
+
507
+ up_block = get_up_block(
508
+ up_block_type,
509
+ num_layers=reversed_layers_per_block[i] + 1,
510
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
511
+ in_channels=input_channel,
512
+ out_channels=output_channel,
513
+ prev_output_channel=prev_output_channel,
514
+ temb_channels=blocks_time_embed_dim,
515
+ add_upsample=add_upsample,
516
+ resnet_eps=norm_eps,
517
+ resnet_act_fn=act_fn,
518
+ resolution_idx=i,
519
+ resnet_groups=norm_num_groups,
520
+ cross_attention_dim=reversed_cross_attention_dim[i],
521
+ num_attention_heads=reversed_num_attention_heads[i],
522
+ dual_cross_attention=dual_cross_attention,
523
+ use_linear_projection=use_linear_projection,
524
+ only_cross_attention=only_cross_attention[i],
525
+ upcast_attention=upcast_attention,
526
+ resnet_time_scale_shift=resnet_time_scale_shift,
527
+ attention_type=attention_type,
528
+ resnet_skip_time_act=resnet_skip_time_act,
529
+ resnet_out_scale_factor=resnet_out_scale_factor,
530
+ cross_attention_norm=cross_attention_norm,
531
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
532
+ dropout=dropout,
533
+ )
534
+ self.up_blocks.append(up_block)
535
+ prev_output_channel = output_channel
536
+
537
+ # out
538
+ if norm_num_groups is not None:
539
+ self.conv_norm_out = nn.GroupNorm(
540
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
541
+ )
542
+
543
+ self.conv_act = get_activation(act_fn)
544
+
545
+ else:
546
+ self.conv_norm_out = None
547
+ self.conv_act = None
548
+
549
+ conv_out_padding = (conv_out_kernel - 1) // 2
550
+ self.conv_out = nn.Conv2d(
551
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
552
+ )
553
+
554
+ self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
555
+
556
+ def _check_config(
557
+ self,
558
+ down_block_types: Tuple[str],
559
+ up_block_types: Tuple[str],
560
+ only_cross_attention: Union[bool, Tuple[bool]],
561
+ block_out_channels: Tuple[int],
562
+ layers_per_block: Union[int, Tuple[int]],
563
+ cross_attention_dim: Union[int, Tuple[int]],
564
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
565
+ reverse_transformer_layers_per_block: bool,
566
+ attention_head_dim: int,
567
+ num_attention_heads: Optional[Union[int, Tuple[int]]],
568
+ ):
569
+ if len(down_block_types) != len(up_block_types):
570
+ raise ValueError(
571
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
572
+ )
573
+
574
+ if len(block_out_channels) != len(down_block_types):
575
+ raise ValueError(
576
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
577
+ )
578
+
579
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
580
+ raise ValueError(
581
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
582
+ )
583
+
584
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
585
+ raise ValueError(
586
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
587
+ )
588
+
589
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
590
+ raise ValueError(
591
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
592
+ )
593
+
594
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
595
+ raise ValueError(
596
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
597
+ )
598
+
599
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
600
+ raise ValueError(
601
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
602
+ )
603
+ if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
604
+ for layer_number_per_block in transformer_layers_per_block:
605
+ if isinstance(layer_number_per_block, list):
606
+ raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
607
+
608
+ def _set_time_proj(
609
+ self,
610
+ time_embedding_type: str,
611
+ block_out_channels: int,
612
+ flip_sin_to_cos: bool,
613
+ freq_shift: float,
614
+ time_embedding_dim: int,
615
+ ) -> Tuple[int, int]:
616
+ if time_embedding_type == "fourier":
617
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
618
+ if time_embed_dim % 2 != 0:
619
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
620
+ self.time_proj = GaussianFourierProjection(
621
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
622
+ )
623
+ timestep_input_dim = time_embed_dim
624
+ elif time_embedding_type == "positional":
625
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
626
+
627
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
628
+ timestep_input_dim = block_out_channels[0]
629
+ else:
630
+ raise ValueError(
631
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
632
+ )
633
+
634
+ return time_embed_dim, timestep_input_dim
635
+
636
+ def _set_encoder_hid_proj(
637
+ self,
638
+ encoder_hid_dim_type: Optional[str],
639
+ cross_attention_dim: Union[int, Tuple[int]],
640
+ encoder_hid_dim: Optional[int],
641
+ ):
642
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
643
+ encoder_hid_dim_type = "text_proj"
644
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
645
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
646
+
647
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
648
+ raise ValueError(
649
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
650
+ )
651
+
652
+ if encoder_hid_dim_type == "text_proj":
653
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
654
+ elif encoder_hid_dim_type == "text_image_proj":
655
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
656
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
657
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
658
+ self.encoder_hid_proj = TextImageProjection(
659
+ text_embed_dim=encoder_hid_dim,
660
+ image_embed_dim=cross_attention_dim,
661
+ cross_attention_dim=cross_attention_dim,
662
+ )
663
+ elif encoder_hid_dim_type == "image_proj":
664
+ # Kandinsky 2.2
665
+ self.encoder_hid_proj = ImageProjection(
666
+ image_embed_dim=encoder_hid_dim,
667
+ cross_attention_dim=cross_attention_dim,
668
+ )
669
+ elif encoder_hid_dim_type is not None:
670
+ raise ValueError(
671
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
672
+ )
673
+ else:
674
+ self.encoder_hid_proj = None
675
+
676
+ def _set_class_embedding(
677
+ self,
678
+ class_embed_type: Optional[str],
679
+ act_fn: str,
680
+ num_class_embeds: Optional[int],
681
+ projection_class_embeddings_input_dim: Optional[int],
682
+ time_embed_dim: int,
683
+ timestep_input_dim: int,
684
+ ):
685
+ if class_embed_type is None and num_class_embeds is not None:
686
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
687
+ elif class_embed_type == "timestep":
688
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
689
+ elif class_embed_type == "identity":
690
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
691
+ elif class_embed_type == "projection":
692
+ if projection_class_embeddings_input_dim is None:
693
+ raise ValueError(
694
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
695
+ )
696
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
697
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
698
+ # 2. it projects from an arbitrary input dimension.
699
+ #
700
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
701
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
702
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
703
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
704
+ elif class_embed_type == "simple_projection":
705
+ if projection_class_embeddings_input_dim is None:
706
+ raise ValueError(
707
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
708
+ )
709
+ self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
710
+ else:
711
+ self.class_embedding = None
712
+
713
+ def _set_add_embedding(
714
+ self,
715
+ addition_embed_type: str,
716
+ addition_embed_type_num_heads: int,
717
+ addition_time_embed_dim: Optional[int],
718
+ flip_sin_to_cos: bool,
719
+ freq_shift: float,
720
+ cross_attention_dim: Optional[int],
721
+ encoder_hid_dim: Optional[int],
722
+ projection_class_embeddings_input_dim: Optional[int],
723
+ time_embed_dim: int,
724
+ ):
725
+ if addition_embed_type == "text":
726
+ if encoder_hid_dim is not None:
727
+ text_time_embedding_from_dim = encoder_hid_dim
728
+ else:
729
+ text_time_embedding_from_dim = cross_attention_dim
730
+
731
+ self.add_embedding = TextTimeEmbedding(
732
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
733
+ )
734
+ elif addition_embed_type == "text_image":
735
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
736
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
737
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
738
+ self.add_embedding = TextImageTimeEmbedding(
739
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
740
+ )
741
+ elif addition_embed_type == "text_time":
742
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
743
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
744
+ elif addition_embed_type == "image":
745
+ # Kandinsky 2.2
746
+ self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
747
+ elif addition_embed_type == "image_hint":
748
+ # Kandinsky 2.2 ControlNet
749
+ self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
750
+ elif addition_embed_type is not None:
751
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
752
+
753
+ def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
754
+ if attention_type in ["gated", "gated-text-image"]:
755
+ positive_len = 768
756
+ if isinstance(cross_attention_dim, int):
757
+ positive_len = cross_attention_dim
758
+ elif isinstance(cross_attention_dim, (list, tuple)):
759
+ positive_len = cross_attention_dim[0]
760
+
761
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
762
+ self.position_net = GLIGENTextBoundingboxProjection(
763
+ positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
764
+ )
765
+
766
+ @property
767
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
768
+ r"""
769
+ Returns:
770
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
771
+ indexed by its weight name.
772
+ """
773
+ # set recursively
774
+ processors = {}
775
+
776
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
777
+ if hasattr(module, "get_processor"):
778
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
779
+
780
+ for sub_name, child in module.named_children():
781
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
782
+
783
+ return processors
784
+
785
+ for name, module in self.named_children():
786
+ fn_recursive_add_processors(name, module, processors)
787
+
788
+ return processors
789
+
790
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
791
+ r"""
792
+ Sets the attention processor to use to compute attention.
793
+
794
+ Parameters:
795
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
796
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
797
+ for **all** `Attention` layers.
798
+
799
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
800
+ processor. This is strongly recommended when setting trainable attention processors.
801
+
802
+ """
803
+ count = len(self.attn_processors.keys())
804
+
805
+ if isinstance(processor, dict) and len(processor) != count:
806
+ raise ValueError(
807
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
808
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
809
+ )
810
+
811
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
812
+ if hasattr(module, "set_processor"):
813
+ if not isinstance(processor, dict):
814
+ module.set_processor(processor)
815
+ else:
816
+ module.set_processor(processor.pop(f"{name}.processor"))
817
+
818
+ for sub_name, child in module.named_children():
819
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
820
+
821
+ for name, module in self.named_children():
822
+ fn_recursive_attn_processor(name, module, processor)
823
+
824
+ def set_default_attn_processor(self):
825
+ """
826
+ Disables custom attention processors and sets the default attention implementation.
827
+ """
828
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
829
+ processor = AttnAddedKVProcessor()
830
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
831
+ processor = AttnProcessor()
832
+ else:
833
+ raise ValueError(
834
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
835
+ )
836
+
837
+ self.set_attn_processor(processor)
838
+
839
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
840
+ r"""
841
+ Enable sliced attention computation.
842
+
843
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
844
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
845
+
846
+ Args:
847
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
848
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
849
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
850
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
851
+ must be a multiple of `slice_size`.
852
+ """
853
+ sliceable_head_dims = []
854
+
855
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
856
+ if hasattr(module, "set_attention_slice"):
857
+ sliceable_head_dims.append(module.sliceable_head_dim)
858
+
859
+ for child in module.children():
860
+ fn_recursive_retrieve_sliceable_dims(child)
861
+
862
+ # retrieve number of attention layers
863
+ for module in self.children():
864
+ fn_recursive_retrieve_sliceable_dims(module)
865
+
866
+ num_sliceable_layers = len(sliceable_head_dims)
867
+
868
+ if slice_size == "auto":
869
+ # half the attention head size is usually a good trade-off between
870
+ # speed and memory
871
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
872
+ elif slice_size == "max":
873
+ # make smallest slice possible
874
+ slice_size = num_sliceable_layers * [1]
875
+
876
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
877
+
878
+ if len(slice_size) != len(sliceable_head_dims):
879
+ raise ValueError(
880
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
881
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
882
+ )
883
+
884
+ for i in range(len(slice_size)):
885
+ size = slice_size[i]
886
+ dim = sliceable_head_dims[i]
887
+ if size is not None and size > dim:
888
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
889
+
890
+ # Recursively walk through all the children.
891
+ # Any children which exposes the set_attention_slice method
892
+ # gets the message
893
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
894
+ if hasattr(module, "set_attention_slice"):
895
+ module.set_attention_slice(slice_size.pop())
896
+
897
+ for child in module.children():
898
+ fn_recursive_set_attention_slice(child, slice_size)
899
+
900
+ reversed_slice_size = list(reversed(slice_size))
901
+ for module in self.children():
902
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
903
+
904
+ def _set_gradient_checkpointing(self, module, value=False):
905
+ if hasattr(module, "gradient_checkpointing"):
906
+ module.gradient_checkpointing = value
907
+
908
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
909
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
910
+
911
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
912
+
913
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
914
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
915
+
916
+ Args:
917
+ s1 (`float`):
918
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
919
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
920
+ s2 (`float`):
921
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
922
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
923
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
924
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
925
+ """
926
+ for i, upsample_block in enumerate(self.up_blocks):
927
+ setattr(upsample_block, "s1", s1)
928
+ setattr(upsample_block, "s2", s2)
929
+ setattr(upsample_block, "b1", b1)
930
+ setattr(upsample_block, "b2", b2)
931
+
932
+ def disable_freeu(self):
933
+ """Disables the FreeU mechanism."""
934
+ freeu_keys = {"s1", "s2", "b1", "b2"}
935
+ for i, upsample_block in enumerate(self.up_blocks):
936
+ for k in freeu_keys:
937
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
938
+ setattr(upsample_block, k, None)
939
+
940
+ def fuse_qkv_projections(self):
941
+ """
942
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
943
+ are fused. For cross-attention modules, key and value projection matrices are fused.
944
+
945
+ <Tip warning={true}>
946
+
947
+ This API is 🧪 experimental.
948
+
949
+ </Tip>
950
+ """
951
+ self.original_attn_processors = None
952
+
953
+ for _, attn_processor in self.attn_processors.items():
954
+ if "Added" in str(attn_processor.__class__.__name__):
955
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
956
+
957
+ self.original_attn_processors = self.attn_processors
958
+
959
+ for module in self.modules():
960
+ if isinstance(module, Attention):
961
+ module.fuse_projections(fuse=True)
962
+
963
+ def unfuse_qkv_projections(self):
964
+ """Disables the fused QKV projection if enabled.
965
+
966
+ <Tip warning={true}>
967
+
968
+ This API is 🧪 experimental.
969
+
970
+ </Tip>
971
+
972
+ """
973
+ if self.original_attn_processors is not None:
974
+ self.set_attn_processor(self.original_attn_processors)
975
+
976
+ def get_time_embed(
977
+ self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
978
+ ) -> Optional[torch.Tensor]:
979
+ timesteps = timestep
980
+ if not torch.is_tensor(timesteps):
981
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
982
+ # This would be a good case for the `match` statement (Python 3.10+)
983
+ is_mps = sample.device.type == "mps"
984
+ if isinstance(timestep, float):
985
+ dtype = torch.float32 if is_mps else torch.float64
986
+ else:
987
+ dtype = torch.int32 if is_mps else torch.int64
988
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
989
+ elif len(timesteps.shape) == 0:
990
+ timesteps = timesteps[None].to(sample.device)
991
+
992
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
993
+ timesteps = timesteps.expand(sample.shape[0])
994
+
995
+ t_emb = self.time_proj(timesteps)
996
+ # `Timesteps` does not contain any weights and will always return f32 tensors
997
+ # but time_embedding might actually be running in fp16. so we need to cast here.
998
+ # there might be better ways to encapsulate this.
999
+ t_emb = t_emb.to(dtype=sample.dtype)
1000
+ return t_emb
1001
+
1002
+ def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
1003
+ class_emb = None
1004
+ if self.class_embedding is not None:
1005
+ if class_labels is None:
1006
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
1007
+
1008
+ if self.config.class_embed_type == "timestep":
1009
+ class_labels = self.time_proj(class_labels)
1010
+
1011
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1012
+ # there might be better ways to encapsulate this.
1013
+ class_labels = class_labels.to(dtype=sample.dtype)
1014
+
1015
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
1016
+ return class_emb
1017
+
1018
+ def get_aug_embed(
1019
+ self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1020
+ ) -> Optional[torch.Tensor]:
1021
+ aug_emb = None
1022
+ if self.config.addition_embed_type == "text":
1023
+ aug_emb = self.add_embedding(encoder_hidden_states)
1024
+ elif self.config.addition_embed_type == "text_image":
1025
+ # Kandinsky 2.1 - style
1026
+ if "image_embeds" not in added_cond_kwargs:
1027
+ raise ValueError(
1028
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
1029
+ )
1030
+
1031
+ image_embs = added_cond_kwargs.get("image_embeds")
1032
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
1033
+ aug_emb = self.add_embedding(text_embs, image_embs)
1034
+ elif self.config.addition_embed_type == "text_time":
1035
+ # SDXL - style
1036
+ if "text_embeds" not in added_cond_kwargs:
1037
+ raise ValueError(
1038
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
1039
+ )
1040
+ text_embeds = added_cond_kwargs.get("text_embeds")
1041
+ if "time_ids" not in added_cond_kwargs:
1042
+ raise ValueError(
1043
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
1044
+ )
1045
+ time_ids = added_cond_kwargs.get("time_ids")
1046
+ time_embeds = self.add_time_proj(time_ids.flatten())
1047
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1048
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1049
+ add_embeds = add_embeds.to(emb.dtype)
1050
+ aug_emb = self.add_embedding(add_embeds)
1051
+ elif self.config.addition_embed_type == "image":
1052
+ # Kandinsky 2.2 - style
1053
+ if "image_embeds" not in added_cond_kwargs:
1054
+ raise ValueError(
1055
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
1056
+ )
1057
+ image_embs = added_cond_kwargs.get("image_embeds")
1058
+ aug_emb = self.add_embedding(image_embs)
1059
+ elif self.config.addition_embed_type == "image_hint":
1060
+ # Kandinsky 2.2 - style
1061
+ if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1062
+ raise ValueError(
1063
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
1064
+ )
1065
+ image_embs = added_cond_kwargs.get("image_embeds")
1066
+ hint = added_cond_kwargs.get("hint")
1067
+ aug_emb = self.add_embedding(image_embs, hint)
1068
+ return aug_emb
1069
+
1070
+ def process_encoder_hidden_states(
1071
+ self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1072
+ ) -> torch.Tensor:
1073
+ if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1074
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1075
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1076
+ # Kandinsky 2.1 - style
1077
+ if "image_embeds" not in added_cond_kwargs:
1078
+ raise ValueError(
1079
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1080
+ )
1081
+
1082
+ image_embeds = added_cond_kwargs.get("image_embeds")
1083
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1084
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1085
+ # Kandinsky 2.2 - style
1086
+ if "image_embeds" not in added_cond_kwargs:
1087
+ raise ValueError(
1088
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1089
+ )
1090
+ image_embeds = added_cond_kwargs.get("image_embeds")
1091
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1092
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1093
+ if "image_embeds" not in added_cond_kwargs:
1094
+ raise ValueError(
1095
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1096
+ )
1097
+ image_embeds = added_cond_kwargs.get("image_embeds")
1098
+ image_embeds = self.encoder_hid_proj(image_embeds)
1099
+ encoder_hidden_states = (encoder_hidden_states, image_embeds)
1100
+ return encoder_hidden_states
1101
+
1102
+ def forward(
1103
+ self,
1104
+ sample: torch.Tensor,
1105
+ timestep: Union[torch.Tensor, float, int],
1106
+ encoder_hidden_states: torch.Tensor,
1107
+ class_labels: Optional[torch.Tensor] = None,
1108
+ timestep_cond: Optional[torch.Tensor] = None,
1109
+ attention_mask: Optional[torch.Tensor] = None,
1110
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1111
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1112
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1113
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
1114
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1115
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1116
+ controls: Optional[Dict[str, torch.Tensor]] = None,
1117
+ return_dict: bool = True,
1118
+ ) -> Union[UNet2DConditionOutput, Tuple]:
1119
+ r"""
1120
+ The [`UNet2DConditionModel`] forward method.
1121
+
1122
+ Args:
1123
+ sample (`torch.Tensor`):
1124
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
1125
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
1126
+ encoder_hidden_states (`torch.Tensor`):
1127
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1128
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1129
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1130
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1131
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1132
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
1133
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1134
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1135
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1136
+ negative values to the attention scores corresponding to "discard" tokens.
1137
+ cross_attention_kwargs (`dict`, *optional*):
1138
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1139
+ `self.processor` in
1140
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1141
+ added_cond_kwargs: (`dict`, *optional*):
1142
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1143
+ are passed along to the UNet blocks.
1144
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1145
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
1146
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
1147
+ A tensor that if specified is added to the residual of the middle unet block.
1148
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1149
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1150
+ encoder_attention_mask (`torch.Tensor`):
1151
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1152
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1153
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
1154
+ return_dict (`bool`, *optional*, defaults to `True`):
1155
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1156
+ tuple.
1157
+
1158
+ Returns:
1159
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1160
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1161
+ otherwise a `tuple` is returned where the first element is the sample tensor.
1162
+ """
1163
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
1164
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1165
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
1166
+ # on the fly if necessary.
1167
+ default_overall_up_factor = 2**self.num_upsamplers
1168
+
1169
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1170
+ forward_upsample_size = False
1171
+ upsample_size = None
1172
+
1173
+ for dim in sample.shape[-2:]:
1174
+ if dim % default_overall_up_factor != 0:
1175
+ # Forward upsample size to force interpolation output size.
1176
+ forward_upsample_size = True
1177
+ break
1178
+
1179
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1180
+ # expects mask of shape:
1181
+ # [batch, key_tokens]
1182
+ # adds singleton query_tokens dimension:
1183
+ # [batch, 1, key_tokens]
1184
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1185
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1186
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1187
+ if attention_mask is not None:
1188
+ # assume that mask is expressed as:
1189
+ # (1 = keep, 0 = discard)
1190
+ # convert mask into a bias that can be added to attention scores:
1191
+ # (keep = +0, discard = -10000.0)
1192
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1193
+ attention_mask = attention_mask.unsqueeze(1)
1194
+
1195
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
1196
+ if encoder_attention_mask is not None:
1197
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1198
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1199
+
1200
+ # 0. center input if necessary
1201
+ if self.config.center_input_sample:
1202
+ sample = 2 * sample - 1.0
1203
+
1204
+ # 1. time
1205
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1206
+ emb = self.time_embedding(t_emb, timestep_cond)
1207
+ aug_emb = None
1208
+
1209
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1210
+ if class_emb is not None:
1211
+ if self.config.class_embeddings_concat:
1212
+ emb = torch.cat([emb, class_emb], dim=-1)
1213
+ else:
1214
+ emb = emb + class_emb
1215
+
1216
+ aug_emb = self.get_aug_embed(
1217
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1218
+ )
1219
+ if self.config.addition_embed_type == "image_hint":
1220
+ aug_emb, hint = aug_emb
1221
+ sample = torch.cat([sample, hint], dim=1)
1222
+
1223
+ emb = emb + aug_emb if aug_emb is not None else emb
1224
+
1225
+ if self.time_embed_act is not None:
1226
+ emb = self.time_embed_act(emb)
1227
+
1228
+ encoder_hidden_states = self.process_encoder_hidden_states(
1229
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1230
+ )
1231
+
1232
+ # 2. pre-process
1233
+ sample = self.conv_in(sample)
1234
+
1235
+ # 2.5 GLIGEN position net
1236
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1237
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1238
+ gligen_args = cross_attention_kwargs.pop("gligen")
1239
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1240
+
1241
+ # 3. down
1242
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1243
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1244
+ if cross_attention_kwargs is not None:
1245
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1246
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1247
+ else:
1248
+ lora_scale = 1.0
1249
+
1250
+ if USE_PEFT_BACKEND:
1251
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1252
+ scale_lora_layers(self, lora_scale)
1253
+
1254
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1255
+ is_controlnext = controls is not None
1256
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1257
+ is_adapter = down_intrablock_additional_residuals is not None
1258
+ # maintain backward compatibility for legacy usage, where
1259
+ # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1260
+ # but can only use one or the other
1261
+ if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
1262
+ deprecate(
1263
+ "T2I should not use down_block_additional_residuals",
1264
+ "1.3.0",
1265
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1266
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1267
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1268
+ standard_warn=False,
1269
+ )
1270
+ down_intrablock_additional_residuals = down_block_additional_residuals
1271
+ is_adapter = True
1272
+
1273
+ down_block_res_samples = (sample,)
1274
+
1275
+ if is_controlnext:
1276
+ scale = controls['scale']
1277
+ controls = controls['out'].to(sample)
1278
+ mean_latents, std_latents = torch.mean(sample, dim=(1, 2, 3), keepdim=True), torch.std(sample, dim=(1, 2, 3), keepdim=True)
1279
+ mean_control, std_control = torch.mean(controls, dim=(1, 2, 3), keepdim=True), torch.std(controls, dim=(1, 2, 3), keepdim=True)
1280
+ controls = (controls - mean_control) * (std_latents / (std_control + 1e-12)) + mean_latents
1281
+ controls = nn.functional.adaptive_avg_pool2d(controls, sample.shape[-2:])
1282
+ sample = sample + controls * scale
1283
+
1284
+ for i, downsample_block in enumerate(self.down_blocks):
1285
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1286
+ # For t2i-adapter CrossAttnDownBlock2D
1287
+ additional_residuals = {}
1288
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1289
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1290
+
1291
+ sample, res_samples = downsample_block(
1292
+ hidden_states=sample,
1293
+ temb=emb,
1294
+ encoder_hidden_states=encoder_hidden_states,
1295
+ attention_mask=attention_mask,
1296
+ cross_attention_kwargs=cross_attention_kwargs,
1297
+ encoder_attention_mask=encoder_attention_mask,
1298
+ **additional_residuals,
1299
+ )
1300
+ else:
1301
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1302
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1303
+ sample += down_intrablock_additional_residuals.pop(0)
1304
+
1305
+ down_block_res_samples += res_samples
1306
+
1307
+ if is_controlnet:
1308
+ new_down_block_res_samples = ()
1309
+
1310
+ for down_block_res_sample, down_block_additional_residual in zip(
1311
+ down_block_res_samples, down_block_additional_residuals
1312
+ ):
1313
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
1314
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1315
+
1316
+ down_block_res_samples = new_down_block_res_samples
1317
+
1318
+ # 4. mid
1319
+ if self.mid_block is not None:
1320
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1321
+ sample = self.mid_block(
1322
+ sample,
1323
+ emb,
1324
+ encoder_hidden_states=encoder_hidden_states,
1325
+ attention_mask=attention_mask,
1326
+ cross_attention_kwargs=cross_attention_kwargs,
1327
+ encoder_attention_mask=encoder_attention_mask,
1328
+ )
1329
+ else:
1330
+ sample = self.mid_block(sample, emb)
1331
+
1332
+ # To support T2I-Adapter-XL
1333
+ if (
1334
+ is_adapter
1335
+ and len(down_intrablock_additional_residuals) > 0
1336
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1337
+ ):
1338
+ sample += down_intrablock_additional_residuals.pop(0)
1339
+
1340
+ if is_controlnet:
1341
+ sample = sample + mid_block_additional_residual
1342
+
1343
+ # 5. up
1344
+ for i, upsample_block in enumerate(self.up_blocks):
1345
+ is_final_block = i == len(self.up_blocks) - 1
1346
+
1347
+ res_samples = down_block_res_samples[-len(upsample_block.resnets):]
1348
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1349
+
1350
+ # if we have not reached the final block and need to forward the
1351
+ # upsample size, we do it here
1352
+ if not is_final_block and forward_upsample_size:
1353
+ upsample_size = down_block_res_samples[-1].shape[2:]
1354
+
1355
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1356
+ sample = upsample_block(
1357
+ hidden_states=sample,
1358
+ temb=emb,
1359
+ res_hidden_states_tuple=res_samples,
1360
+ encoder_hidden_states=encoder_hidden_states,
1361
+ cross_attention_kwargs=cross_attention_kwargs,
1362
+ upsample_size=upsample_size,
1363
+ attention_mask=attention_mask,
1364
+ encoder_attention_mask=encoder_attention_mask,
1365
+ )
1366
+ else:
1367
+ sample = upsample_block(
1368
+ hidden_states=sample,
1369
+ temb=emb,
1370
+ res_hidden_states_tuple=res_samples,
1371
+ upsample_size=upsample_size,
1372
+ )
1373
+
1374
+ # 6. post-process
1375
+ if self.conv_norm_out:
1376
+ sample = self.conv_norm_out(sample)
1377
+ sample = self.conv_act(sample)
1378
+ sample = self.conv_out(sample)
1379
+
1380
+ if USE_PEFT_BACKEND:
1381
+ # remove `lora_scale` from each PEFT layer
1382
+ unscale_lora_layers(self, lora_scale)
1383
+
1384
+ if not return_dict:
1385
+ return (sample,)
1386
+
1387
+ return UNet2DConditionOutput(sample=sample)
pipeline/pipeline_controlnext.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+ from packaging import version
18
+ import torch
19
+ from transformers import (
20
+ CLIPImageProcessor,
21
+ CLIPTextModel,
22
+ CLIPTextModelWithProjection,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ )
26
+
27
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
28
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
29
+ from diffusers.loaders import (
30
+ FromSingleFileMixin,
31
+ IPAdapterMixin,
32
+ StableDiffusionXLLoraLoaderMixin,
33
+ TextualInversionLoaderMixin,
34
+ )
35
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
36
+ from diffusers.models.attention_processor import (
37
+ AttnProcessor2_0,
38
+ FusedAttnProcessor2_0,
39
+ LoRAAttnProcessor2_0,
40
+ LoRAXFormersAttnProcessor,
41
+ XFormersAttnProcessor,
42
+ )
43
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
44
+ from models.controlnet import ControlNetModel
45
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
46
+ from diffusers.schedulers import KarrasDiffusionSchedulers
47
+ from diffusers.utils import (
48
+ USE_PEFT_BACKEND,
49
+ deprecate,
50
+ is_invisible_watermark_available,
51
+ is_torch_xla_available,
52
+ logging,
53
+ replace_example_docstring,
54
+ scale_lora_layers,
55
+ unscale_lora_layers,
56
+ )
57
+ from diffusers.utils.torch_utils import randn_tensor
58
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
59
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
60
+
61
+ if is_invisible_watermark_available():
62
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
63
+
64
+ if is_torch_xla_available():
65
+ import torch_xla.core.xla_model as xm
66
+
67
+ XLA_AVAILABLE = True
68
+ else:
69
+ XLA_AVAILABLE = False
70
+
71
+
72
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
73
+
74
+ EXAMPLE_DOC_STRING = """
75
+ Examples:
76
+ ```py
77
+ >>> import torch
78
+ >>> from diffusers import StableDiffusionXLPipeline
79
+
80
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
81
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
82
+ ... )
83
+ >>> pipe = pipe.to("cuda")
84
+
85
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
86
+ >>> image = pipe(prompt).images[0]
87
+ ```
88
+ """
89
+
90
+
91
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
92
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
93
+ """
94
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
95
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
96
+ """
97
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
98
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
99
+ # rescale the results from guidance (fixes overexposure)
100
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
101
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
102
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
103
+ return noise_cfg
104
+
105
+
106
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
107
+ def retrieve_timesteps(
108
+ scheduler,
109
+ num_inference_steps: Optional[int] = None,
110
+ device: Optional[Union[str, torch.device]] = None,
111
+ timesteps: Optional[List[int]] = None,
112
+ sigmas: Optional[List[float]] = None,
113
+ **kwargs,
114
+ ):
115
+ """
116
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
117
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
118
+
119
+ Args:
120
+ scheduler (`SchedulerMixin`):
121
+ The scheduler to get timesteps from.
122
+ num_inference_steps (`int`):
123
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
124
+ must be `None`.
125
+ device (`str` or `torch.device`, *optional*):
126
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
127
+ timesteps (`List[int]`, *optional*):
128
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
129
+ `num_inference_steps` and `sigmas` must be `None`.
130
+ sigmas (`List[float]`, *optional*):
131
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
132
+ `num_inference_steps` and `timesteps` must be `None`.
133
+
134
+ Returns:
135
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
136
+ second element is the number of inference steps.
137
+ """
138
+ if timesteps is not None and sigmas is not None:
139
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
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
+ elif sigmas is not None:
151
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
152
+ if not accept_sigmas:
153
+ raise ValueError(
154
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
155
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
156
+ )
157
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
158
+ timesteps = scheduler.timesteps
159
+ num_inference_steps = len(timesteps)
160
+ else:
161
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
162
+ timesteps = scheduler.timesteps
163
+ return timesteps, num_inference_steps
164
+
165
+
166
+ class StableDiffusionXLControlNeXtPipeline(
167
+ DiffusionPipeline,
168
+ StableDiffusionMixin,
169
+ FromSingleFileMixin,
170
+ StableDiffusionXLLoraLoaderMixin,
171
+ TextualInversionLoaderMixin,
172
+ IPAdapterMixin,
173
+ ):
174
+ r"""
175
+ Pipeline for text-to-image generation using Stable Diffusion XL.
176
+
177
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
178
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
179
+
180
+ The pipeline also inherits the following loading methods:
181
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
182
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
183
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
184
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
185
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
186
+
187
+ Args:
188
+ vae ([`AutoencoderKL`]):
189
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
190
+ text_encoder ([`CLIPTextModel`]):
191
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
192
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
193
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
194
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
195
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
196
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
197
+ specifically the
198
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
199
+ variant.
200
+ tokenizer (`CLIPTokenizer`):
201
+ Tokenizer of class
202
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
203
+ tokenizer_2 (`CLIPTokenizer`):
204
+ Second Tokenizer of class
205
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
206
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
207
+ scheduler ([`SchedulerMixin`]):
208
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
209
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
210
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
211
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
212
+ `stabilityai/stable-diffusion-xl-base-1-0`.
213
+ add_watermarker (`bool`, *optional*):
214
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
215
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
216
+ watermarker will be used.
217
+ """
218
+
219
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
220
+ _optional_components = [
221
+ "tokenizer",
222
+ "tokenizer_2",
223
+ "text_encoder",
224
+ "text_encoder_2",
225
+ "image_encoder",
226
+ "feature_extractor",
227
+ ]
228
+ _callback_tensor_inputs = [
229
+ "latents",
230
+ "prompt_embeds",
231
+ "negative_prompt_embeds",
232
+ "add_text_embeds",
233
+ "add_time_ids",
234
+ "negative_pooled_prompt_embeds",
235
+ "negative_add_time_ids",
236
+ ]
237
+
238
+ def __init__(
239
+ self,
240
+ vae: AutoencoderKL,
241
+ text_encoder: CLIPTextModel,
242
+ text_encoder_2: CLIPTextModelWithProjection,
243
+ tokenizer: CLIPTokenizer,
244
+ tokenizer_2: CLIPTokenizer,
245
+ unet: UNet2DConditionModel,
246
+ scheduler: KarrasDiffusionSchedulers,
247
+ controlnet: Optional[Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel]] = None,
248
+ image_encoder: CLIPVisionModelWithProjection = None,
249
+ feature_extractor: CLIPImageProcessor = None,
250
+ force_zeros_for_empty_prompt: bool = True,
251
+ add_watermarker: Optional[bool] = None,
252
+ ):
253
+ super().__init__()
254
+
255
+ self.register_modules(
256
+ vae=vae,
257
+ text_encoder=text_encoder,
258
+ text_encoder_2=text_encoder_2,
259
+ tokenizer=tokenizer,
260
+ tokenizer_2=tokenizer_2,
261
+ unet=unet,
262
+ scheduler=scheduler,
263
+ image_encoder=image_encoder,
264
+ feature_extractor=feature_extractor,
265
+ controlnet=controlnet,
266
+ )
267
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
268
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
269
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
270
+ self.control_image_processor = VaeImageProcessor(
271
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
272
+ )
273
+
274
+ self.default_sample_size = self.unet.config.sample_size
275
+
276
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
277
+
278
+ if add_watermarker:
279
+ self.watermark = StableDiffusionXLWatermarker()
280
+ else:
281
+ self.watermark = None
282
+
283
+ def prepare_image(
284
+ self,
285
+ image,
286
+ width,
287
+ height,
288
+ batch_size,
289
+ num_images_per_prompt,
290
+ device,
291
+ dtype,
292
+ do_classifier_free_guidance=False,
293
+ guess_mode=False,
294
+ ):
295
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
296
+ image_batch_size = image.shape[0]
297
+
298
+ if image_batch_size == 1:
299
+ repeat_by = batch_size
300
+ else:
301
+ # image batch size is the same as prompt batch size
302
+ repeat_by = num_images_per_prompt
303
+
304
+ image = image.repeat_interleave(repeat_by, dim=0)
305
+
306
+ image = image.to(device=device, dtype=dtype)
307
+
308
+ if do_classifier_free_guidance and not guess_mode:
309
+ image = torch.cat([image] * 2)
310
+
311
+ return image
312
+
313
+ def encode_prompt(
314
+ self,
315
+ prompt: str,
316
+ prompt_2: Optional[str] = None,
317
+ device: Optional[torch.device] = None,
318
+ num_images_per_prompt: int = 1,
319
+ do_classifier_free_guidance: bool = True,
320
+ negative_prompt: Optional[str] = None,
321
+ negative_prompt_2: Optional[str] = None,
322
+ prompt_embeds: Optional[torch.Tensor] = None,
323
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
324
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
325
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
326
+ lora_scale: Optional[float] = None,
327
+ clip_skip: Optional[int] = None,
328
+ ):
329
+ r"""
330
+ Encodes the prompt into text encoder hidden states.
331
+
332
+ Args:
333
+ prompt (`str` or `List[str]`, *optional*):
334
+ prompt to be encoded
335
+ prompt_2 (`str` or `List[str]`, *optional*):
336
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
337
+ used in both text-encoders
338
+ device: (`torch.device`):
339
+ torch device
340
+ num_images_per_prompt (`int`):
341
+ number of images that should be generated per prompt
342
+ do_classifier_free_guidance (`bool`):
343
+ whether to use classifier free guidance or not
344
+ negative_prompt (`str` or `List[str]`, *optional*):
345
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
346
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
347
+ less than `1`).
348
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
349
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
350
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
351
+ prompt_embeds (`torch.Tensor`, *optional*):
352
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
353
+ provided, text embeddings will be generated from `prompt` input argument.
354
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
355
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
356
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
357
+ argument.
358
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
359
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
360
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
361
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
362
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
363
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
364
+ input argument.
365
+ lora_scale (`float`, *optional*):
366
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
367
+ clip_skip (`int`, *optional*):
368
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
369
+ the output of the pre-final layer will be used for computing the prompt embeddings.
370
+ """
371
+ device = device or self._execution_device
372
+
373
+ # set lora scale so that monkey patched LoRA
374
+ # function of text encoder can correctly access it
375
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
376
+ self._lora_scale = lora_scale
377
+
378
+ # dynamically adjust the LoRA scale
379
+ if self.text_encoder is not None:
380
+ if not USE_PEFT_BACKEND:
381
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
382
+ else:
383
+ scale_lora_layers(self.text_encoder, lora_scale)
384
+
385
+ if self.text_encoder_2 is not None:
386
+ if not USE_PEFT_BACKEND:
387
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
388
+ else:
389
+ scale_lora_layers(self.text_encoder_2, lora_scale)
390
+
391
+ prompt = [prompt] if isinstance(prompt, str) else prompt
392
+
393
+ if prompt is not None:
394
+ batch_size = len(prompt)
395
+ else:
396
+ batch_size = prompt_embeds.shape[0]
397
+
398
+ # Define tokenizers and text encoders
399
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
400
+ text_encoders = (
401
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
402
+ )
403
+
404
+ if prompt_embeds is None:
405
+ prompt_2 = prompt_2 or prompt
406
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
407
+
408
+ # textual inversion: process multi-vector tokens if necessary
409
+ prompt_embeds_list = []
410
+ prompts = [prompt, prompt_2]
411
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
412
+ if isinstance(self, TextualInversionLoaderMixin):
413
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
414
+
415
+ text_inputs = tokenizer(
416
+ prompt,
417
+ padding="max_length",
418
+ max_length=tokenizer.model_max_length,
419
+ truncation=True,
420
+ return_tensors="pt",
421
+ )
422
+
423
+ text_input_ids = text_inputs.input_ids
424
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
425
+
426
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
427
+ text_input_ids, untruncated_ids
428
+ ):
429
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1: -1])
430
+ logger.warning(
431
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
432
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
433
+ )
434
+
435
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
436
+
437
+ # We are only ALWAYS interested in the pooled output of the final text encoder
438
+ pooled_prompt_embeds = prompt_embeds[0]
439
+ if clip_skip is None:
440
+ prompt_embeds = prompt_embeds.hidden_states[-2]
441
+ else:
442
+ # "2" because SDXL always indexes from the penultimate layer.
443
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
444
+
445
+ prompt_embeds_list.append(prompt_embeds)
446
+
447
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
448
+
449
+ # get unconditional embeddings for classifier free guidance
450
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
451
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
452
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
453
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
454
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
455
+ negative_prompt = negative_prompt or ""
456
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
457
+
458
+ # normalize str to list
459
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
460
+ negative_prompt_2 = (
461
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
462
+ )
463
+
464
+ uncond_tokens: List[str]
465
+ if prompt is not None and type(prompt) is not type(negative_prompt):
466
+ raise TypeError(
467
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
468
+ f" {type(prompt)}."
469
+ )
470
+ elif batch_size != len(negative_prompt):
471
+ raise ValueError(
472
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
473
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
474
+ " the batch size of `prompt`."
475
+ )
476
+ else:
477
+ uncond_tokens = [negative_prompt, negative_prompt_2]
478
+
479
+ negative_prompt_embeds_list = []
480
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
481
+ if isinstance(self, TextualInversionLoaderMixin):
482
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
483
+
484
+ max_length = prompt_embeds.shape[1]
485
+ uncond_input = tokenizer(
486
+ negative_prompt,
487
+ padding="max_length",
488
+ max_length=max_length,
489
+ truncation=True,
490
+ return_tensors="pt",
491
+ )
492
+
493
+ negative_prompt_embeds = text_encoder(
494
+ uncond_input.input_ids.to(device),
495
+ output_hidden_states=True,
496
+ )
497
+ # We are only ALWAYS interested in the pooled output of the final text encoder
498
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
499
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
500
+
501
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
502
+
503
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
504
+
505
+ if self.text_encoder_2 is not None:
506
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
507
+ else:
508
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
509
+
510
+ bs_embed, seq_len, _ = prompt_embeds.shape
511
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
512
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
513
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
514
+
515
+ if do_classifier_free_guidance:
516
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
517
+ seq_len = negative_prompt_embeds.shape[1]
518
+
519
+ if self.text_encoder_2 is not None:
520
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
521
+ else:
522
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
523
+
524
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
525
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
526
+
527
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
528
+ bs_embed * num_images_per_prompt, -1
529
+ )
530
+ if do_classifier_free_guidance:
531
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
532
+ bs_embed * num_images_per_prompt, -1
533
+ )
534
+
535
+ if self.text_encoder is not None:
536
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
537
+ # Retrieve the original scale by scaling back the LoRA layers
538
+ unscale_lora_layers(self.text_encoder, lora_scale)
539
+
540
+ if self.text_encoder_2 is not None:
541
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
542
+ # Retrieve the original scale by scaling back the LoRA layers
543
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
544
+
545
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
546
+
547
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
548
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
549
+ dtype = next(self.image_encoder.parameters()).dtype
550
+
551
+ if not isinstance(image, torch.Tensor):
552
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
553
+
554
+ image = image.to(device=device, dtype=dtype)
555
+ if output_hidden_states:
556
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
557
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
558
+ uncond_image_enc_hidden_states = self.image_encoder(
559
+ torch.zeros_like(image), output_hidden_states=True
560
+ ).hidden_states[-2]
561
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
562
+ num_images_per_prompt, dim=0
563
+ )
564
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
565
+ else:
566
+ image_embeds = self.image_encoder(image).image_embeds
567
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
568
+ uncond_image_embeds = torch.zeros_like(image_embeds)
569
+
570
+ return image_embeds, uncond_image_embeds
571
+
572
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
573
+ def prepare_ip_adapter_image_embeds(
574
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
575
+ ):
576
+ if ip_adapter_image_embeds is None:
577
+ if not isinstance(ip_adapter_image, list):
578
+ ip_adapter_image = [ip_adapter_image]
579
+
580
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
581
+ raise ValueError(
582
+ 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."
583
+ )
584
+
585
+ image_embeds = []
586
+ for single_ip_adapter_image, image_proj_layer in zip(
587
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
588
+ ):
589
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
590
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
591
+ single_ip_adapter_image, device, 1, output_hidden_state
592
+ )
593
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
594
+ single_negative_image_embeds = torch.stack(
595
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
596
+ )
597
+
598
+ if do_classifier_free_guidance:
599
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
600
+ single_image_embeds = single_image_embeds.to(device)
601
+
602
+ image_embeds.append(single_image_embeds)
603
+ else:
604
+ repeat_dims = [1]
605
+ image_embeds = []
606
+ for single_image_embeds in ip_adapter_image_embeds:
607
+ if do_classifier_free_guidance:
608
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
609
+ single_image_embeds = single_image_embeds.repeat(
610
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
611
+ )
612
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
613
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
614
+ )
615
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
616
+ else:
617
+ single_image_embeds = single_image_embeds.repeat(
618
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
619
+ )
620
+ image_embeds.append(single_image_embeds)
621
+
622
+ return image_embeds
623
+
624
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
625
+ def prepare_extra_step_kwargs(self, generator, eta):
626
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
627
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
628
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
629
+ # and should be between [0, 1]
630
+
631
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
632
+ extra_step_kwargs = {}
633
+ if accepts_eta:
634
+ extra_step_kwargs["eta"] = eta
635
+
636
+ # check if the scheduler accepts generator
637
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
638
+ if accepts_generator:
639
+ extra_step_kwargs["generator"] = generator
640
+ return extra_step_kwargs
641
+
642
+ def check_inputs(
643
+ self,
644
+ prompt,
645
+ prompt_2,
646
+ height,
647
+ width,
648
+ callback_steps,
649
+ negative_prompt=None,
650
+ negative_prompt_2=None,
651
+ prompt_embeds=None,
652
+ negative_prompt_embeds=None,
653
+ pooled_prompt_embeds=None,
654
+ negative_pooled_prompt_embeds=None,
655
+ ip_adapter_image=None,
656
+ ip_adapter_image_embeds=None,
657
+ callback_on_step_end_tensor_inputs=None,
658
+ ):
659
+ if height % 8 != 0 or width % 8 != 0:
660
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
661
+
662
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
663
+ raise ValueError(
664
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
665
+ f" {type(callback_steps)}."
666
+ )
667
+
668
+ if callback_on_step_end_tensor_inputs is not None and not all(
669
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
670
+ ):
671
+ raise ValueError(
672
+ 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]}"
673
+ )
674
+
675
+ if prompt is not None and prompt_embeds is not None:
676
+ raise ValueError(
677
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
678
+ " only forward one of the two."
679
+ )
680
+ elif prompt_2 is not None and prompt_embeds is not None:
681
+ raise ValueError(
682
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
683
+ " only forward one of the two."
684
+ )
685
+ elif prompt is None and prompt_embeds is None:
686
+ raise ValueError(
687
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
688
+ )
689
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
690
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
691
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
692
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
693
+
694
+ if negative_prompt is not None and negative_prompt_embeds is not None:
695
+ raise ValueError(
696
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
697
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
698
+ )
699
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
700
+ raise ValueError(
701
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
702
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
703
+ )
704
+
705
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
706
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
707
+ raise ValueError(
708
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
709
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
710
+ f" {negative_prompt_embeds.shape}."
711
+ )
712
+
713
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
714
+ raise ValueError(
715
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
716
+ )
717
+
718
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
719
+ raise ValueError(
720
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
721
+ )
722
+
723
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
724
+ raise ValueError(
725
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
726
+ )
727
+
728
+ if ip_adapter_image_embeds is not None:
729
+ if not isinstance(ip_adapter_image_embeds, list):
730
+ raise ValueError(
731
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
732
+ )
733
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
734
+ raise ValueError(
735
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
736
+ )
737
+
738
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
739
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
740
+ shape = (
741
+ batch_size,
742
+ num_channels_latents,
743
+ int(height) // self.vae_scale_factor,
744
+ int(width) // self.vae_scale_factor,
745
+ )
746
+ if isinstance(generator, list) and len(generator) != batch_size:
747
+ raise ValueError(
748
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
749
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
750
+ )
751
+
752
+ if latents is None:
753
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
754
+ else:
755
+ latents = latents.to(device)
756
+
757
+ # scale the initial noise by the standard deviation required by the scheduler
758
+ latents = latents * self.scheduler.init_noise_sigma
759
+ return latents
760
+
761
+ def _get_add_time_ids(
762
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
763
+ ):
764
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
765
+
766
+ passed_add_embed_dim = (
767
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
768
+ )
769
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
770
+
771
+ if expected_add_embed_dim != passed_add_embed_dim:
772
+ raise ValueError(
773
+ 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`."
774
+ )
775
+
776
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
777
+ return add_time_ids
778
+
779
+ def upcast_vae(self):
780
+ dtype = self.vae.dtype
781
+ self.vae.to(dtype=torch.float32)
782
+ use_torch_2_0_or_xformers = isinstance(
783
+ self.vae.decoder.mid_block.attentions[0].processor,
784
+ (
785
+ AttnProcessor2_0,
786
+ XFormersAttnProcessor,
787
+ LoRAXFormersAttnProcessor,
788
+ LoRAAttnProcessor2_0,
789
+ FusedAttnProcessor2_0,
790
+ ),
791
+ )
792
+ # if xformers or torch_2_0 is used attention block does not need
793
+ # to be in float32 which can save lots of memory
794
+ if use_torch_2_0_or_xformers:
795
+ self.vae.post_quant_conv.to(dtype)
796
+ self.vae.decoder.conv_in.to(dtype)
797
+ self.vae.decoder.mid_block.to(dtype)
798
+
799
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
800
+ def get_guidance_scale_embedding(
801
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
802
+ ) -> torch.Tensor:
803
+ """
804
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
805
+
806
+ Args:
807
+ w (`torch.Tensor`):
808
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
809
+ embedding_dim (`int`, *optional*, defaults to 512):
810
+ Dimension of the embeddings to generate.
811
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
812
+ Data type of the generated embeddings.
813
+
814
+ Returns:
815
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
816
+ """
817
+ assert len(w.shape) == 1
818
+ w = w * 1000.0
819
+
820
+ half_dim = embedding_dim // 2
821
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
822
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
823
+ emb = w.to(dtype)[:, None] * emb[None, :]
824
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
825
+ if embedding_dim % 2 == 1: # zero pad
826
+ emb = torch.nn.functional.pad(emb, (0, 1))
827
+ assert emb.shape == (w.shape[0], embedding_dim)
828
+ return emb
829
+
830
+ @property
831
+ def guidance_scale(self):
832
+ return self._guidance_scale
833
+
834
+ @property
835
+ def guidance_rescale(self):
836
+ return self._guidance_rescale
837
+
838
+ @property
839
+ def clip_skip(self):
840
+ return self._clip_skip
841
+
842
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
843
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
844
+ # corresponds to doing no classifier free guidance.
845
+ @property
846
+ def do_classifier_free_guidance(self):
847
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
848
+
849
+ @property
850
+ def cross_attention_kwargs(self):
851
+ return self._cross_attention_kwargs
852
+
853
+ @property
854
+ def denoising_end(self):
855
+ return self._denoising_end
856
+
857
+ @property
858
+ def num_timesteps(self):
859
+ return self._num_timesteps
860
+
861
+ @property
862
+ def interrupt(self):
863
+ return self._interrupt
864
+
865
+ @torch.no_grad()
866
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
867
+ def __call__(
868
+ self,
869
+ prompt: Union[str, List[str]] = None,
870
+ prompt_2: Optional[Union[str, List[str]]] = None,
871
+ controlnet_image: Optional[PipelineImageInput] = None,
872
+ controlnet_scale: Optional[float] = 1.0,
873
+ height: Optional[int] = None,
874
+ width: Optional[int] = None,
875
+ num_inference_steps: int = 50,
876
+ timesteps: List[int] = None,
877
+ sigmas: List[float] = None,
878
+ denoising_end: Optional[float] = None,
879
+ guidance_scale: float = 5.0,
880
+ negative_prompt: Optional[Union[str, List[str]]] = None,
881
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
882
+ num_images_per_prompt: Optional[int] = 1,
883
+ eta: float = 0.0,
884
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
885
+ latents: Optional[torch.Tensor] = None,
886
+ prompt_embeds: Optional[torch.Tensor] = None,
887
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
888
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
889
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
890
+ ip_adapter_image: Optional[PipelineImageInput] = None,
891
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
892
+ output_type: Optional[str] = "pil",
893
+ return_dict: bool = True,
894
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
895
+ guidance_rescale: float = 0.0,
896
+ original_size: Optional[Tuple[int, int]] = None,
897
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
898
+ target_size: Optional[Tuple[int, int]] = None,
899
+ negative_original_size: Optional[Tuple[int, int]] = None,
900
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
901
+ negative_target_size: Optional[Tuple[int, int]] = None,
902
+ clip_skip: Optional[int] = None,
903
+ callback_on_step_end: Optional[
904
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
905
+ ] = None,
906
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
907
+ **kwargs,
908
+ ):
909
+ r"""
910
+ Function invoked when calling the pipeline for generation.
911
+
912
+ Args:
913
+ prompt (`str` or `List[str]`, *optional*):
914
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
915
+ instead.
916
+ prompt_2 (`str` or `List[str]`, *optional*):
917
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
918
+ used in both text-encoders
919
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
920
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
921
+ Anything below 512 pixels won't work well for
922
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
923
+ and checkpoints that are not specifically fine-tuned on low resolutions.
924
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
925
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
926
+ Anything below 512 pixels won't work well for
927
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
928
+ and checkpoints that are not specifically fine-tuned on low resolutions.
929
+ num_inference_steps (`int`, *optional*, defaults to 50):
930
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
931
+ expense of slower inference.
932
+ timesteps (`List[int]`, *optional*):
933
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
934
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
935
+ passed will be used. Must be in descending order.
936
+ sigmas (`List[float]`, *optional*):
937
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
938
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
939
+ will be used.
940
+ denoising_end (`float`, *optional*):
941
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
942
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
943
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
944
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
945
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
946
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
947
+ guidance_scale (`float`, *optional*, defaults to 5.0):
948
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
949
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
950
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
951
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
952
+ usually at the expense of lower image quality.
953
+ negative_prompt (`str` or `List[str]`, *optional*):
954
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
955
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
956
+ less than `1`).
957
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
958
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
959
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
960
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
961
+ The number of images to generate per prompt.
962
+ eta (`float`, *optional*, defaults to 0.0):
963
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
964
+ [`schedulers.DDIMScheduler`], will be ignored for others.
965
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
966
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
967
+ to make generation deterministic.
968
+ latents (`torch.Tensor`, *optional*):
969
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
970
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
971
+ tensor will ge generated by sampling using the supplied random `generator`.
972
+ prompt_embeds (`torch.Tensor`, *optional*):
973
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
974
+ provided, text embeddings will be generated from `prompt` input argument.
975
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
976
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
977
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
978
+ argument.
979
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
980
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
981
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
982
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
983
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
984
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
985
+ input argument.
986
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
987
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
988
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
989
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
990
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
991
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
992
+ output_type (`str`, *optional*, defaults to `"pil"`):
993
+ The output format of the generate image. Choose between
994
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
995
+ return_dict (`bool`, *optional*, defaults to `True`):
996
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
997
+ of a plain tuple.
998
+ cross_attention_kwargs (`dict`, *optional*):
999
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1000
+ `self.processor` in
1001
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1002
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1003
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1004
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1005
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1006
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1007
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1008
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1009
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1010
+ explained in section 2.2 of
1011
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1012
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1013
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1014
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1015
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1016
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1017
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1018
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1019
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1020
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1021
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1022
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1023
+ micro-conditioning as explained in section 2.2 of
1024
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1025
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1026
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1027
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1028
+ micro-conditioning as explained in section 2.2 of
1029
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1030
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1031
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1032
+ To negatively condition the generation process based on a target image resolution. It should be as same
1033
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1034
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1035
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1036
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1037
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1038
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1039
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1040
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1041
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1042
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1043
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1044
+ `._callback_tensor_inputs` attribute of your pipeline class.
1045
+
1046
+ Examples:
1047
+
1048
+ Returns:
1049
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1050
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1051
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1052
+ """
1053
+
1054
+ callback = kwargs.pop("callback", None)
1055
+ callback_steps = kwargs.pop("callback_steps", None)
1056
+
1057
+ if callback is not None:
1058
+ deprecate(
1059
+ "callback",
1060
+ "1.0.0",
1061
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1062
+ )
1063
+ if callback_steps is not None:
1064
+ deprecate(
1065
+ "callback_steps",
1066
+ "1.0.0",
1067
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1068
+ )
1069
+
1070
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1071
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1072
+
1073
+ # 0. Default height and width to unet
1074
+ height = height or self.default_sample_size * self.vae_scale_factor
1075
+ width = width or self.default_sample_size * self.vae_scale_factor
1076
+
1077
+ original_size = original_size or (height, width)
1078
+ target_size = target_size or (height, width)
1079
+
1080
+ # 1. Check inputs. Raise error if not correct
1081
+ self.check_inputs(
1082
+ prompt,
1083
+ prompt_2,
1084
+ height,
1085
+ width,
1086
+ callback_steps,
1087
+ negative_prompt,
1088
+ negative_prompt_2,
1089
+ prompt_embeds,
1090
+ negative_prompt_embeds,
1091
+ pooled_prompt_embeds,
1092
+ negative_pooled_prompt_embeds,
1093
+ ip_adapter_image,
1094
+ ip_adapter_image_embeds,
1095
+ callback_on_step_end_tensor_inputs,
1096
+ )
1097
+
1098
+ self._guidance_scale = guidance_scale
1099
+ self._guidance_rescale = guidance_rescale
1100
+ self._clip_skip = clip_skip
1101
+ self._cross_attention_kwargs = cross_attention_kwargs
1102
+ self._denoising_end = denoising_end
1103
+ self._interrupt = False
1104
+
1105
+ # 2. Define call parameters
1106
+ if prompt is not None and isinstance(prompt, str):
1107
+ batch_size = 1
1108
+ elif prompt is not None and isinstance(prompt, list):
1109
+ batch_size = len(prompt)
1110
+ else:
1111
+ batch_size = prompt_embeds.shape[0]
1112
+
1113
+ device = self._execution_device
1114
+
1115
+ # 3. Encode input prompt
1116
+ lora_scale = (
1117
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1118
+ )
1119
+
1120
+ (
1121
+ prompt_embeds,
1122
+ negative_prompt_embeds,
1123
+ pooled_prompt_embeds,
1124
+ negative_pooled_prompt_embeds,
1125
+ ) = self.encode_prompt(
1126
+ prompt=prompt,
1127
+ prompt_2=prompt_2,
1128
+ device=device,
1129
+ num_images_per_prompt=num_images_per_prompt,
1130
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1131
+ negative_prompt=negative_prompt,
1132
+ negative_prompt_2=negative_prompt_2,
1133
+ prompt_embeds=prompt_embeds,
1134
+ negative_prompt_embeds=negative_prompt_embeds,
1135
+ pooled_prompt_embeds=pooled_prompt_embeds,
1136
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1137
+ lora_scale=lora_scale,
1138
+ clip_skip=self.clip_skip,
1139
+ )
1140
+
1141
+ # 4. Prepare timesteps
1142
+ timesteps, num_inference_steps = retrieve_timesteps(
1143
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1144
+ )
1145
+
1146
+ # 5. Prepare latent variables
1147
+ num_channels_latents = self.unet.config.in_channels
1148
+ latents = self.prepare_latents(
1149
+ batch_size * num_images_per_prompt,
1150
+ num_channels_latents,
1151
+ height,
1152
+ width,
1153
+ prompt_embeds.dtype,
1154
+ device,
1155
+ generator,
1156
+ latents,
1157
+ )
1158
+
1159
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1160
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1161
+
1162
+ # 7. Prepare added time ids & embeddings
1163
+ add_text_embeds = pooled_prompt_embeds
1164
+ if self.text_encoder_2 is None:
1165
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1166
+ else:
1167
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1168
+
1169
+ add_time_ids = self._get_add_time_ids(
1170
+ original_size,
1171
+ crops_coords_top_left,
1172
+ target_size,
1173
+ dtype=prompt_embeds.dtype,
1174
+ text_encoder_projection_dim=text_encoder_projection_dim,
1175
+ )
1176
+ if negative_original_size is not None and negative_target_size is not None:
1177
+ negative_add_time_ids = self._get_add_time_ids(
1178
+ negative_original_size,
1179
+ negative_crops_coords_top_left,
1180
+ negative_target_size,
1181
+ dtype=prompt_embeds.dtype,
1182
+ text_encoder_projection_dim=text_encoder_projection_dim,
1183
+ )
1184
+ else:
1185
+ negative_add_time_ids = add_time_ids
1186
+
1187
+ if self.do_classifier_free_guidance:
1188
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1189
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1190
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1191
+
1192
+ prompt_embeds = prompt_embeds.to(device)
1193
+ add_text_embeds = add_text_embeds.to(device)
1194
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1195
+
1196
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1197
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1198
+ ip_adapter_image,
1199
+ ip_adapter_image_embeds,
1200
+ device,
1201
+ batch_size * num_images_per_prompt,
1202
+ self.do_classifier_free_guidance,
1203
+ )
1204
+
1205
+ if controlnet_image is not None and self.controlnet is not None:
1206
+ controlnet_image = self.prepare_image(
1207
+ controlnet_image,
1208
+ width,
1209
+ height,
1210
+ batch_size,
1211
+ num_images_per_prompt,
1212
+ device,
1213
+ self.controlnet.dtype,
1214
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1215
+ )
1216
+ # 8. Denoising loop
1217
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1218
+
1219
+ # 8.1 Apply denoising_end
1220
+ if (
1221
+ self.denoising_end is not None
1222
+ and isinstance(self.denoising_end, float)
1223
+ and self.denoising_end > 0
1224
+ and self.denoising_end < 1
1225
+ ):
1226
+ discrete_timestep_cutoff = int(
1227
+ round(
1228
+ self.scheduler.config.num_train_timesteps
1229
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1230
+ )
1231
+ )
1232
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1233
+ timesteps = timesteps[:num_inference_steps]
1234
+
1235
+ # 9. Optionally get Guidance Scale Embedding
1236
+ timestep_cond = None
1237
+ if self.unet.config.time_cond_proj_dim is not None:
1238
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1239
+ timestep_cond = self.get_guidance_scale_embedding(
1240
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1241
+ ).to(device=device, dtype=latents.dtype)
1242
+
1243
+ self._num_timesteps = len(timesteps)
1244
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1245
+ for i, t in enumerate(timesteps):
1246
+ if self.interrupt:
1247
+ continue
1248
+
1249
+ # expand the latents if we are doing classifier free guidance
1250
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1251
+
1252
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1253
+
1254
+ # predict the noise residual
1255
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1256
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1257
+ added_cond_kwargs["image_embeds"] = image_embeds
1258
+
1259
+ unet_additional_args = {}
1260
+ if self.controlnet is not None:
1261
+ controls = self.controlnet(
1262
+ controlnet_image,
1263
+ t,
1264
+ )
1265
+
1266
+ # This makes the effect of the controlnext much more stronger
1267
+ # if do_classifier_free_guidance:
1268
+ # scale = controlnet_output['scale']
1269
+ # scale = scale.repeat(batch_size*2)[:, None, None, None]
1270
+ # scale[:batch_size] *= 0
1271
+ # controlnet_output['scale'] = scale
1272
+
1273
+ controls['scale'] *= controlnet_scale
1274
+ unet_additional_args["controls"] = controls
1275
+
1276
+ noise_pred = self.unet(
1277
+ latent_model_input,
1278
+ t,
1279
+ encoder_hidden_states=prompt_embeds,
1280
+ timestep_cond=timestep_cond,
1281
+ cross_attention_kwargs=self.cross_attention_kwargs,
1282
+ added_cond_kwargs=added_cond_kwargs,
1283
+ return_dict=False,
1284
+ **unet_additional_args,
1285
+ )[0]
1286
+
1287
+ # perform guidance
1288
+ if self.do_classifier_free_guidance:
1289
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1290
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1291
+
1292
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1293
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1294
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1295
+
1296
+ # compute the previous noisy sample x_t -> x_t-1
1297
+ latents_dtype = latents.dtype
1298
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1299
+ if latents.dtype != latents_dtype:
1300
+ if torch.backends.mps.is_available():
1301
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1302
+ latents = latents.to(latents_dtype)
1303
+
1304
+ if callback_on_step_end is not None:
1305
+ callback_kwargs = {}
1306
+ for k in callback_on_step_end_tensor_inputs:
1307
+ callback_kwargs[k] = locals()[k]
1308
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1309
+
1310
+ latents = callback_outputs.pop("latents", latents)
1311
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1312
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1313
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1314
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1315
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1316
+ )
1317
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1318
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1319
+
1320
+ # call the callback, if provided
1321
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1322
+ progress_bar.update()
1323
+ if callback is not None and i % callback_steps == 0:
1324
+ step_idx = i // getattr(self.scheduler, "order", 1)
1325
+ callback(step_idx, t, latents)
1326
+
1327
+ if XLA_AVAILABLE:
1328
+ xm.mark_step()
1329
+
1330
+ if not output_type == "latent":
1331
+ # make sure the VAE is in float32 mode, as it overflows in float16
1332
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1333
+
1334
+ if needs_upcasting:
1335
+ self.upcast_vae()
1336
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1337
+ elif latents.dtype != self.vae.dtype:
1338
+ if torch.backends.mps.is_available():
1339
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1340
+ self.vae = self.vae.to(latents.dtype)
1341
+
1342
+ # unscale/denormalize the latents
1343
+ # denormalize with the mean and std if available and not None
1344
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1345
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1346
+ if has_latents_mean and has_latents_std:
1347
+ latents_mean = (
1348
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1349
+ )
1350
+ latents_std = (
1351
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1352
+ )
1353
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1354
+ else:
1355
+ latents = latents / self.vae.config.scaling_factor
1356
+
1357
+ image = self.vae.decode(latents, return_dict=False)[0]
1358
+
1359
+ # cast back to fp16 if needed
1360
+ if needs_upcasting:
1361
+ self.vae.to(dtype=torch.float16)
1362
+ else:
1363
+ image = latents
1364
+
1365
+ if not output_type == "latent":
1366
+ # apply watermark if available
1367
+ if self.watermark is not None:
1368
+ image = self.watermark.apply_watermark(image)
1369
+
1370
+ image = self.image_processor.postprocess(image, output_type=output_type)
1371
+
1372
+ # Offload all models
1373
+ self.maybe_free_model_hooks()
1374
+
1375
+ if not return_dict:
1376
+ return (image,)
1377
+
1378
+ return StableDiffusionXLPipelineOutput(images=image)
utils/preprocess.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+
5
+
6
+ def get_extractor(extractor_name):
7
+ if extractor_name is None:
8
+ return None
9
+ if extractor_name not in EXTRACTORS:
10
+ raise ValueError(f"Extractor {extractor_name} is not supported.")
11
+ return EXTRACTORS[extractor_name]
12
+
13
+
14
+ def canny_extractor(image: Image.Image, threshold1=None, threshold2=None) -> Image.Image:
15
+ image = np.array(image)
16
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
17
+ v = np.median(gray)
18
+
19
+ sigma = 0.33
20
+ threshold1 = threshold1 or int(max(0, (1.0 - sigma) * v))
21
+ threshold2 = threshold2 or int(min(255, (1.0 + sigma) * v))
22
+
23
+ edges = cv2.Canny(gray, threshold1, threshold2)
24
+ edges = Image.fromarray(edges).convert("RGB")
25
+ return edges
26
+
27
+
28
+ def depth_extractor(image: Image.Image):
29
+ raise NotImplementedError("Depth extractor is not implemented yet.")
30
+
31
+
32
+ def pose_extractor(image: Image.Image):
33
+ raise NotImplementedError("Pose extractor is not implemented yet.")
34
+
35
+
36
+ EXTRACTORS = {
37
+ "canny": canny_extractor,
38
+ }
utils/tools.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from torch import nn
4
+ from diffusers import UniPCMultistepScheduler, AutoencoderKL
5
+ from safetensors.torch import load_file
6
+ from pipeline.pipeline_controlnext import StableDiffusionXLControlNeXtPipeline
7
+ from models.unet import UNet2DConditionModel, UNET_CONFIG
8
+ from models.controlnet import ControlNetModel
9
+ from . import utils
10
+
11
+
12
+ def get_pipeline(
13
+ pretrained_model_name_or_path,
14
+ unet_model_name_or_path,
15
+ controlnet_model_name_or_path,
16
+ vae_model_name_or_path=None,
17
+ lora_path=None,
18
+ load_weight_increasement=False,
19
+ enable_xformers_memory_efficient_attention=False,
20
+ revision=None,
21
+ variant=None,
22
+ hf_cache_dir=None,
23
+ use_safetensors=True,
24
+ device=None,
25
+ ):
26
+ pipeline_init_kwargs = {}
27
+
28
+ if controlnet_model_name_or_path is not None:
29
+ print(f"loading controlnet from {controlnet_model_name_or_path}")
30
+ controlnet = ControlNetModel()
31
+ if controlnet_model_name_or_path is not None:
32
+ utils.load_safetensors(controlnet, controlnet_model_name_or_path)
33
+ else:
34
+ controlnet.scale = nn.Parameter(torch.tensor(0.), requires_grad=False)
35
+ controlnet.to(device, dtype=torch.float32)
36
+ pipeline_init_kwargs["controlnet"] = controlnet
37
+
38
+ utils.log_model_info(controlnet, "controlnext")
39
+ else:
40
+ print(f"no controlnet")
41
+
42
+ print(f"loading unet from {pretrained_model_name_or_path}")
43
+ if os.path.isfile(pretrained_model_name_or_path):
44
+ # load unet from local checkpoint
45
+ unet_sd = load_file(pretrained_model_name_or_path) if pretrained_model_name_or_path.endswith(".safetensors") else torch.load(pretrained_model_name_or_path)
46
+ unet_sd = utils.extract_unet_state_dict(unet_sd)
47
+ unet_sd = utils.convert_sdxl_unet_state_dict_to_diffusers(unet_sd)
48
+ unet = UNet2DConditionModel.from_config(UNET_CONFIG)
49
+ unet.load_state_dict(unet_sd, strict=True)
50
+ else:
51
+ from huggingface_hub import hf_hub_download
52
+ filename = "diffusion_pytorch_model"
53
+ if variant == "fp16":
54
+ filename += ".fp16"
55
+ if use_safetensors:
56
+ filename += ".safetensors"
57
+ else:
58
+ filename += ".pt"
59
+ unet_file = hf_hub_download(
60
+ repo_id=pretrained_model_name_or_path,
61
+ filename="unet" + '/' + filename,
62
+ cache_dir=hf_cache_dir,
63
+ )
64
+ unet_sd = load_file(unet_file) if unet_file.endswith(".safetensors") else torch.load(pretrained_model_name_or_path)
65
+ unet_sd = utils.extract_unet_state_dict(unet_sd)
66
+ unet_sd = utils.convert_sdxl_unet_state_dict_to_diffusers(unet_sd)
67
+ unet = UNet2DConditionModel.from_config(UNET_CONFIG)
68
+ unet.load_state_dict(unet_sd, strict=True)
69
+ unet = unet.to(dtype=torch.float16)
70
+ utils.log_model_info(unet, "unet")
71
+
72
+ if unet_model_name_or_path is not None:
73
+ print(f"loading controlnext unet from {unet_model_name_or_path}")
74
+ controlnext_unet_sd = load_file(unet_model_name_or_path)
75
+ controlnext_unet_sd = utils.convert_to_controlnext_unet_state_dict(controlnext_unet_sd)
76
+ unet_sd = unet.state_dict()
77
+ assert all(
78
+ k in unet_sd for k in controlnext_unet_sd), \
79
+ f"controlnext unet state dict is not compatible with unet state dict, missing keys: {set(controlnext_unet_sd.keys()) - set(unet_sd.keys())}, extra keys: {set(unet_sd.keys()) - set(controlnext_unet_sd.keys())}"
80
+ if load_weight_increasement:
81
+ print("loading weight increasement")
82
+ for k in controlnext_unet_sd.keys():
83
+ controlnext_unet_sd[k] = controlnext_unet_sd[k] + unet_sd[k]
84
+ unet.load_state_dict(controlnext_unet_sd, strict=False)
85
+ utils.log_model_info(controlnext_unet_sd, "controlnext unet")
86
+
87
+ pipeline_init_kwargs["unet"] = unet
88
+
89
+ if vae_model_name_or_path is not None:
90
+ print(f"loading vae from {vae_model_name_or_path}")
91
+ vae = AutoencoderKL.from_pretrained(vae_model_name_or_path, cache_dir=hf_cache_dir, torch_dtype=torch.float16).to(device)
92
+ pipeline_init_kwargs["vae"] = vae
93
+
94
+ print(f"loading pipeline from {pretrained_model_name_or_path}")
95
+ if os.path.isfile(pretrained_model_name_or_path):
96
+ pipeline: StableDiffusionXLControlNeXtPipeline = StableDiffusionXLControlNeXtPipeline.from_single_file(
97
+ pretrained_model_name_or_path,
98
+ use_safetensors=pretrained_model_name_or_path.endswith(".safetensors"),
99
+ local_files_only=True,
100
+ cache_dir=hf_cache_dir,
101
+ **pipeline_init_kwargs,
102
+ )
103
+ else:
104
+ pipeline: StableDiffusionXLControlNeXtPipeline = StableDiffusionXLControlNeXtPipeline.from_pretrained(
105
+ pretrained_model_name_or_path,
106
+ revision=revision,
107
+ variant=variant,
108
+ use_safetensors=use_safetensors,
109
+ cache_dir=hf_cache_dir,
110
+ **pipeline_init_kwargs,
111
+ )
112
+
113
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
114
+ pipeline.set_progress_bar_config()
115
+ pipeline = pipeline.to(device, dtype=torch.float16)
116
+
117
+ if lora_path is not None:
118
+ pipeline.load_lora_weights(lora_path)
119
+ if enable_xformers_memory_efficient_attention:
120
+ pipeline.enable_xformers_memory_efficient_attention()
121
+
122
+ return pipeline
123
+
124
+
125
+ def get_scheduler(
126
+ scheduler_name,
127
+ scheduler_config,
128
+ ):
129
+ if scheduler_name == 'Euler A':
130
+ from diffusers.schedulers import EulerAncestralDiscreteScheduler
131
+ scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler_config)
132
+ elif scheduler_name == 'UniPC':
133
+ from diffusers.schedulers import UniPCMultistepScheduler
134
+ scheduler = UniPCMultistepScheduler.from_config(scheduler_config)
135
+ elif scheduler_name == 'Euler':
136
+ from diffusers.schedulers import EulerDiscreteScheduler
137
+ scheduler = EulerDiscreteScheduler.from_config(scheduler_config)
138
+ elif scheduler_name == 'DDIM':
139
+ from diffusers.schedulers import DDIMScheduler
140
+ scheduler = DDIMScheduler.from_config(scheduler_config)
141
+ elif scheduler_name == 'DDPM':
142
+ from diffusers.schedulers import DDPMScheduler
143
+ scheduler = DDPMScheduler.from_config(scheduler_config)
144
+ else:
145
+ raise ValueError(f"Unknown scheduler: {scheduler_name}")
146
+ return scheduler
utils/utils.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Tuple, Union, Optional
3
+ from safetensors.torch import load_file
4
+ from transformers import PretrainedConfig
5
+
6
+
7
+ def count_num_parameters_of_safetensors_model(safetensors_path):
8
+ state_dict = load_file(safetensors_path)
9
+ return sum(p.numel() for p in state_dict.values())
10
+
11
+
12
+ def import_model_class_from_model_name_or_path(
13
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = None
14
+ ):
15
+ text_encoder_config = PretrainedConfig.from_pretrained(
16
+ pretrained_model_name_or_path, revision=revision, subfolder=subfolder
17
+ )
18
+ model_class = text_encoder_config.architectures[0]
19
+ if model_class == "CLIPTextModel":
20
+ from transformers import CLIPTextModel
21
+ return CLIPTextModel
22
+ elif model_class == "CLIPTextModelWithProjection":
23
+ from transformers import CLIPTextModelWithProjection
24
+ return CLIPTextModelWithProjection
25
+ else:
26
+ raise ValueError(f"{model_class} is not supported.")
27
+
28
+
29
+ def fix_clip_text_encoder_position_ids(text_encoder):
30
+ if hasattr(text_encoder.text_model.embeddings, "position_ids"):
31
+ text_encoder.text_model.embeddings.position_ids = text_encoder.text_model.embeddings.position_ids.long()
32
+
33
+
34
+ def load_controlnext_unet_state_dict(unet_sd, controlnext_unet_sd):
35
+ assert all(
36
+ k in unet_sd for k in controlnext_unet_sd), f"controlnext unet state dict is not compatible with unet state dict, missing keys: {set(controlnext_unet_sd.keys()) - set(unet_sd.keys())}, extra keys: {set(unet_sd.keys()) - set(controlnext_unet_sd.keys())}"
37
+ for k in controlnext_unet_sd.keys():
38
+ unet_sd[k] = controlnext_unet_sd[k]
39
+ return unet_sd
40
+
41
+
42
+ def convert_to_controlnext_unet_state_dict(state_dict):
43
+ import re
44
+ pattern = re.compile(r'.*attn2.*to_out.*')
45
+ state_dict = {k: v for k, v in state_dict.items() if pattern.match(k)}
46
+ # state_dict = extract_unet_state_dict(state_dict)
47
+ if is_sdxl_state_dict(state_dict):
48
+ state_dict = convert_sdxl_unet_state_dict_to_diffusers(state_dict)
49
+ return state_dict
50
+
51
+
52
+ def make_unet_conversion_map():
53
+ unet_conversion_map_layer = []
54
+
55
+ for i in range(3): # num_blocks is 3 in sdxl
56
+ # loop over downblocks/upblocks
57
+ for j in range(2):
58
+ # loop over resnets/attentions for downblocks
59
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
60
+ sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0."
61
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
62
+
63
+ if i < 3:
64
+ # no attention layers in down_blocks.3
65
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
66
+ sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1."
67
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
68
+
69
+ for j in range(3):
70
+ # loop over resnets/attentions for upblocks
71
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
72
+ sd_up_res_prefix = f"output_blocks.{3*i + j}.0."
73
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
74
+
75
+ # if i > 0: commentout for sdxl
76
+ # no attention layers in up_blocks.0
77
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
78
+ sd_up_atn_prefix = f"output_blocks.{3*i + j}.1."
79
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
80
+
81
+ if i < 3:
82
+ # no downsample in down_blocks.3
83
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
84
+ sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op."
85
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
86
+
87
+ # no upsample in up_blocks.3
88
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
89
+ sd_upsample_prefix = f"output_blocks.{3*i + 2}.{2}." # change for sdxl
90
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
91
+
92
+ hf_mid_atn_prefix = "mid_block.attentions.0."
93
+ sd_mid_atn_prefix = "middle_block.1."
94
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
95
+
96
+ for j in range(2):
97
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
98
+ sd_mid_res_prefix = f"middle_block.{2*j}."
99
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
100
+
101
+ unet_conversion_map_resnet = [
102
+ # (stable-diffusion, HF Diffusers)
103
+ ("in_layers.0.", "norm1."),
104
+ ("in_layers.2.", "conv1."),
105
+ ("out_layers.0.", "norm2."),
106
+ ("out_layers.3.", "conv2."),
107
+ ("emb_layers.1.", "time_emb_proj."),
108
+ ("skip_connection.", "conv_shortcut."),
109
+ ]
110
+
111
+ unet_conversion_map = []
112
+ for sd, hf in unet_conversion_map_layer:
113
+ if "resnets" in hf:
114
+ for sd_res, hf_res in unet_conversion_map_resnet:
115
+ unet_conversion_map.append((sd + sd_res, hf + hf_res))
116
+ else:
117
+ unet_conversion_map.append((sd, hf))
118
+
119
+ for j in range(2):
120
+ hf_time_embed_prefix = f"time_embedding.linear_{j+1}."
121
+ sd_time_embed_prefix = f"time_embed.{j*2}."
122
+ unet_conversion_map.append((sd_time_embed_prefix, hf_time_embed_prefix))
123
+
124
+ for j in range(2):
125
+ hf_label_embed_prefix = f"add_embedding.linear_{j+1}."
126
+ sd_label_embed_prefix = f"label_emb.0.{j*2}."
127
+ unet_conversion_map.append((sd_label_embed_prefix, hf_label_embed_prefix))
128
+
129
+ unet_conversion_map.append(("input_blocks.0.0.", "conv_in."))
130
+ unet_conversion_map.append(("out.0.", "conv_norm_out."))
131
+ unet_conversion_map.append(("out.2.", "conv_out."))
132
+
133
+ return unet_conversion_map
134
+
135
+
136
+ def convert_unet_state_dict(src_sd, conversion_map):
137
+ converted_sd = {}
138
+ for src_key, value in src_sd.items():
139
+ src_key_fragments = src_key.split(".")[:-1] # remove weight/bias
140
+ while len(src_key_fragments) > 0:
141
+ src_key_prefix = ".".join(src_key_fragments) + "."
142
+ if src_key_prefix in conversion_map:
143
+ converted_prefix = conversion_map[src_key_prefix]
144
+ converted_key = converted_prefix + src_key[len(src_key_prefix):]
145
+ converted_sd[converted_key] = value
146
+ break
147
+ src_key_fragments.pop(-1)
148
+ assert len(src_key_fragments) > 0, f"key {src_key} not found in conversion map"
149
+
150
+ return converted_sd
151
+
152
+
153
+ def convert_sdxl_unet_state_dict_to_diffusers(sd):
154
+ unet_conversion_map = make_unet_conversion_map()
155
+
156
+ conversion_dict = {sd: hf for sd, hf in unet_conversion_map}
157
+ return convert_unet_state_dict(sd, conversion_dict)
158
+
159
+
160
+ def extract_unet_state_dict(state_dict):
161
+ unet_sd = {}
162
+ UNET_KEY_PREFIX = "model.diffusion_model."
163
+ for k, v in state_dict.items():
164
+ if k.startswith(UNET_KEY_PREFIX):
165
+ unet_sd[k[len(UNET_KEY_PREFIX):]] = v
166
+ return unet_sd
167
+
168
+
169
+ def is_sdxl_state_dict(state_dict):
170
+ return any(key.startswith('input_blocks') for key in state_dict.keys())
171
+
172
+
173
+ def contains_unet_keys(state_dict):
174
+ UNET_KEY_PREFIX = "model.diffusion_model."
175
+ return any(k.startswith(UNET_KEY_PREFIX) for k in state_dict.keys())
176
+
177
+
178
+ def load_safetensors(model, safetensors_path, strict=True, load_weight_increasement=False):
179
+ if not load_weight_increasement:
180
+ state_dict = load_file(safetensors_path)
181
+ model.load_state_dict(state_dict, strict=strict)
182
+ else:
183
+ state_dict = load_file(safetensors_path)
184
+ pretrained_state_dict = model.state_dict()
185
+ for k in state_dict.keys():
186
+ state_dict[k] = state_dict[k] + pretrained_state_dict[k]
187
+ model.load_state_dict(state_dict, strict=False)
188
+
189
+
190
+ def log_model_info(model, name):
191
+ sd = model.state_dict() if hasattr(model, "state_dict") else model
192
+ print(
193
+ f"{name}:",
194
+ f" number of parameters: {sum(p.numel() for p in sd.values())}",
195
+ f" dtype: {sd[next(iter(sd))].dtype}",
196
+ sep='\n'
197
+ )
198
+
199
+
200
+ def around_reso(img_w, img_h, reso: Union[Tuple[int, int], int], divisible: Optional[int] = None, max_width=None, max_height=None) -> Tuple[int, int]:
201
+ r"""
202
+ w*h = reso*reso
203
+ w/h = img_w/img_h
204
+ => w = img_ar*h
205
+ => img_ar*h^2 = reso
206
+ => h = sqrt(reso / img_ar)
207
+ """
208
+ reso = reso if isinstance(reso, tuple) else (reso, reso)
209
+ divisible = divisible or 1
210
+ if img_w * img_h <= reso[0] * reso[1] and (not max_width or img_w <= max_width) and (not max_height or img_h <= max_height) and img_w % divisible == 0 and img_h % divisible == 0:
211
+ return (img_w, img_h)
212
+ img_ar = img_w / img_h
213
+ around_h = math.sqrt(reso[0]*reso[1] / img_ar)
214
+ around_w = img_ar * around_h // divisible * divisible
215
+ if max_width and around_w > max_width:
216
+ around_h = around_h * max_width // around_w
217
+ around_w = max_width
218
+ elif max_height and around_h > max_height:
219
+ around_w = around_w * max_height // around_h
220
+ around_h = max_height
221
+ around_h = min(around_h, max_height) if max_height else around_h
222
+ around_w = min(around_w, max_width) if max_width else around_w
223
+ around_h = int(around_h // divisible * divisible)
224
+ around_w = int(around_w // divisible * divisible)
225
+ return (around_w, around_h)