mikonvergence commited on
Commit
37c80b4
·
1 Parent(s): 21202e6

first test

Browse files
app.py CHANGED
@@ -1,107 +1,40 @@
1
- !pip install "huggingface_hub[hf_transfer]"
2
- !pip install -U "huggingface_hub[cli]"
3
- !pip install gradio trimesh scipy
4
- !HF_HUB_ENABLE_HF_TRANSFER=1
5
- !git clone https://github.com/PaulBorneP/MESA.git
6
- !cd MESA
7
- !mkdir weights
8
- !huggingface-cli download NewtNewt/MESA --local-dir weights
9
-
10
- import torch
11
- from MESA.pipeline_terrain import TerrainDiffusionPipeline
12
- import sys
13
  import gradio as gr
14
- import numpy as np
15
- import trimesh
16
- import tempfile
17
- import torch
18
- from scipy.spatial import Delaunay
19
-
20
- sys.path.append('MESA/')
21
-
22
- pipe = TerrainDiffusionPipeline.from_pretrained("./weights", torch_dtype=torch.float16)
23
- pipe.to("cuda")
24
-
25
- def generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
26
- """Generates terrain data (RGB and elevation) from a text prompt."""
27
- if prefix and not prefix.endswith(' '):
28
- prefix += ' ' # Ensure prefix ends with a space
29
-
30
- full_prompt = prefix + prompt
31
- generator = torch.Generator("cuda").manual_seed(seed)
32
- image, dem = pipe(full_prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator)
33
-
34
- # Center crop the image and dem
35
- h, w, c = image[0].shape
36
- start_h = (h - crop_size) // 2
37
- start_w = (w - crop_size) // 2
38
- end_h = start_h + crop_size
39
- end_w = start_w + crop_size
40
-
41
- cropped_image = image[0][start_h:end_h, start_w:end_w, :]
42
- cropped_dem = dem[0][start_h:end_h, start_w:end_w, :]
43
-
44
- return (255 * cropped_image).astype(np.uint8), 500*cropped_dem.mean(-1)
45
-
46
- def create_3d_mesh(rgb, elevation):
47
- """Creates a 3D mesh from RGB and elevation data."""
48
- x, y = np.meshgrid(np.arange(elevation.shape[1]), np.arange(elevation.shape[0]))
49
- points = np.stack([x.flatten(), y.flatten()], axis=-1)
50
- tri = Delaunay(points)
51
-
52
- vertices = np.stack([x.flatten(), y.flatten(), elevation.flatten()], axis=-1)
53
- faces = tri.simplices
54
-
55
- mesh = trimesh.Trimesh(vertices=vertices, faces=faces, vertex_colors=rgb.reshape(-1, 3))
56
-
57
- return mesh
58
-
59
- def generate_and_display(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
60
- """Generates terrain and displays it as a 3D model."""
61
- rgb, elevation = generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix)
62
- mesh = create_3d_mesh(rgb, elevation)
63
-
64
- with tempfile.NamedTemporaryFile(suffix=".obj", delete=False) as temp_file:
65
- mesh.export(temp_file.name)
66
- file_path = temp_file.name
67
-
68
- return file_path
69
-
70
- theme = gr.themes.Soft(primary_hue="red", secondary_hue="red", font=['arial'])
71
-
72
- with gr.Blocks(theme=theme) as demo:
73
- with gr.Column(elem_classes="header"):
74
- gr.Markdown("# MESA: Text-Driven Terrain Generation Using Latent Diffusion and Global Copernicus Data")
75
- gr.Markdown("### Paul Borne–Pons, Mikolaj Czerkawski, Rosalie Martin, Romain Rouffet")
76
- gr.Markdown('[[GitHub](https://github.com/PaulBorneP/MESA)] [[Model](https://huggingface.co/NewtNewt/MESA)] [[Dataset](https://huggingface.co/datasets/Major-TOM/Core-DEM)]')
77
 
78
- # Abstract Section
79
- with gr.Column(elem_classes="abstract"):
80
- gr.Markdown("MESA is a novel generative model based on latent denoising diffusion capable of generating 2.5D representations of terrain based on the text prompt conditioning supplied via natural language. The model produces two co-registered modalities of optical and depth maps.") # Replace with your abstract text
81
- gr.Markdown("This is a test version of the demo app. Please be aware that MESA supports primarily complex, mountainous terrains as opposed to flat land")
82
- gr.Markdown("The generated image is quite large, so for the full resolution (768) it might take a while to load the surface")
83
-
84
- with gr.Row():
85
- prompt_input = gr.Textbox(lines=2, placeholder="Enter a terrain description...")
86
- generate_button = gr.Button("Generate Terrain", variant="primary")
87
-
88
- model_output = gr.Model3D(
89
- camera_position=[90, 180, 512]
90
- )
91
-
92
- with gr.Accordion("Advanced Options", open=False) as advanced_options:
93
- num_inference_steps_slider = gr.Slider(minimum=10, maximum=1000, step=10, value=50, label="Inference Steps")
94
- guidance_scale_slider = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, value=7.5, label="Guidance Scale")
95
- seed_number = gr.Number(value=6378, label="Seed")
96
- crop_size_slider = gr.Slider(minimum=128, maximum=768, step=64, value=512, label="Crop Size")
97
- prefix_textbox = gr.Textbox(label="Prompt Prefix", value="A Sentinel-2 image of ")
98
-
99
- generate_button.click(
100
- fn=generate_and_display,
101
- inputs=[prompt_input, num_inference_steps_slider, guidance_scale_slider, seed_number, crop_size_slider, prefix_textbox],
102
- outputs=model_output,
103
- )
104
-
105
- if __name__ == "__main__":
106
- demo.launch(debug=True,
107
- share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from src.utils import *
3
+
4
+ if __name__ == '__main__':
5
+ theme = gr.themes.Soft(primary_hue="red", secondary_hue="red", font=['arial'])
6
+
7
+ with gr.Blocks(theme=theme) as demo:
8
+ with gr.Column(elem_classes="header"):
9
+ gr.Markdown("# MESA: Text-Driven Terrain Generation Using Latent Diffusion and Global Copernicus Data")
10
+ gr.Markdown("### Paul Borne–Pons, Mikolaj Czerkawski, Rosalie Martin, Romain Rouffet")
11
+ gr.Markdown('[[GitHub](https://github.com/PaulBorneP/MESA)] [[Model](https://huggingface.co/NewtNewt/MESA)] [[Dataset](https://huggingface.co/datasets/Major-TOM/Core-DEM)]')
12
+
13
+ # Abstract Section
14
+ with gr.Column(elem_classes="abstract"):
15
+ gr.Markdown("MESA is a novel generative model based on latent denoising diffusion capable of generating 2.5D representations of terrain based on the text prompt conditioning supplied via natural language. The model produces two co-registered modalities of optical and depth maps.") # Replace with your abstract text
16
+ gr.Markdown("This is a test version of the demo app. Please be aware that MESA supports primarily complex, mountainous terrains as opposed to flat land")
17
+ gr.Markdown("The generated image is quite large, so for the full resolution (768) it might take a while to load the surface")
18
+
19
+ with gr.Row():
20
+ prompt_input = gr.Textbox(lines=2, placeholder="Enter a terrain description...")
21
+ generate_button = gr.Button("Generate Terrain", variant="primary")
22
+
23
+ model_output = gr.Model3D(
24
+ camera_position=[90, 180, 512]
25
+ )
26
+
27
+ with gr.Accordion("Advanced Options", open=False) as advanced_options:
28
+ num_inference_steps_slider = gr.Slider(minimum=10, maximum=1000, step=10, value=50, label="Inference Steps")
29
+ guidance_scale_slider = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, value=7.5, label="Guidance Scale")
30
+ seed_number = gr.Number(value=6378, label="Seed")
31
+ crop_size_slider = gr.Slider(minimum=128, maximum=768, step=64, value=512, label="Crop Size")
32
+ prefix_textbox = gr.Textbox(label="Prompt Prefix", value="A Sentinel-2 image of ")
33
+
34
+ generate_button.click(
35
+ fn=generate_and_display,
36
+ inputs=[prompt_input, num_inference_steps_slider, guidance_scale_slider, seed_number, crop_size_slider, prefix_textbox],
37
+ outputs=model_output,
38
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ demo.queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+ from torch.nn import functional as F
3
+ from diffusers import UNet2DConditionModel
4
+ import torch
5
+
6
+ def init_dem_channels(model,conv_in=None,conv_out=None):
7
+ """
8
+ Add a channel to the input and output of the model, with 0 initialization
9
+ """
10
+ # add one channel to the input and output, with 0 initialization
11
+ if conv_in is not None:
12
+ # add a channel to the input of the encoder
13
+ pretrained_in_weights = conv_in.weight.clone()
14
+ pretrained_in_bias = conv_in.bias.clone()
15
+
16
+ with torch.no_grad():
17
+ # weight matrix is of shape (out_channels, in_channels, kernel_size, kernel_size)
18
+ model.conv_in.weight[:, :4, :, :] = pretrained_in_weights
19
+ model.conv_in.weight[:, 4:, :, :] = 0
20
+ # bias vector is of shape (out_channels) no need to change it
21
+ model.conv_in.bias[...] = pretrained_in_bias
22
+
23
+
24
+
25
+ if conv_out is not None:
26
+ # add a channel to the output of the decoder
27
+ pretrained_out_weights = conv_out.weight.clone()
28
+ pretrained_out_bias = conv_out.bias.clone()
29
+
30
+ with torch.no_grad():
31
+ # weight matrix is of shape (out_channels, in_channels, kernel_size, kernel_size)
32
+ model.conv_out.weight[:4, :, :, :] = pretrained_out_weights
33
+ model.conv_out.weight[4:, :, :, :] = 0
34
+ # bias vector is of shape (out_channels)
35
+ model.conv_out.bias[:4] = pretrained_out_bias
36
+ model.conv_out.bias[4:] = 0
37
+ # Ensure the new layers are registered
38
+ model.register_to_config()
39
+
40
+ return model
41
+
42
+
43
+
44
+
45
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
46
+ #
47
+ # Licensed under the Apache License, Version 2.0 (the "License");
48
+ # you may not use this file except in compliance with the License.
49
+ # You may obtain a copy of the License at
50
+ #
51
+ # http://www.apache.org/licenses/LICENSE-2.0
52
+ #
53
+ # Unless required by applicable law or agreed to in writing, software
54
+ # distributed under the License is distributed on an "AS IS" BASIS,
55
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
56
+ # See the License for the specific language governing permissions and
57
+ # limitations under the License.
58
+ from dataclasses import dataclass
59
+ from typing import Any, Dict, List, Optional, Tuple, Union
60
+
61
+ import torch
62
+ import torch.nn as nn
63
+ import torch.utils.checkpoint
64
+ import diffusers
65
+
66
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
67
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
68
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin
69
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
70
+ from diffusers.models.activations import get_activation
71
+ from diffusers.models.attention_processor import (
72
+ ADDED_KV_ATTENTION_PROCESSORS,
73
+ CROSS_ATTENTION_PROCESSORS,
74
+ Attention,
75
+ AttentionProcessor,
76
+ AttnAddedKVProcessor,
77
+ AttnProcessor,
78
+ FusedAttnProcessor2_0,
79
+ )
80
+ from diffusers.models.embeddings import (
81
+ GaussianFourierProjection,
82
+ GLIGENTextBoundingboxProjection,
83
+ ImageHintTimeEmbedding,
84
+ ImageProjection,
85
+ ImageTimeEmbedding,
86
+ TextImageProjection,
87
+ TextImageTimeEmbedding,
88
+ TextTimeEmbedding,
89
+ TimestepEmbedding,
90
+ Timesteps,
91
+ )
92
+ from diffusers.models.modeling_utils import ModelMixin
93
+ from diffusers.models.unets.unet_2d_blocks import (
94
+ get_down_block,
95
+ get_mid_block,
96
+ get_up_block,
97
+ )
98
+
99
+
100
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
101
+
102
+
103
+ @dataclass
104
+ class UNet2DConditionOutput(BaseOutput):
105
+ """
106
+ The output of [`UNet2DConditionModel`].
107
+
108
+ Args:
109
+ sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
110
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
111
+ """
112
+
113
+ sample: torch.Tensor = None
114
+
115
+
116
+ class UNetDEMConditionModel(
117
+ ModelMixin, ConfigMixin, FromOriginalModelMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin
118
+ ):
119
+ r"""
120
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
121
+ shaped output.
122
+
123
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
124
+ for all models (such as downloading or saving).
125
+
126
+ Parameters:
127
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
128
+ Height and width of input/output sample.
129
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
130
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
131
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
132
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
133
+ Whether to flip the sin to cos in the time embedding.
134
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
135
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
136
+ The tuple of downsample blocks to use.
137
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
138
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
139
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
140
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
141
+ The tuple of upsample blocks to use.
142
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
143
+ Whether to include self-attention in the basic transformer blocks, see
144
+ [`~models.attention.BasicTransformerBlock`].
145
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
146
+ The tuple of output channels for each block.
147
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
148
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
149
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
150
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
151
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
152
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
153
+ If `None`, normalization and activation layers is skipped in post-processing.
154
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
155
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
156
+ The dimension of the cross attention features.
157
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
158
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
159
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
160
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
161
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
162
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
163
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
164
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
165
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
166
+ encoder_hid_dim (`int`, *optional*, defaults to None):
167
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
168
+ dimension to `cross_attention_dim`.
169
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
170
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
171
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
172
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
173
+ num_attention_heads (`int`, *optional*):
174
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
175
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
176
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
177
+ class_embed_type (`str`, *optional*, defaults to `None`):
178
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
179
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
180
+ addition_embed_type (`str`, *optional*, defaults to `None`):
181
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
182
+ "text". "text" will use the `TextTimeEmbedding` layer.
183
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
184
+ Dimension for the timestep embeddings.
185
+ num_class_embeds (`int`, *optional*, defaults to `None`):
186
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
187
+ class conditioning with `class_embed_type` equal to `None`.
188
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
189
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
190
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
191
+ An optional override for the dimension of the projected time embedding.
192
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
193
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
194
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
195
+ timestep_post_act (`str`, *optional*, defaults to `None`):
196
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
197
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
198
+ The dimension of `cond_proj` layer in the timestep embedding.
199
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
200
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
201
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
202
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
203
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
204
+ embeddings with the class embeddings.
205
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
206
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
207
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
208
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
209
+ otherwise.
210
+ """
211
+
212
+ _supports_gradient_checkpointing = True
213
+ _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
214
+
215
+ @register_to_config
216
+ def __init__(
217
+ self,
218
+ sample_size: Optional[int] = None,
219
+ in_channels: int = 8,
220
+ out_channels: int = 8,
221
+ center_input_sample: bool = False,
222
+ flip_sin_to_cos: bool = True,
223
+ freq_shift: int = 0,
224
+ down_block_types: Tuple[str] = (
225
+ "CrossAttnDownBlock2D",
226
+ "CrossAttnDownBlock2D",
227
+ "CrossAttnDownBlock2D",
228
+ "DownBlock2D",
229
+ ),
230
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
231
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
232
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
233
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
234
+ layers_per_block: Union[int, Tuple[int]] = 2,
235
+ downsample_padding: int = 1,
236
+ mid_block_scale_factor: float = 1,
237
+ dropout: float = 0.0,
238
+ act_fn: str = "silu",
239
+ norm_num_groups: Optional[int] = 32,
240
+ norm_eps: float = 1e-5,
241
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
242
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
243
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
244
+ encoder_hid_dim: Optional[int] = None,
245
+ encoder_hid_dim_type: Optional[str] = None,
246
+ attention_head_dim: Union[int, Tuple[int]] = 8,
247
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
248
+ dual_cross_attention: bool = False,
249
+ use_linear_projection: bool = False,
250
+ class_embed_type: Optional[str] = None,
251
+ addition_embed_type: Optional[str] = None,
252
+ addition_time_embed_dim: Optional[int] = None,
253
+ num_class_embeds: Optional[int] = None,
254
+ upcast_attention: bool = False,
255
+ resnet_time_scale_shift: str = "default",
256
+ resnet_skip_time_act: bool = False,
257
+ resnet_out_scale_factor: float = 1.0,
258
+ time_embedding_type: str = "positional",
259
+ time_embedding_dim: Optional[int] = None,
260
+ time_embedding_act_fn: Optional[str] = None,
261
+ timestep_post_act: Optional[str] = None,
262
+ time_cond_proj_dim: Optional[int] = None,
263
+ conv_in_kernel: int = 3,
264
+ conv_out_kernel: int = 3,
265
+ projection_class_embeddings_input_dim: Optional[int] = None,
266
+ attention_type: str = "default",
267
+ class_embeddings_concat: bool = False,
268
+ mid_block_only_cross_attention: Optional[bool] = None,
269
+ cross_attention_norm: Optional[str] = None,
270
+ addition_embed_type_num_heads: int = 64,
271
+ ):
272
+ super().__init__()
273
+
274
+ self.sample_size = sample_size
275
+
276
+ if num_attention_heads is not None:
277
+ raise ValueError(
278
+ "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."
279
+ )
280
+
281
+ # If `num_attention_heads` is not defined (which is the case for most models)
282
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
283
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
284
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
285
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
286
+ # which is why we correct for the naming here.
287
+ num_attention_heads = num_attention_heads or attention_head_dim
288
+
289
+ # Check inputs
290
+ self._check_config(
291
+ down_block_types=down_block_types,
292
+ up_block_types=up_block_types,
293
+ only_cross_attention=only_cross_attention,
294
+ block_out_channels=block_out_channels,
295
+ layers_per_block=layers_per_block,
296
+ cross_attention_dim=cross_attention_dim,
297
+ transformer_layers_per_block=transformer_layers_per_block,
298
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
299
+ attention_head_dim=attention_head_dim,
300
+ num_attention_heads=num_attention_heads,
301
+ )
302
+
303
+ # input
304
+ conv_in_padding = (conv_in_kernel - 1) // 2
305
+ self.conv_in_img = nn.Conv2d(
306
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
307
+ )
308
+ self.conv_in_dem = nn.Conv2d(
309
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
310
+ )
311
+
312
+ # time
313
+ time_embed_dim, timestep_input_dim = self._set_time_proj(
314
+ time_embedding_type,
315
+ block_out_channels=block_out_channels,
316
+ flip_sin_to_cos=flip_sin_to_cos,
317
+ freq_shift=freq_shift,
318
+ time_embedding_dim=time_embedding_dim,
319
+ )
320
+
321
+ self.time_embedding = TimestepEmbedding(
322
+ timestep_input_dim,
323
+ time_embed_dim,
324
+ act_fn=act_fn,
325
+ post_act_fn=timestep_post_act,
326
+ cond_proj_dim=time_cond_proj_dim,
327
+ )
328
+
329
+ self._set_encoder_hid_proj(
330
+ encoder_hid_dim_type,
331
+ cross_attention_dim=cross_attention_dim,
332
+ encoder_hid_dim=encoder_hid_dim,
333
+ )
334
+
335
+ # class embedding
336
+ self._set_class_embedding(
337
+ class_embed_type,
338
+ act_fn=act_fn,
339
+ num_class_embeds=num_class_embeds,
340
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
341
+ time_embed_dim=time_embed_dim,
342
+ timestep_input_dim=timestep_input_dim,
343
+ )
344
+
345
+ self._set_add_embedding(
346
+ addition_embed_type,
347
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
348
+ addition_time_embed_dim=addition_time_embed_dim,
349
+ cross_attention_dim=cross_attention_dim,
350
+ encoder_hid_dim=encoder_hid_dim,
351
+ flip_sin_to_cos=flip_sin_to_cos,
352
+ freq_shift=freq_shift,
353
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
354
+ time_embed_dim=time_embed_dim,
355
+ )
356
+
357
+ if time_embedding_act_fn is None:
358
+ self.time_embed_act = None
359
+ else:
360
+ self.time_embed_act = get_activation(time_embedding_act_fn)
361
+
362
+ self.down_blocks = nn.ModuleList([])
363
+ self.up_blocks = nn.ModuleList([])
364
+
365
+ if isinstance(only_cross_attention, bool):
366
+ if mid_block_only_cross_attention is None:
367
+ mid_block_only_cross_attention = only_cross_attention
368
+
369
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
370
+
371
+ if mid_block_only_cross_attention is None:
372
+ mid_block_only_cross_attention = False
373
+
374
+ if isinstance(num_attention_heads, int):
375
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
376
+
377
+ if isinstance(attention_head_dim, int):
378
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
379
+
380
+ if isinstance(cross_attention_dim, int):
381
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
382
+
383
+ if isinstance(layers_per_block, int):
384
+ layers_per_block = [layers_per_block] * len(down_block_types)
385
+
386
+ if isinstance(transformer_layers_per_block, int):
387
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
388
+
389
+ if class_embeddings_concat:
390
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
391
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
392
+ # regular time embeddings
393
+ blocks_time_embed_dim = time_embed_dim * 2
394
+ else:
395
+ blocks_time_embed_dim = time_embed_dim
396
+
397
+ # down
398
+ output_channel = block_out_channels[0]
399
+
400
+
401
+ for i, down_block_type in enumerate(down_block_types):
402
+ input_channel = output_channel
403
+ output_channel = block_out_channels[i]
404
+ is_final_block = i == len(block_out_channels) - 1
405
+ down_block_kwargs = {"down_block_type":down_block_type,
406
+ "num_layers":layers_per_block[i],
407
+ "transformer_layers_per_block":transformer_layers_per_block[i],
408
+ "in_channels":input_channel,
409
+ "out_channels":output_channel,
410
+ "temb_channels":blocks_time_embed_dim,
411
+ "add_downsample":not is_final_block,
412
+ "resnet_eps":norm_eps,
413
+ "resnet_act_fn":act_fn,
414
+ "resnet_groups":norm_num_groups,
415
+ "cross_attention_dim":cross_attention_dim[i],
416
+ "num_attention_heads":num_attention_heads[i],
417
+ "downsample_padding":downsample_padding,
418
+ "dual_cross_attention":dual_cross_attention,
419
+ "use_linear_projection":use_linear_projection,
420
+ "only_cross_attention":only_cross_attention[i],
421
+ "upcast_attention":upcast_attention,
422
+ "resnet_time_scale_shift":resnet_time_scale_shift,
423
+ "attention_type":attention_type,
424
+ "resnet_skip_time_act":resnet_skip_time_act,
425
+ "resnet_out_scale_factor":resnet_out_scale_factor,
426
+ "cross_attention_norm":cross_attention_norm,
427
+ "attention_head_dim":attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
428
+ "dropout":dropout}
429
+
430
+ if i == 0:
431
+ self.head_img = get_down_block(**down_block_kwargs)
432
+ # same architecture as the head_img but different weights
433
+ self.head_dem = get_down_block(**down_block_kwargs)
434
+ # elif i == 1:
435
+ # down_block_kwargs["in_channels"] = input_channel *2 # concatenate the output of the head_img and head_dem
436
+ # down_block = get_down_block(**down_block_kwargs)
437
+ # self.down_blocks.append(down_block)
438
+ else:
439
+ down_block = get_down_block(**down_block_kwargs)
440
+ self.down_blocks.append(down_block)
441
+
442
+ # mid
443
+ self.mid_block = get_mid_block(
444
+ mid_block_type,
445
+ temb_channels=blocks_time_embed_dim,
446
+ in_channels=block_out_channels[-1],
447
+ resnet_eps=norm_eps,
448
+ resnet_act_fn=act_fn,
449
+ resnet_groups=norm_num_groups,
450
+ output_scale_factor=mid_block_scale_factor,
451
+ transformer_layers_per_block=transformer_layers_per_block[-1],
452
+ num_attention_heads=num_attention_heads[-1],
453
+ cross_attention_dim=cross_attention_dim[-1],
454
+ dual_cross_attention=dual_cross_attention,
455
+ use_linear_projection=use_linear_projection,
456
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
457
+ upcast_attention=upcast_attention,
458
+ resnet_time_scale_shift=resnet_time_scale_shift,
459
+ attention_type=attention_type,
460
+ resnet_skip_time_act=resnet_skip_time_act,
461
+ cross_attention_norm=cross_attention_norm,
462
+ attention_head_dim=attention_head_dim[-1],
463
+ dropout=dropout,
464
+ )
465
+
466
+ # count how many layers upsample the images
467
+ self.num_upsamplers = 0
468
+
469
+ # up
470
+ reversed_block_out_channels = list(reversed(block_out_channels))
471
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
472
+ reversed_layers_per_block = list(reversed(layers_per_block))
473
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
474
+ reversed_transformer_layers_per_block = (
475
+ list(reversed(transformer_layers_per_block))
476
+ if reverse_transformer_layers_per_block is None
477
+ else reverse_transformer_layers_per_block
478
+ )
479
+ only_cross_attention = list(reversed(only_cross_attention))
480
+
481
+ output_channel = reversed_block_out_channels[0]
482
+ for i, up_block_type in enumerate(up_block_types):
483
+ is_final_block = i == len(block_out_channels) - 1
484
+
485
+ prev_output_channel = output_channel
486
+ output_channel = reversed_block_out_channels[i]
487
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
488
+
489
+ # add upsample block for all BUT final layer
490
+ if not is_final_block:
491
+ add_upsample = True
492
+ self.num_upsamplers += 1
493
+ else:
494
+ add_upsample = False
495
+
496
+ up_block_kwargs = {"up_block_type":up_block_type,
497
+ "num_layers":reversed_layers_per_block[i] + 1,
498
+ "transformer_layers_per_block":reversed_transformer_layers_per_block[i],
499
+ "in_channels":input_channel,
500
+ "out_channels":output_channel,
501
+ "prev_output_channel":prev_output_channel,
502
+ "temb_channels":blocks_time_embed_dim,
503
+ "add_upsample":add_upsample,
504
+ "resnet_eps":norm_eps,
505
+ "resnet_act_fn":act_fn,
506
+ "resolution_idx":i,
507
+ "resnet_groups":norm_num_groups,
508
+ "cross_attention_dim":reversed_cross_attention_dim[i],
509
+ "num_attention_heads":reversed_num_attention_heads[i],
510
+ "dual_cross_attention":dual_cross_attention,
511
+ "use_linear_projection":use_linear_projection,
512
+ "only_cross_attention":only_cross_attention[i],
513
+ "upcast_attention":upcast_attention,
514
+ "resnet_time_scale_shift":resnet_time_scale_shift,
515
+ "attention_type":attention_type,
516
+ "resnet_skip_time_act":resnet_skip_time_act,
517
+ "resnet_out_scale_factor":resnet_out_scale_factor,
518
+ "cross_attention_norm":cross_attention_norm,
519
+ "attention_head_dim":attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
520
+ "dropout":dropout,}
521
+
522
+ # if i == len(block_out_channels) - 2:
523
+ # up_block_kwargs["in_channels"] = input_channel*2
524
+ # up_block = get_up_block(**up_block_kwargs)
525
+ # self.up_blocks.append(up_block)
526
+
527
+ if is_final_block :
528
+
529
+ self.head_out_img = get_up_block(**up_block_kwargs)
530
+ self.head_out_dem = get_up_block(**up_block_kwargs)
531
+
532
+ else :
533
+ up_block = get_up_block(**up_block_kwargs)
534
+ self.up_blocks.append(up_block)
535
+
536
+
537
+ # out
538
+ if norm_num_groups is not None:
539
+ self.conv_norm_out_img = nn.GroupNorm(
540
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
541
+ )
542
+ self.conv_norm_out_dem = nn.GroupNorm(
543
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
544
+ )
545
+
546
+ self.conv_act = get_activation(act_fn)
547
+
548
+ else:
549
+ self.conv_norm_out_img = None
550
+ self.conv_norm_out_dem = None
551
+ self.conv_act = None
552
+
553
+ conv_out_padding = (conv_out_kernel - 1) // 2
554
+ self.conv_out_img = nn.Conv2d(
555
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
556
+ )
557
+ self.conv_out_dem = nn.Conv2d(
558
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
559
+ )
560
+
561
+ self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
562
+
563
+ def _check_config(
564
+ self,
565
+ down_block_types: Tuple[str],
566
+ up_block_types: Tuple[str],
567
+ only_cross_attention: Union[bool, Tuple[bool]],
568
+ block_out_channels: Tuple[int],
569
+ layers_per_block: Union[int, Tuple[int]],
570
+ cross_attention_dim: Union[int, Tuple[int]],
571
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
572
+ reverse_transformer_layers_per_block: bool,
573
+ attention_head_dim: int,
574
+ num_attention_heads: Optional[Union[int, Tuple[int]]],
575
+ ):
576
+ if len(down_block_types) != len(up_block_types):
577
+ raise ValueError(
578
+ 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}."
579
+ )
580
+
581
+ if len(block_out_channels) != len(down_block_types):
582
+ raise ValueError(
583
+ 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}."
584
+ )
585
+
586
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
587
+ raise ValueError(
588
+ 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}."
589
+ )
590
+
591
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
592
+ raise ValueError(
593
+ 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}."
594
+ )
595
+
596
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
597
+ raise ValueError(
598
+ 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}."
599
+ )
600
+
601
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
602
+ raise ValueError(
603
+ 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}."
604
+ )
605
+
606
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
607
+ raise ValueError(
608
+ 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}."
609
+ )
610
+ if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
611
+ for layer_number_per_block in transformer_layers_per_block:
612
+ if isinstance(layer_number_per_block, list):
613
+ raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
614
+
615
+ def _set_time_proj(
616
+ self,
617
+ time_embedding_type: str,
618
+ block_out_channels: int,
619
+ flip_sin_to_cos: bool,
620
+ freq_shift: float,
621
+ time_embedding_dim: int,
622
+ ) -> Tuple[int, int]:
623
+ if time_embedding_type == "fourier":
624
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
625
+ if time_embed_dim % 2 != 0:
626
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
627
+ self.time_proj = GaussianFourierProjection(
628
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
629
+ )
630
+ timestep_input_dim = time_embed_dim
631
+ elif time_embedding_type == "positional":
632
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
633
+
634
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
635
+ timestep_input_dim = block_out_channels[0]
636
+ else:
637
+ raise ValueError(
638
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
639
+ )
640
+
641
+ return time_embed_dim, timestep_input_dim
642
+
643
+ def _set_encoder_hid_proj(
644
+ self,
645
+ encoder_hid_dim_type: Optional[str],
646
+ cross_attention_dim: Union[int, Tuple[int]],
647
+ encoder_hid_dim: Optional[int],
648
+ ):
649
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
650
+ encoder_hid_dim_type = "text_proj"
651
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
652
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
653
+
654
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
655
+ raise ValueError(
656
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
657
+ )
658
+
659
+ if encoder_hid_dim_type == "text_proj":
660
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
661
+ elif encoder_hid_dim_type == "text_image_proj":
662
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
663
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
664
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
665
+ self.encoder_hid_proj = TextImageProjection(
666
+ text_embed_dim=encoder_hid_dim,
667
+ image_embed_dim=cross_attention_dim,
668
+ cross_attention_dim=cross_attention_dim,
669
+ )
670
+ elif encoder_hid_dim_type == "image_proj":
671
+ # Kandinsky 2.2
672
+ self.encoder_hid_proj = ImageProjection(
673
+ image_embed_dim=encoder_hid_dim,
674
+ cross_attention_dim=cross_attention_dim,
675
+ )
676
+ elif encoder_hid_dim_type is not None:
677
+ raise ValueError(
678
+ f"`encoder_hid_dim_type`: {encoder_hid_dim_type} must be None, 'text_proj', 'text_image_proj', or 'image_proj'."
679
+ )
680
+ else:
681
+ self.encoder_hid_proj = None
682
+
683
+ def _set_class_embedding(
684
+ self,
685
+ class_embed_type: Optional[str],
686
+ act_fn: str,
687
+ num_class_embeds: Optional[int],
688
+ projection_class_embeddings_input_dim: Optional[int],
689
+ time_embed_dim: int,
690
+ timestep_input_dim: int,
691
+ ):
692
+ if class_embed_type is None and num_class_embeds is not None:
693
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
694
+ elif class_embed_type == "timestep":
695
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
696
+ elif class_embed_type == "identity":
697
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
698
+ elif class_embed_type == "projection":
699
+ if projection_class_embeddings_input_dim is None:
700
+ raise ValueError(
701
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
702
+ )
703
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
704
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
705
+ # 2. it projects from an arbitrary input dimension.
706
+ #
707
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
708
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
709
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
710
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
711
+ elif class_embed_type == "simple_projection":
712
+ if projection_class_embeddings_input_dim is None:
713
+ raise ValueError(
714
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
715
+ )
716
+ self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
717
+ else:
718
+ self.class_embedding = None
719
+
720
+ def _set_add_embedding(
721
+ self,
722
+ addition_embed_type: str,
723
+ addition_embed_type_num_heads: int,
724
+ addition_time_embed_dim: Optional[int],
725
+ flip_sin_to_cos: bool,
726
+ freq_shift: float,
727
+ cross_attention_dim: Optional[int],
728
+ encoder_hid_dim: Optional[int],
729
+ projection_class_embeddings_input_dim: Optional[int],
730
+ time_embed_dim: int,
731
+ ):
732
+ if addition_embed_type == "text":
733
+ if encoder_hid_dim is not None:
734
+ text_time_embedding_from_dim = encoder_hid_dim
735
+ else:
736
+ text_time_embedding_from_dim = cross_attention_dim
737
+
738
+ self.add_embedding = TextTimeEmbedding(
739
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
740
+ )
741
+ elif addition_embed_type == "text_image":
742
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
743
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
744
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
745
+ self.add_embedding = TextImageTimeEmbedding(
746
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
747
+ )
748
+ elif addition_embed_type == "text_time":
749
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
750
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
751
+ elif addition_embed_type == "image":
752
+ # Kandinsky 2.2
753
+ self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
754
+ elif addition_embed_type == "image_hint":
755
+ # Kandinsky 2.2 ControlNet
756
+ self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
757
+ elif addition_embed_type is not None:
758
+ raise ValueError(
759
+ f"`addition_embed_type`: {addition_embed_type} must be None, 'text', 'text_image', 'text_time', 'image', or 'image_hint'."
760
+ )
761
+
762
+ def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
763
+ if attention_type in ["gated", "gated-text-image"]:
764
+ positive_len = 768
765
+ if isinstance(cross_attention_dim, int):
766
+ positive_len = cross_attention_dim
767
+ elif isinstance(cross_attention_dim, (list, tuple)):
768
+ positive_len = cross_attention_dim[0]
769
+
770
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
771
+ self.position_net = GLIGENTextBoundingboxProjection(
772
+ positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
773
+ )
774
+
775
+ @property
776
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
777
+ r"""
778
+ Returns:
779
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
780
+ indexed by its weight name.
781
+ """
782
+ # set recursively
783
+ processors = {}
784
+
785
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
786
+ if hasattr(module, "get_processor"):
787
+ processors[f"{name}.processor"] = module.get_processor()
788
+
789
+ for sub_name, child in module.named_children():
790
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
791
+
792
+ return processors
793
+
794
+ for name, module in self.named_children():
795
+ fn_recursive_add_processors(name, module, processors)
796
+
797
+ return processors
798
+
799
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
800
+ r"""
801
+ Sets the attention processor to use to compute attention.
802
+
803
+ Parameters:
804
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
805
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
806
+ for **all** `Attention` layers.
807
+
808
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
809
+ processor. This is strongly recommended when setting trainable attention processors.
810
+
811
+ """
812
+ count = len(self.attn_processors.keys())
813
+
814
+ if isinstance(processor, dict) and len(processor) != count:
815
+ raise ValueError(
816
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
817
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
818
+ )
819
+
820
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
821
+ if hasattr(module, "set_processor"):
822
+ if not isinstance(processor, dict):
823
+ module.set_processor(processor)
824
+ else:
825
+ module.set_processor(processor.pop(f"{name}.processor"))
826
+
827
+ for sub_name, child in module.named_children():
828
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
829
+
830
+ for name, module in self.named_children():
831
+ fn_recursive_attn_processor(name, module, processor)
832
+
833
+ def set_default_attn_processor(self):
834
+ """
835
+ Disables custom attention processors and sets the default attention implementation.
836
+ """
837
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
838
+ processor = AttnAddedKVProcessor()
839
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
840
+ processor = AttnProcessor()
841
+ else:
842
+ raise ValueError(
843
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
844
+ )
845
+
846
+ self.set_attn_processor(processor)
847
+
848
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
849
+ r"""
850
+ Enable sliced attention computation.
851
+
852
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
853
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
854
+
855
+ Args:
856
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
857
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
858
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
859
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
860
+ must be a multiple of `slice_size`.
861
+ """
862
+ sliceable_head_dims = []
863
+
864
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
865
+ if hasattr(module, "set_attention_slice"):
866
+ sliceable_head_dims.append(module.sliceable_head_dim)
867
+
868
+ for child in module.children():
869
+ fn_recursive_retrieve_sliceable_dims(child)
870
+
871
+ # retrieve number of attention layers
872
+ for module in self.children():
873
+ fn_recursive_retrieve_sliceable_dims(module)
874
+
875
+ num_sliceable_layers = len(sliceable_head_dims)
876
+
877
+ if slice_size == "auto":
878
+ # half the attention head size is usually a good trade-off between
879
+ # speed and memory
880
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
881
+ elif slice_size == "max":
882
+ # make smallest slice possible
883
+ slice_size = num_sliceable_layers * [1]
884
+
885
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
886
+
887
+ if len(slice_size) != len(sliceable_head_dims):
888
+ raise ValueError(
889
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
890
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
891
+ )
892
+
893
+ for i in range(len(slice_size)):
894
+ size = slice_size[i]
895
+ dim = sliceable_head_dims[i]
896
+ if size is not None and size > dim:
897
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
898
+
899
+ # Recursively walk through all the children.
900
+ # Any children which exposes the set_attention_slice method
901
+ # gets the message
902
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
903
+ if hasattr(module, "set_attention_slice"):
904
+ module.set_attention_slice(slice_size.pop())
905
+
906
+ for child in module.children():
907
+ fn_recursive_set_attention_slice(child, slice_size)
908
+
909
+ reversed_slice_size = list(reversed(slice_size))
910
+ for module in self.children():
911
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
912
+
913
+ def _set_gradient_checkpointing(self, module, value=False):
914
+ if hasattr(module, "gradient_checkpointing"):
915
+ module.gradient_checkpointing = value
916
+
917
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
918
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
919
+
920
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
921
+
922
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
923
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
924
+
925
+ Args:
926
+ s1 (`float`):
927
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
928
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
929
+ s2 (`float`):
930
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
931
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
932
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
933
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
934
+ """
935
+ for i, upsample_block in enumerate(self.up_blocks):
936
+ setattr(upsample_block, "s1", s1)
937
+ setattr(upsample_block, "s2", s2)
938
+ setattr(upsample_block, "b1", b1)
939
+ setattr(upsample_block, "b2", b2)
940
+
941
+ def disable_freeu(self):
942
+ """Disables the FreeU mechanism."""
943
+ freeu_keys = {"s1", "s2", "b1", "b2"}
944
+ for i, upsample_block in enumerate(self.up_blocks):
945
+ for k in freeu_keys:
946
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
947
+ setattr(upsample_block, k, None)
948
+
949
+ def fuse_qkv_projections(self):
950
+ """
951
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
952
+ are fused. For cross-attention modules, key and value projection matrices are fused.
953
+
954
+ <Tip warning={true}>
955
+
956
+ This API is 🧪 experimental.
957
+
958
+ </Tip>
959
+ """
960
+ self.original_attn_processors = None
961
+
962
+ for _, attn_processor in self.attn_processors.items():
963
+ if "Added" in str(attn_processor.__class__.__name__):
964
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
965
+
966
+ self.original_attn_processors = self.attn_processors
967
+
968
+ for module in self.modules():
969
+ if isinstance(module, Attention):
970
+ module.fuse_projections(fuse=True)
971
+
972
+ self.set_attn_processor(FusedAttnProcessor2_0())
973
+
974
+ def unfuse_qkv_projections(self):
975
+ """Disables the fused QKV projection if enabled.
976
+
977
+ <Tip warning={true}>
978
+
979
+ This API is 🧪 experimental.
980
+
981
+ </Tip>
982
+
983
+ """
984
+ if self.original_attn_processors is not None:
985
+ self.set_attn_processor(self.original_attn_processors)
986
+
987
+ def get_time_embed(
988
+ self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
989
+ ) -> Optional[torch.Tensor]:
990
+ timesteps = timestep
991
+ if not torch.is_tensor(timesteps):
992
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
993
+ # This would be a good case for the `match` statement (Python 3.10+)
994
+ is_mps = sample.device.type == "mps"
995
+ if isinstance(timestep, float):
996
+ dtype = torch.float32 if is_mps else torch.float64
997
+ else:
998
+ dtype = torch.int32 if is_mps else torch.int64
999
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1000
+ elif len(timesteps.shape) == 0:
1001
+ timesteps = timesteps[None].to(sample.device)
1002
+
1003
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1004
+ timesteps = timesteps.expand(sample.shape[0])
1005
+
1006
+ t_emb = self.time_proj(timesteps)
1007
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1008
+ # but time_embedding might actually be running in fp16. so we need to cast here.
1009
+ # there might be better ways to encapsulate this.
1010
+ t_emb = t_emb.to(dtype=sample.dtype)
1011
+ return t_emb
1012
+
1013
+ def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
1014
+ class_emb = None
1015
+ if self.class_embedding is not None:
1016
+ if class_labels is None:
1017
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
1018
+
1019
+ if self.config.class_embed_type == "timestep":
1020
+ class_labels = self.time_proj(class_labels)
1021
+
1022
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1023
+ # there might be better ways to encapsulate this.
1024
+ class_labels = class_labels.to(dtype=sample.dtype)
1025
+
1026
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
1027
+ return class_emb
1028
+
1029
+ def get_aug_embed(
1030
+ self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1031
+ ) -> Optional[torch.Tensor]:
1032
+ aug_emb = None
1033
+ if self.config.addition_embed_type == "text":
1034
+ aug_emb = self.add_embedding(encoder_hidden_states)
1035
+ elif self.config.addition_embed_type == "text_image":
1036
+ # Kandinsky 2.1 - style
1037
+ if "image_embeds" not in added_cond_kwargs:
1038
+ raise ValueError(
1039
+ 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`"
1040
+ )
1041
+
1042
+ image_embs = added_cond_kwargs.get("image_embeds")
1043
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
1044
+ aug_emb = self.add_embedding(text_embs, image_embs)
1045
+ elif self.config.addition_embed_type == "text_time":
1046
+ # SDXL - style
1047
+ if "text_embeds" not in added_cond_kwargs:
1048
+ raise ValueError(
1049
+ 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`"
1050
+ )
1051
+ text_embeds = added_cond_kwargs.get("text_embeds")
1052
+ if "time_ids" not in added_cond_kwargs:
1053
+ raise ValueError(
1054
+ 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`"
1055
+ )
1056
+ time_ids = added_cond_kwargs.get("time_ids")
1057
+ time_embeds = self.add_time_proj(time_ids.flatten())
1058
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1059
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1060
+ add_embeds = add_embeds.to(emb.dtype)
1061
+ aug_emb = self.add_embedding(add_embeds)
1062
+ elif self.config.addition_embed_type == "image":
1063
+ # Kandinsky 2.2 - style
1064
+ if "image_embeds" not in added_cond_kwargs:
1065
+ raise ValueError(
1066
+ 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`"
1067
+ )
1068
+ image_embs = added_cond_kwargs.get("image_embeds")
1069
+ aug_emb = self.add_embedding(image_embs)
1070
+ elif self.config.addition_embed_type == "image_hint":
1071
+ # Kandinsky 2.2 ControlNet - style
1072
+ if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1073
+ raise ValueError(
1074
+ 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`"
1075
+ )
1076
+ image_embs = added_cond_kwargs.get("image_embeds")
1077
+ hint = added_cond_kwargs.get("hint")
1078
+ aug_emb = self.add_embedding(image_embs, hint)
1079
+ return aug_emb
1080
+
1081
+ def process_encoder_hidden_states(
1082
+ self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1083
+ ) -> torch.Tensor:
1084
+ if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1085
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1086
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1087
+ # Kandinsky 2.1 - style
1088
+ if "image_embeds" not in added_cond_kwargs:
1089
+ raise ValueError(
1090
+ 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_cond_kwargs`"
1091
+ )
1092
+
1093
+ image_embeds = added_cond_kwargs.get("image_embeds")
1094
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1095
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1096
+ # Kandinsky 2.2 - style
1097
+ if "image_embeds" not in added_cond_kwargs:
1098
+ raise ValueError(
1099
+ 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_cond_kwargs`"
1100
+ )
1101
+ image_embeds = added_cond_kwargs.get("image_embeds")
1102
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1103
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1104
+ if "image_embeds" not in added_cond_kwargs:
1105
+ raise ValueError(
1106
+ 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_cond_kwargs`"
1107
+ )
1108
+
1109
+ if hasattr(self, "text_encoder_hid_proj") and self.text_encoder_hid_proj is not None:
1110
+ encoder_hidden_states = self.text_encoder_hid_proj(encoder_hidden_states)
1111
+
1112
+ image_embeds = added_cond_kwargs.get("image_embeds")
1113
+ image_embeds = self.encoder_hid_proj(image_embeds)
1114
+ encoder_hidden_states = (encoder_hidden_states, image_embeds)
1115
+ return encoder_hidden_states
1116
+
1117
+ def forward(
1118
+ self,
1119
+ sample: torch.Tensor,
1120
+ timestep: Union[torch.Tensor, float, int],
1121
+ encoder_hidden_states: torch.Tensor,
1122
+ class_labels: Optional[torch.Tensor] = None,
1123
+ timestep_cond: Optional[torch.Tensor] = None,
1124
+ attention_mask: Optional[torch.Tensor] = None,
1125
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1126
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1127
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1128
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
1129
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1130
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1131
+ return_dict: bool = True,
1132
+ ) -> Union[UNet2DConditionOutput, Tuple]:
1133
+ r"""
1134
+ The [`UNet2DConditionModel`] forward method.
1135
+
1136
+ Args:
1137
+ sample (`torch.Tensor`):
1138
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
1139
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
1140
+ encoder_hidden_states (`torch.Tensor`):
1141
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1142
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1143
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1144
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1145
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1146
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
1147
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1148
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1149
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1150
+ negative values to the attention scores corresponding to "discard" tokens.
1151
+ cross_attention_kwargs (`dict`, *optional*):
1152
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1153
+ `self.processor` in
1154
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1155
+ added_cond_kwargs: (`dict`, *optional*):
1156
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1157
+ are passed along to the UNet blocks.
1158
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1159
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
1160
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
1161
+ A tensor that if specified is added to the residual of the middle unet block.
1162
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1163
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1164
+ encoder_attention_mask (`torch.Tensor`):
1165
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1166
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1167
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
1168
+ return_dict (`bool`, *optional*, defaults to `True`):
1169
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1170
+ tuple.
1171
+
1172
+ Returns:
1173
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1174
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1175
+ otherwise a `tuple` is returned where the first element is the sample tensor.
1176
+ """
1177
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
1178
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1179
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
1180
+ # on the fly if necessary.
1181
+ default_overall_up_factor = 2**self.num_upsamplers
1182
+
1183
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1184
+ forward_upsample_size = False
1185
+ upsample_size = None
1186
+
1187
+ for dim in sample.shape[-2:]:
1188
+ if dim % default_overall_up_factor != 0:
1189
+ # Forward upsample size to force interpolation output size.
1190
+ forward_upsample_size = True
1191
+ break
1192
+
1193
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1194
+ # expects mask of shape:
1195
+ # [batch, key_tokens]
1196
+ # adds singleton query_tokens dimension:
1197
+ # [batch, 1, key_tokens]
1198
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1199
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1200
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1201
+ if attention_mask is not None:
1202
+ # assume that mask is expressed as:
1203
+ # (1 = keep, 0 = discard)
1204
+ # convert mask into a bias that can be added to attention scores:
1205
+ # (keep = +0, discard = -10000.0)
1206
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1207
+ attention_mask = attention_mask.unsqueeze(1)
1208
+
1209
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
1210
+ if encoder_attention_mask is not None:
1211
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1212
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1213
+
1214
+ # 0. center input if necessary
1215
+ if self.config.center_input_sample:
1216
+ sample = 2 * sample - 1.0
1217
+
1218
+ # 1. time
1219
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1220
+ emb = self.time_embedding(t_emb, timestep_cond)
1221
+
1222
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1223
+ if class_emb is not None:
1224
+ if self.config.class_embeddings_concat:
1225
+ emb = torch.cat([emb, class_emb], dim=-1)
1226
+ else:
1227
+ emb = emb + class_emb
1228
+
1229
+ aug_emb = self.get_aug_embed(
1230
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1231
+ )
1232
+ if self.config.addition_embed_type == "image_hint":
1233
+ aug_emb, hint = aug_emb
1234
+ sample = torch.cat([sample, hint], dim=1)
1235
+
1236
+
1237
+ emb = emb + aug_emb if aug_emb is not None else emb
1238
+
1239
+ if self.time_embed_act is not None:
1240
+ emb = self.time_embed_act(emb)
1241
+
1242
+ encoder_hidden_states = self.process_encoder_hidden_states(
1243
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1244
+ )
1245
+
1246
+ sample_img = sample[:, :4, :, :]
1247
+ sample_dem = sample[:, 4:, :, :]
1248
+ # 2. pre-process using the two different heads
1249
+ sample_img = self.conv_in_img(sample_img)
1250
+ sample_dem = self.conv_in_dem(sample_dem)
1251
+
1252
+ # 2.5 GLIGEN position net
1253
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1254
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1255
+ gligen_args = cross_attention_kwargs.pop("gligen")
1256
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1257
+
1258
+ # 3. down
1259
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1260
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1261
+ if cross_attention_kwargs is not None:
1262
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1263
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1264
+ else:
1265
+ lora_scale = 1.0
1266
+
1267
+ if USE_PEFT_BACKEND:
1268
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1269
+ scale_lora_layers(self, lora_scale)
1270
+
1271
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1272
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1273
+ is_adapter = down_intrablock_additional_residuals is not None
1274
+ if (down_intrablock_additional_residuals is not None) or is_adapter:
1275
+ raise NotImplementedError("additional_residuals")
1276
+
1277
+
1278
+ # go through the heads
1279
+ head_img_res_sample = (sample_img,)
1280
+ # RGB head
1281
+ if hasattr(self.head_img, "has_cross_attention") and self.head_img.has_cross_attention:
1282
+ # For t2i-adapter CrossAttnDownBlock2D
1283
+ additional_residuals = {}
1284
+ sample_img, res_samples_img = self.head_img(
1285
+ hidden_states=sample_img,
1286
+ temb=emb,
1287
+ encoder_hidden_states=encoder_hidden_states,
1288
+ attention_mask=attention_mask,
1289
+ cross_attention_kwargs=cross_attention_kwargs,
1290
+ encoder_attention_mask=encoder_attention_mask,
1291
+ **additional_residuals,
1292
+ )
1293
+ else:
1294
+ sample_img, res_samples_img = self.head_img(hidden_states=sample, temb=emb)
1295
+ head_img_res_sample += res_samples_img[:2]
1296
+
1297
+
1298
+
1299
+ head_dem_res_sample = (sample_dem,)
1300
+ # DEM head
1301
+ if hasattr(self.head_dem, "has_cross_attention") and self.head_dem.has_cross_attention:
1302
+ # For t2i-adapter CrossAttnDownBlock2D
1303
+ additional_residuals = {}
1304
+
1305
+ sample_dem, res_samples_dem = self.head_dem(
1306
+ hidden_states=sample_dem,
1307
+ temb=emb,
1308
+ encoder_hidden_states=encoder_hidden_states,
1309
+ attention_mask=attention_mask,
1310
+ cross_attention_kwargs=cross_attention_kwargs,
1311
+ encoder_attention_mask=encoder_attention_mask,
1312
+ **additional_residuals,
1313
+ )
1314
+ else:
1315
+ # sample_dem, res_samples_dem = self.head_dem(hidden_states=sample, temb=emb)
1316
+ sample_dem, res_samples_dem = self.head_img(hidden_states=sample, temb=emb) # shared weights
1317
+
1318
+ head_dem_res_sample += res_samples_dem[:2]
1319
+
1320
+ #average the two heads and pass them through the down blocks
1321
+ sample = (sample_img + sample_dem) / 2
1322
+ #####
1323
+ res_samples_img_dem = (res_samples_img[2] + res_samples_dem[2]) / 2
1324
+ down_block_res_samples = (res_samples_img_dem,)
1325
+
1326
+
1327
+ for downsample_block in self.down_blocks:
1328
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1329
+ # For t2i-adapter CrossAttnDownBlock2D
1330
+ additional_residuals = {}
1331
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1332
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1333
+
1334
+ sample, res_samples = downsample_block(
1335
+ hidden_states=sample,
1336
+ temb=emb,
1337
+ encoder_hidden_states=encoder_hidden_states,
1338
+ attention_mask=attention_mask,
1339
+ cross_attention_kwargs=cross_attention_kwargs,
1340
+ encoder_attention_mask=encoder_attention_mask,
1341
+ **additional_residuals,
1342
+ )
1343
+ else:
1344
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1345
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1346
+ sample += down_intrablock_additional_residuals.pop(0)
1347
+
1348
+ down_block_res_samples += res_samples
1349
+
1350
+ if is_controlnet:
1351
+ new_down_block_res_samples = ()
1352
+
1353
+ for down_block_res_sample, down_block_additional_residual in zip(
1354
+ down_block_res_samples, down_block_additional_residuals
1355
+ ):
1356
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
1357
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1358
+
1359
+ down_block_res_samples = new_down_block_res_samples
1360
+
1361
+
1362
+ # 4. mid
1363
+ if self.mid_block is not None:
1364
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1365
+ sample = self.mid_block(
1366
+ sample,
1367
+ emb,
1368
+ encoder_hidden_states=encoder_hidden_states,
1369
+ attention_mask=attention_mask,
1370
+ cross_attention_kwargs=cross_attention_kwargs,
1371
+ encoder_attention_mask=encoder_attention_mask,
1372
+ )
1373
+ else:
1374
+ sample = self.mid_block(sample, emb)
1375
+
1376
+ # To support T2I-Adapter-XL
1377
+ if (
1378
+ is_adapter
1379
+ and len(down_intrablock_additional_residuals) > 0
1380
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1381
+ ):
1382
+ sample += down_intrablock_additional_residuals.pop(0)
1383
+
1384
+ if is_controlnet:
1385
+ sample = sample + mid_block_additional_residual
1386
+
1387
+ # 5. up
1388
+ for i, upsample_block in enumerate(self.up_blocks):
1389
+
1390
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1391
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1392
+
1393
+ # if we have not reached the final block and need to forward the
1394
+ # upsample size, we do it here
1395
+ if forward_upsample_size:
1396
+ upsample_size = down_block_res_samples[-1].shape[2:]
1397
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1398
+ sample = upsample_block(
1399
+ hidden_states=sample,
1400
+ temb=emb,
1401
+ res_hidden_states_tuple=res_samples,
1402
+ encoder_hidden_states=encoder_hidden_states,
1403
+ cross_attention_kwargs=cross_attention_kwargs,
1404
+ upsample_size=upsample_size,
1405
+ attention_mask=attention_mask,
1406
+ encoder_attention_mask=encoder_attention_mask,
1407
+ )
1408
+
1409
+ else:
1410
+ sample = upsample_block(
1411
+ hidden_states=sample,
1412
+ temb=emb,
1413
+ res_hidden_states_tuple=res_samples,
1414
+ upsample_size=upsample_size)
1415
+
1416
+
1417
+ # go through each head
1418
+
1419
+ sample_img = sample
1420
+
1421
+ if hasattr(self.head_out_img, "has_cross_attention") and self.head_out_img.has_cross_attention:
1422
+ sample_img = self.head_out_img(
1423
+ hidden_states=sample_img,
1424
+ temb=emb,
1425
+ res_hidden_states_tuple=head_img_res_sample,
1426
+ encoder_hidden_states=encoder_hidden_states,
1427
+ cross_attention_kwargs=cross_attention_kwargs,
1428
+ upsample_size=upsample_size,
1429
+ attention_mask=attention_mask,
1430
+ encoder_attention_mask=encoder_attention_mask,
1431
+ )
1432
+ else:
1433
+ sample_img = self.head_out_img(sample_img,
1434
+ hidden_states=sample,
1435
+ temb=emb,
1436
+ res_hidden_states_tuple=head_img_res_sample,
1437
+ upsample_size=upsample_size,
1438
+ )
1439
+ if self.conv_norm_out_img:
1440
+ sample_img = self.conv_norm_out_img(sample_img)
1441
+ sample_img = self.conv_act(sample_img)
1442
+ sample_img = self.conv_out_img(sample_img)
1443
+
1444
+ sample_dem = sample
1445
+
1446
+ if hasattr(self.head_out_dem, "has_cross_attention") and self.head_out_dem.has_cross_attention:
1447
+ sample_dem = self.head_out_dem(
1448
+ hidden_states=sample_dem,
1449
+ temb=emb,
1450
+ res_hidden_states_tuple=head_dem_res_sample,
1451
+ encoder_hidden_states=encoder_hidden_states,
1452
+ cross_attention_kwargs=cross_attention_kwargs,
1453
+ upsample_size=upsample_size,
1454
+ attention_mask=attention_mask,
1455
+ encoder_attention_mask=encoder_attention_mask,
1456
+ )
1457
+ else:
1458
+ sample_dem = self.head_out_dem(sample_dem,
1459
+ hidden_states=sample,
1460
+ temb=emb,
1461
+ res_hidden_states_tuple=head_dem_res_sample,
1462
+ upsample_size=upsample_size,
1463
+ )
1464
+
1465
+ if self.conv_norm_out_dem:
1466
+ sample_dem = self.conv_norm_out_dem(sample_dem)
1467
+ sample_dem = self.conv_act(sample_dem)
1468
+ sample_dem = self.conv_out_dem(sample_dem)
1469
+
1470
+ sample = torch.cat([sample_img,sample_dem],dim=1)
1471
+
1472
+ if USE_PEFT_BACKEND:
1473
+ # remove `lora_scale` from each PEFT layer
1474
+ unscale_lora_layers(self, lora_scale)
1475
+
1476
+ if not return_dict:
1477
+ return (sample,)
1478
+
1479
+ return UNet2DConditionOutput(sample=sample)
1480
+
1481
+
1482
+
1483
+ def load_weights_from_pretrained(pretrain_model,model_dem):
1484
+ dem_state_dict = model_dem.state_dict()
1485
+ for name, param in pretrain_model.named_parameters():
1486
+ block = name.split(".")[0]
1487
+ if block == "conv_in":
1488
+ new_name_img = name.replace("conv_in","conv_in_img")
1489
+ dem_state_dict[new_name_img] = param
1490
+ new_name_dem = name.replace("conv_in","conv_in_dem")
1491
+ dem_state_dict[new_name_dem] = param
1492
+ if block == "down_blocks":
1493
+ block_num = int(name.split(".")[1])
1494
+ if block_num == 0:
1495
+ new_name_img = name.replace("down_blocks.0","head_img")
1496
+ dem_state_dict[new_name_img] = param
1497
+ new_name_dem = name.replace("down_blocks.0","head_dem")
1498
+ dem_state_dict[new_name_dem] = param
1499
+ elif block_num > 0:
1500
+ new_name = name.replace(f"down_blocks.{block_num}",f"down_blocks.{block_num-1}")
1501
+ dem_state_dict[new_name] = param
1502
+ if block == "mid_block":
1503
+ dem_state_dict[name] = param
1504
+ if block == "time_embedding":
1505
+ dem_state_dict[name] = param
1506
+ if block == "up_blocks":
1507
+ block_num = int(name.split(".")[1])
1508
+ if block_num == 3:
1509
+ new_name = name.replace("up_blocks.3","head_out_img")
1510
+ dem_state_dict[new_name] = param
1511
+ new_name = name.replace("up_blocks.3","head_out_dem")
1512
+ dem_state_dict[new_name] = param
1513
+ else:
1514
+ dem_state_dict[name] = param
1515
+ if block == "conv_out":
1516
+ new_name = name.replace("conv_out","conv_out_img")
1517
+ dem_state_dict[new_name] = param
1518
+ new_name = name.replace("conv_out","conv_out_dem")
1519
+ dem_state_dict[new_name] = param
1520
+ if block == "conv_norm_out":
1521
+ new_name = name.replace("conv_norm_out","conv_norm_out_img")
1522
+ dem_state_dict[new_name] = param
1523
+ new_name = name.replace("conv_norm_out","conv_norm_out_dem")
1524
+ dem_state_dict[new_name] = param
1525
+
1526
+ model_dem.load_state_dict(dem_state_dict)
1527
+
1528
+ return model_dem
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ diffusers==0.31
2
+ gradio
3
+ torch
4
+ trimesh
5
+ numpy
6
+ scipy
7
+ huggingface_hub
src/.ipynb_checkpoints/build_pipe-checkpoint.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .pipeline_terrain import TerrainDiffusionPipeline
2
+ #import models
3
+ from huggingface_hub import hf_hub_download, snapshot_download
4
+ import os
5
+ import torch
6
+
7
+ def build_pipe():
8
+ print('Downloading weights...')
9
+ try:
10
+ os.mkdir('./weights/')
11
+ except:
12
+ True
13
+ snapshot_download(repo_id="NewtNewt/MESA", local_dir="./weights")
14
+ weight_path = './weights'
15
+ print('[DONE]')
16
+
17
+ print('Instantiating Model...')
18
+ pipe = TerrainDiffusionPipeline.from_pretrained(weight_path, torch_dtype=torch.float16)
19
+ pipe.to("cuda")
20
+ print('[DONE]')
21
+
22
+ return pipe
src/.ipynb_checkpoints/models-checkpoint.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+ from torch.nn import functional as F
3
+ from diffusers import UNet2DConditionModel
4
+ import torch
5
+
6
+ def init_dem_channels(model,conv_in=None,conv_out=None):
7
+ """
8
+ Add a channel to the input and output of the model, with 0 initialization
9
+ """
10
+ # add one channel to the input and output, with 0 initialization
11
+ if conv_in is not None:
12
+ # add a channel to the input of the encoder
13
+ pretrained_in_weights = conv_in.weight.clone()
14
+ pretrained_in_bias = conv_in.bias.clone()
15
+
16
+ with torch.no_grad():
17
+ # weight matrix is of shape (out_channels, in_channels, kernel_size, kernel_size)
18
+ model.conv_in.weight[:, :4, :, :] = pretrained_in_weights
19
+ model.conv_in.weight[:, 4:, :, :] = 0
20
+ # bias vector is of shape (out_channels) no need to change it
21
+ model.conv_in.bias[...] = pretrained_in_bias
22
+
23
+
24
+
25
+ if conv_out is not None:
26
+ # add a channel to the output of the decoder
27
+ pretrained_out_weights = conv_out.weight.clone()
28
+ pretrained_out_bias = conv_out.bias.clone()
29
+
30
+ with torch.no_grad():
31
+ # weight matrix is of shape (out_channels, in_channels, kernel_size, kernel_size)
32
+ model.conv_out.weight[:4, :, :, :] = pretrained_out_weights
33
+ model.conv_out.weight[4:, :, :, :] = 0
34
+ # bias vector is of shape (out_channels)
35
+ model.conv_out.bias[:4] = pretrained_out_bias
36
+ model.conv_out.bias[4:] = 0
37
+ # Ensure the new layers are registered
38
+ model.register_to_config()
39
+
40
+ return model
41
+
42
+
43
+
44
+
45
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
46
+ #
47
+ # Licensed under the Apache License, Version 2.0 (the "License");
48
+ # you may not use this file except in compliance with the License.
49
+ # You may obtain a copy of the License at
50
+ #
51
+ # http://www.apache.org/licenses/LICENSE-2.0
52
+ #
53
+ # Unless required by applicable law or agreed to in writing, software
54
+ # distributed under the License is distributed on an "AS IS" BASIS,
55
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
56
+ # See the License for the specific language governing permissions and
57
+ # limitations under the License.
58
+ from dataclasses import dataclass
59
+ from typing import Any, Dict, List, Optional, Tuple, Union
60
+
61
+ import torch
62
+ import torch.nn as nn
63
+ import torch.utils.checkpoint
64
+ import diffusers
65
+
66
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
67
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
68
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin
69
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
70
+ from diffusers.models.activations import get_activation
71
+ from diffusers.models.attention_processor import (
72
+ ADDED_KV_ATTENTION_PROCESSORS,
73
+ CROSS_ATTENTION_PROCESSORS,
74
+ Attention,
75
+ AttentionProcessor,
76
+ AttnAddedKVProcessor,
77
+ AttnProcessor,
78
+ FusedAttnProcessor2_0,
79
+ )
80
+ from diffusers.models.embeddings import (
81
+ GaussianFourierProjection,
82
+ GLIGENTextBoundingboxProjection,
83
+ ImageHintTimeEmbedding,
84
+ ImageProjection,
85
+ ImageTimeEmbedding,
86
+ TextImageProjection,
87
+ TextImageTimeEmbedding,
88
+ TextTimeEmbedding,
89
+ TimestepEmbedding,
90
+ Timesteps,
91
+ )
92
+ from diffusers.models.modeling_utils import ModelMixin
93
+ from diffusers.models.unets.unet_2d_blocks import (
94
+ get_down_block,
95
+ get_mid_block,
96
+ get_up_block,
97
+ )
98
+
99
+
100
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
101
+
102
+
103
+ @dataclass
104
+ class UNet2DConditionOutput(BaseOutput):
105
+ """
106
+ The output of [`UNet2DConditionModel`].
107
+
108
+ Args:
109
+ sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
110
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
111
+ """
112
+
113
+ sample: torch.Tensor = None
114
+
115
+
116
+ class UNetDEMConditionModel(
117
+ ModelMixin, ConfigMixin, FromOriginalModelMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin
118
+ ):
119
+ r"""
120
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
121
+ shaped output.
122
+
123
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
124
+ for all models (such as downloading or saving).
125
+
126
+ Parameters:
127
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
128
+ Height and width of input/output sample.
129
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
130
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
131
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
132
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
133
+ Whether to flip the sin to cos in the time embedding.
134
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
135
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
136
+ The tuple of downsample blocks to use.
137
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
138
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
139
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
140
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
141
+ The tuple of upsample blocks to use.
142
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
143
+ Whether to include self-attention in the basic transformer blocks, see
144
+ [`~models.attention.BasicTransformerBlock`].
145
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
146
+ The tuple of output channels for each block.
147
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
148
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
149
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
150
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
151
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
152
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
153
+ If `None`, normalization and activation layers is skipped in post-processing.
154
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
155
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
156
+ The dimension of the cross attention features.
157
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
158
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
159
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
160
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
161
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
162
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
163
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
164
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
165
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
166
+ encoder_hid_dim (`int`, *optional*, defaults to None):
167
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
168
+ dimension to `cross_attention_dim`.
169
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
170
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
171
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
172
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
173
+ num_attention_heads (`int`, *optional*):
174
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
175
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
176
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
177
+ class_embed_type (`str`, *optional*, defaults to `None`):
178
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
179
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
180
+ addition_embed_type (`str`, *optional*, defaults to `None`):
181
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
182
+ "text". "text" will use the `TextTimeEmbedding` layer.
183
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
184
+ Dimension for the timestep embeddings.
185
+ num_class_embeds (`int`, *optional*, defaults to `None`):
186
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
187
+ class conditioning with `class_embed_type` equal to `None`.
188
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
189
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
190
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
191
+ An optional override for the dimension of the projected time embedding.
192
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
193
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
194
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
195
+ timestep_post_act (`str`, *optional*, defaults to `None`):
196
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
197
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
198
+ The dimension of `cond_proj` layer in the timestep embedding.
199
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
200
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
201
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
202
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
203
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
204
+ embeddings with the class embeddings.
205
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
206
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
207
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
208
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
209
+ otherwise.
210
+ """
211
+
212
+ _supports_gradient_checkpointing = True
213
+ _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
214
+
215
+ @register_to_config
216
+ def __init__(
217
+ self,
218
+ sample_size: Optional[int] = None,
219
+ in_channels: int = 8,
220
+ out_channels: int = 8,
221
+ center_input_sample: bool = False,
222
+ flip_sin_to_cos: bool = True,
223
+ freq_shift: int = 0,
224
+ down_block_types: Tuple[str] = (
225
+ "CrossAttnDownBlock2D",
226
+ "CrossAttnDownBlock2D",
227
+ "CrossAttnDownBlock2D",
228
+ "DownBlock2D",
229
+ ),
230
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
231
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
232
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
233
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
234
+ layers_per_block: Union[int, Tuple[int]] = 2,
235
+ downsample_padding: int = 1,
236
+ mid_block_scale_factor: float = 1,
237
+ dropout: float = 0.0,
238
+ act_fn: str = "silu",
239
+ norm_num_groups: Optional[int] = 32,
240
+ norm_eps: float = 1e-5,
241
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
242
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
243
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
244
+ encoder_hid_dim: Optional[int] = None,
245
+ encoder_hid_dim_type: Optional[str] = None,
246
+ attention_head_dim: Union[int, Tuple[int]] = 8,
247
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
248
+ dual_cross_attention: bool = False,
249
+ use_linear_projection: bool = False,
250
+ class_embed_type: Optional[str] = None,
251
+ addition_embed_type: Optional[str] = None,
252
+ addition_time_embed_dim: Optional[int] = None,
253
+ num_class_embeds: Optional[int] = None,
254
+ upcast_attention: bool = False,
255
+ resnet_time_scale_shift: str = "default",
256
+ resnet_skip_time_act: bool = False,
257
+ resnet_out_scale_factor: float = 1.0,
258
+ time_embedding_type: str = "positional",
259
+ time_embedding_dim: Optional[int] = None,
260
+ time_embedding_act_fn: Optional[str] = None,
261
+ timestep_post_act: Optional[str] = None,
262
+ time_cond_proj_dim: Optional[int] = None,
263
+ conv_in_kernel: int = 3,
264
+ conv_out_kernel: int = 3,
265
+ projection_class_embeddings_input_dim: Optional[int] = None,
266
+ attention_type: str = "default",
267
+ class_embeddings_concat: bool = False,
268
+ mid_block_only_cross_attention: Optional[bool] = None,
269
+ cross_attention_norm: Optional[str] = None,
270
+ addition_embed_type_num_heads: int = 64,
271
+ ):
272
+ super().__init__()
273
+
274
+ self.sample_size = sample_size
275
+
276
+ if num_attention_heads is not None:
277
+ raise ValueError(
278
+ "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."
279
+ )
280
+
281
+ # If `num_attention_heads` is not defined (which is the case for most models)
282
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
283
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
284
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
285
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
286
+ # which is why we correct for the naming here.
287
+ num_attention_heads = num_attention_heads or attention_head_dim
288
+
289
+ # Check inputs
290
+ self._check_config(
291
+ down_block_types=down_block_types,
292
+ up_block_types=up_block_types,
293
+ only_cross_attention=only_cross_attention,
294
+ block_out_channels=block_out_channels,
295
+ layers_per_block=layers_per_block,
296
+ cross_attention_dim=cross_attention_dim,
297
+ transformer_layers_per_block=transformer_layers_per_block,
298
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
299
+ attention_head_dim=attention_head_dim,
300
+ num_attention_heads=num_attention_heads,
301
+ )
302
+
303
+ # input
304
+ conv_in_padding = (conv_in_kernel - 1) // 2
305
+ self.conv_in_img = nn.Conv2d(
306
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
307
+ )
308
+ self.conv_in_dem = nn.Conv2d(
309
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
310
+ )
311
+
312
+ # time
313
+ time_embed_dim, timestep_input_dim = self._set_time_proj(
314
+ time_embedding_type,
315
+ block_out_channels=block_out_channels,
316
+ flip_sin_to_cos=flip_sin_to_cos,
317
+ freq_shift=freq_shift,
318
+ time_embedding_dim=time_embedding_dim,
319
+ )
320
+
321
+ self.time_embedding = TimestepEmbedding(
322
+ timestep_input_dim,
323
+ time_embed_dim,
324
+ act_fn=act_fn,
325
+ post_act_fn=timestep_post_act,
326
+ cond_proj_dim=time_cond_proj_dim,
327
+ )
328
+
329
+ self._set_encoder_hid_proj(
330
+ encoder_hid_dim_type,
331
+ cross_attention_dim=cross_attention_dim,
332
+ encoder_hid_dim=encoder_hid_dim,
333
+ )
334
+
335
+ # class embedding
336
+ self._set_class_embedding(
337
+ class_embed_type,
338
+ act_fn=act_fn,
339
+ num_class_embeds=num_class_embeds,
340
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
341
+ time_embed_dim=time_embed_dim,
342
+ timestep_input_dim=timestep_input_dim,
343
+ )
344
+
345
+ self._set_add_embedding(
346
+ addition_embed_type,
347
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
348
+ addition_time_embed_dim=addition_time_embed_dim,
349
+ cross_attention_dim=cross_attention_dim,
350
+ encoder_hid_dim=encoder_hid_dim,
351
+ flip_sin_to_cos=flip_sin_to_cos,
352
+ freq_shift=freq_shift,
353
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
354
+ time_embed_dim=time_embed_dim,
355
+ )
356
+
357
+ if time_embedding_act_fn is None:
358
+ self.time_embed_act = None
359
+ else:
360
+ self.time_embed_act = get_activation(time_embedding_act_fn)
361
+
362
+ self.down_blocks = nn.ModuleList([])
363
+ self.up_blocks = nn.ModuleList([])
364
+
365
+ if isinstance(only_cross_attention, bool):
366
+ if mid_block_only_cross_attention is None:
367
+ mid_block_only_cross_attention = only_cross_attention
368
+
369
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
370
+
371
+ if mid_block_only_cross_attention is None:
372
+ mid_block_only_cross_attention = False
373
+
374
+ if isinstance(num_attention_heads, int):
375
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
376
+
377
+ if isinstance(attention_head_dim, int):
378
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
379
+
380
+ if isinstance(cross_attention_dim, int):
381
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
382
+
383
+ if isinstance(layers_per_block, int):
384
+ layers_per_block = [layers_per_block] * len(down_block_types)
385
+
386
+ if isinstance(transformer_layers_per_block, int):
387
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
388
+
389
+ if class_embeddings_concat:
390
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
391
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
392
+ # regular time embeddings
393
+ blocks_time_embed_dim = time_embed_dim * 2
394
+ else:
395
+ blocks_time_embed_dim = time_embed_dim
396
+
397
+ # down
398
+ output_channel = block_out_channels[0]
399
+
400
+
401
+ for i, down_block_type in enumerate(down_block_types):
402
+ input_channel = output_channel
403
+ output_channel = block_out_channels[i]
404
+ is_final_block = i == len(block_out_channels) - 1
405
+ down_block_kwargs = {"down_block_type":down_block_type,
406
+ "num_layers":layers_per_block[i],
407
+ "transformer_layers_per_block":transformer_layers_per_block[i],
408
+ "in_channels":input_channel,
409
+ "out_channels":output_channel,
410
+ "temb_channels":blocks_time_embed_dim,
411
+ "add_downsample":not is_final_block,
412
+ "resnet_eps":norm_eps,
413
+ "resnet_act_fn":act_fn,
414
+ "resnet_groups":norm_num_groups,
415
+ "cross_attention_dim":cross_attention_dim[i],
416
+ "num_attention_heads":num_attention_heads[i],
417
+ "downsample_padding":downsample_padding,
418
+ "dual_cross_attention":dual_cross_attention,
419
+ "use_linear_projection":use_linear_projection,
420
+ "only_cross_attention":only_cross_attention[i],
421
+ "upcast_attention":upcast_attention,
422
+ "resnet_time_scale_shift":resnet_time_scale_shift,
423
+ "attention_type":attention_type,
424
+ "resnet_skip_time_act":resnet_skip_time_act,
425
+ "resnet_out_scale_factor":resnet_out_scale_factor,
426
+ "cross_attention_norm":cross_attention_norm,
427
+ "attention_head_dim":attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
428
+ "dropout":dropout}
429
+
430
+ if i == 0:
431
+ self.head_img = get_down_block(**down_block_kwargs)
432
+ # same architecture as the head_img but different weights
433
+ self.head_dem = get_down_block(**down_block_kwargs)
434
+ # elif i == 1:
435
+ # down_block_kwargs["in_channels"] = input_channel *2 # concatenate the output of the head_img and head_dem
436
+ # down_block = get_down_block(**down_block_kwargs)
437
+ # self.down_blocks.append(down_block)
438
+ else:
439
+ down_block = get_down_block(**down_block_kwargs)
440
+ self.down_blocks.append(down_block)
441
+
442
+ # mid
443
+ self.mid_block = get_mid_block(
444
+ mid_block_type,
445
+ temb_channels=blocks_time_embed_dim,
446
+ in_channels=block_out_channels[-1],
447
+ resnet_eps=norm_eps,
448
+ resnet_act_fn=act_fn,
449
+ resnet_groups=norm_num_groups,
450
+ output_scale_factor=mid_block_scale_factor,
451
+ transformer_layers_per_block=transformer_layers_per_block[-1],
452
+ num_attention_heads=num_attention_heads[-1],
453
+ cross_attention_dim=cross_attention_dim[-1],
454
+ dual_cross_attention=dual_cross_attention,
455
+ use_linear_projection=use_linear_projection,
456
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
457
+ upcast_attention=upcast_attention,
458
+ resnet_time_scale_shift=resnet_time_scale_shift,
459
+ attention_type=attention_type,
460
+ resnet_skip_time_act=resnet_skip_time_act,
461
+ cross_attention_norm=cross_attention_norm,
462
+ attention_head_dim=attention_head_dim[-1],
463
+ dropout=dropout,
464
+ )
465
+
466
+ # count how many layers upsample the images
467
+ self.num_upsamplers = 0
468
+
469
+ # up
470
+ reversed_block_out_channels = list(reversed(block_out_channels))
471
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
472
+ reversed_layers_per_block = list(reversed(layers_per_block))
473
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
474
+ reversed_transformer_layers_per_block = (
475
+ list(reversed(transformer_layers_per_block))
476
+ if reverse_transformer_layers_per_block is None
477
+ else reverse_transformer_layers_per_block
478
+ )
479
+ only_cross_attention = list(reversed(only_cross_attention))
480
+
481
+ output_channel = reversed_block_out_channels[0]
482
+ for i, up_block_type in enumerate(up_block_types):
483
+ is_final_block = i == len(block_out_channels) - 1
484
+
485
+ prev_output_channel = output_channel
486
+ output_channel = reversed_block_out_channels[i]
487
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
488
+
489
+ # add upsample block for all BUT final layer
490
+ if not is_final_block:
491
+ add_upsample = True
492
+ self.num_upsamplers += 1
493
+ else:
494
+ add_upsample = False
495
+
496
+ up_block_kwargs = {"up_block_type":up_block_type,
497
+ "num_layers":reversed_layers_per_block[i] + 1,
498
+ "transformer_layers_per_block":reversed_transformer_layers_per_block[i],
499
+ "in_channels":input_channel,
500
+ "out_channels":output_channel,
501
+ "prev_output_channel":prev_output_channel,
502
+ "temb_channels":blocks_time_embed_dim,
503
+ "add_upsample":add_upsample,
504
+ "resnet_eps":norm_eps,
505
+ "resnet_act_fn":act_fn,
506
+ "resolution_idx":i,
507
+ "resnet_groups":norm_num_groups,
508
+ "cross_attention_dim":reversed_cross_attention_dim[i],
509
+ "num_attention_heads":reversed_num_attention_heads[i],
510
+ "dual_cross_attention":dual_cross_attention,
511
+ "use_linear_projection":use_linear_projection,
512
+ "only_cross_attention":only_cross_attention[i],
513
+ "upcast_attention":upcast_attention,
514
+ "resnet_time_scale_shift":resnet_time_scale_shift,
515
+ "attention_type":attention_type,
516
+ "resnet_skip_time_act":resnet_skip_time_act,
517
+ "resnet_out_scale_factor":resnet_out_scale_factor,
518
+ "cross_attention_norm":cross_attention_norm,
519
+ "attention_head_dim":attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
520
+ "dropout":dropout,}
521
+
522
+ # if i == len(block_out_channels) - 2:
523
+ # up_block_kwargs["in_channels"] = input_channel*2
524
+ # up_block = get_up_block(**up_block_kwargs)
525
+ # self.up_blocks.append(up_block)
526
+
527
+ if is_final_block :
528
+
529
+ self.head_out_img = get_up_block(**up_block_kwargs)
530
+ self.head_out_dem = get_up_block(**up_block_kwargs)
531
+
532
+ else :
533
+ up_block = get_up_block(**up_block_kwargs)
534
+ self.up_blocks.append(up_block)
535
+
536
+
537
+ # out
538
+ if norm_num_groups is not None:
539
+ self.conv_norm_out_img = nn.GroupNorm(
540
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
541
+ )
542
+ self.conv_norm_out_dem = nn.GroupNorm(
543
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
544
+ )
545
+
546
+ self.conv_act = get_activation(act_fn)
547
+
548
+ else:
549
+ self.conv_norm_out_img = None
550
+ self.conv_norm_out_dem = None
551
+ self.conv_act = None
552
+
553
+ conv_out_padding = (conv_out_kernel - 1) // 2
554
+ self.conv_out_img = nn.Conv2d(
555
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
556
+ )
557
+ self.conv_out_dem = nn.Conv2d(
558
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
559
+ )
560
+
561
+ self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
562
+
563
+ def _check_config(
564
+ self,
565
+ down_block_types: Tuple[str],
566
+ up_block_types: Tuple[str],
567
+ only_cross_attention: Union[bool, Tuple[bool]],
568
+ block_out_channels: Tuple[int],
569
+ layers_per_block: Union[int, Tuple[int]],
570
+ cross_attention_dim: Union[int, Tuple[int]],
571
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
572
+ reverse_transformer_layers_per_block: bool,
573
+ attention_head_dim: int,
574
+ num_attention_heads: Optional[Union[int, Tuple[int]]],
575
+ ):
576
+ if len(down_block_types) != len(up_block_types):
577
+ raise ValueError(
578
+ 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}."
579
+ )
580
+
581
+ if len(block_out_channels) != len(down_block_types):
582
+ raise ValueError(
583
+ 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}."
584
+ )
585
+
586
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
587
+ raise ValueError(
588
+ 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}."
589
+ )
590
+
591
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
592
+ raise ValueError(
593
+ 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}."
594
+ )
595
+
596
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
597
+ raise ValueError(
598
+ 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}."
599
+ )
600
+
601
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
602
+ raise ValueError(
603
+ 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}."
604
+ )
605
+
606
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
607
+ raise ValueError(
608
+ 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}."
609
+ )
610
+ if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
611
+ for layer_number_per_block in transformer_layers_per_block:
612
+ if isinstance(layer_number_per_block, list):
613
+ raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
614
+
615
+ def _set_time_proj(
616
+ self,
617
+ time_embedding_type: str,
618
+ block_out_channels: int,
619
+ flip_sin_to_cos: bool,
620
+ freq_shift: float,
621
+ time_embedding_dim: int,
622
+ ) -> Tuple[int, int]:
623
+ if time_embedding_type == "fourier":
624
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
625
+ if time_embed_dim % 2 != 0:
626
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
627
+ self.time_proj = GaussianFourierProjection(
628
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
629
+ )
630
+ timestep_input_dim = time_embed_dim
631
+ elif time_embedding_type == "positional":
632
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
633
+
634
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
635
+ timestep_input_dim = block_out_channels[0]
636
+ else:
637
+ raise ValueError(
638
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
639
+ )
640
+
641
+ return time_embed_dim, timestep_input_dim
642
+
643
+ def _set_encoder_hid_proj(
644
+ self,
645
+ encoder_hid_dim_type: Optional[str],
646
+ cross_attention_dim: Union[int, Tuple[int]],
647
+ encoder_hid_dim: Optional[int],
648
+ ):
649
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
650
+ encoder_hid_dim_type = "text_proj"
651
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
652
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
653
+
654
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
655
+ raise ValueError(
656
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
657
+ )
658
+
659
+ if encoder_hid_dim_type == "text_proj":
660
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
661
+ elif encoder_hid_dim_type == "text_image_proj":
662
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
663
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
664
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
665
+ self.encoder_hid_proj = TextImageProjection(
666
+ text_embed_dim=encoder_hid_dim,
667
+ image_embed_dim=cross_attention_dim,
668
+ cross_attention_dim=cross_attention_dim,
669
+ )
670
+ elif encoder_hid_dim_type == "image_proj":
671
+ # Kandinsky 2.2
672
+ self.encoder_hid_proj = ImageProjection(
673
+ image_embed_dim=encoder_hid_dim,
674
+ cross_attention_dim=cross_attention_dim,
675
+ )
676
+ elif encoder_hid_dim_type is not None:
677
+ raise ValueError(
678
+ f"`encoder_hid_dim_type`: {encoder_hid_dim_type} must be None, 'text_proj', 'text_image_proj', or 'image_proj'."
679
+ )
680
+ else:
681
+ self.encoder_hid_proj = None
682
+
683
+ def _set_class_embedding(
684
+ self,
685
+ class_embed_type: Optional[str],
686
+ act_fn: str,
687
+ num_class_embeds: Optional[int],
688
+ projection_class_embeddings_input_dim: Optional[int],
689
+ time_embed_dim: int,
690
+ timestep_input_dim: int,
691
+ ):
692
+ if class_embed_type is None and num_class_embeds is not None:
693
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
694
+ elif class_embed_type == "timestep":
695
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
696
+ elif class_embed_type == "identity":
697
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
698
+ elif class_embed_type == "projection":
699
+ if projection_class_embeddings_input_dim is None:
700
+ raise ValueError(
701
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
702
+ )
703
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
704
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
705
+ # 2. it projects from an arbitrary input dimension.
706
+ #
707
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
708
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
709
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
710
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
711
+ elif class_embed_type == "simple_projection":
712
+ if projection_class_embeddings_input_dim is None:
713
+ raise ValueError(
714
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
715
+ )
716
+ self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
717
+ else:
718
+ self.class_embedding = None
719
+
720
+ def _set_add_embedding(
721
+ self,
722
+ addition_embed_type: str,
723
+ addition_embed_type_num_heads: int,
724
+ addition_time_embed_dim: Optional[int],
725
+ flip_sin_to_cos: bool,
726
+ freq_shift: float,
727
+ cross_attention_dim: Optional[int],
728
+ encoder_hid_dim: Optional[int],
729
+ projection_class_embeddings_input_dim: Optional[int],
730
+ time_embed_dim: int,
731
+ ):
732
+ if addition_embed_type == "text":
733
+ if encoder_hid_dim is not None:
734
+ text_time_embedding_from_dim = encoder_hid_dim
735
+ else:
736
+ text_time_embedding_from_dim = cross_attention_dim
737
+
738
+ self.add_embedding = TextTimeEmbedding(
739
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
740
+ )
741
+ elif addition_embed_type == "text_image":
742
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
743
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
744
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
745
+ self.add_embedding = TextImageTimeEmbedding(
746
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
747
+ )
748
+ elif addition_embed_type == "text_time":
749
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
750
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
751
+ elif addition_embed_type == "image":
752
+ # Kandinsky 2.2
753
+ self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
754
+ elif addition_embed_type == "image_hint":
755
+ # Kandinsky 2.2 ControlNet
756
+ self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
757
+ elif addition_embed_type is not None:
758
+ raise ValueError(
759
+ f"`addition_embed_type`: {addition_embed_type} must be None, 'text', 'text_image', 'text_time', 'image', or 'image_hint'."
760
+ )
761
+
762
+ def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
763
+ if attention_type in ["gated", "gated-text-image"]:
764
+ positive_len = 768
765
+ if isinstance(cross_attention_dim, int):
766
+ positive_len = cross_attention_dim
767
+ elif isinstance(cross_attention_dim, (list, tuple)):
768
+ positive_len = cross_attention_dim[0]
769
+
770
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
771
+ self.position_net = GLIGENTextBoundingboxProjection(
772
+ positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
773
+ )
774
+
775
+ @property
776
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
777
+ r"""
778
+ Returns:
779
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
780
+ indexed by its weight name.
781
+ """
782
+ # set recursively
783
+ processors = {}
784
+
785
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
786
+ if hasattr(module, "get_processor"):
787
+ processors[f"{name}.processor"] = module.get_processor()
788
+
789
+ for sub_name, child in module.named_children():
790
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
791
+
792
+ return processors
793
+
794
+ for name, module in self.named_children():
795
+ fn_recursive_add_processors(name, module, processors)
796
+
797
+ return processors
798
+
799
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
800
+ r"""
801
+ Sets the attention processor to use to compute attention.
802
+
803
+ Parameters:
804
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
805
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
806
+ for **all** `Attention` layers.
807
+
808
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
809
+ processor. This is strongly recommended when setting trainable attention processors.
810
+
811
+ """
812
+ count = len(self.attn_processors.keys())
813
+
814
+ if isinstance(processor, dict) and len(processor) != count:
815
+ raise ValueError(
816
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
817
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
818
+ )
819
+
820
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
821
+ if hasattr(module, "set_processor"):
822
+ if not isinstance(processor, dict):
823
+ module.set_processor(processor)
824
+ else:
825
+ module.set_processor(processor.pop(f"{name}.processor"))
826
+
827
+ for sub_name, child in module.named_children():
828
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
829
+
830
+ for name, module in self.named_children():
831
+ fn_recursive_attn_processor(name, module, processor)
832
+
833
+ def set_default_attn_processor(self):
834
+ """
835
+ Disables custom attention processors and sets the default attention implementation.
836
+ """
837
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
838
+ processor = AttnAddedKVProcessor()
839
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
840
+ processor = AttnProcessor()
841
+ else:
842
+ raise ValueError(
843
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
844
+ )
845
+
846
+ self.set_attn_processor(processor)
847
+
848
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
849
+ r"""
850
+ Enable sliced attention computation.
851
+
852
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
853
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
854
+
855
+ Args:
856
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
857
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
858
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
859
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
860
+ must be a multiple of `slice_size`.
861
+ """
862
+ sliceable_head_dims = []
863
+
864
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
865
+ if hasattr(module, "set_attention_slice"):
866
+ sliceable_head_dims.append(module.sliceable_head_dim)
867
+
868
+ for child in module.children():
869
+ fn_recursive_retrieve_sliceable_dims(child)
870
+
871
+ # retrieve number of attention layers
872
+ for module in self.children():
873
+ fn_recursive_retrieve_sliceable_dims(module)
874
+
875
+ num_sliceable_layers = len(sliceable_head_dims)
876
+
877
+ if slice_size == "auto":
878
+ # half the attention head size is usually a good trade-off between
879
+ # speed and memory
880
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
881
+ elif slice_size == "max":
882
+ # make smallest slice possible
883
+ slice_size = num_sliceable_layers * [1]
884
+
885
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
886
+
887
+ if len(slice_size) != len(sliceable_head_dims):
888
+ raise ValueError(
889
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
890
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
891
+ )
892
+
893
+ for i in range(len(slice_size)):
894
+ size = slice_size[i]
895
+ dim = sliceable_head_dims[i]
896
+ if size is not None and size > dim:
897
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
898
+
899
+ # Recursively walk through all the children.
900
+ # Any children which exposes the set_attention_slice method
901
+ # gets the message
902
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
903
+ if hasattr(module, "set_attention_slice"):
904
+ module.set_attention_slice(slice_size.pop())
905
+
906
+ for child in module.children():
907
+ fn_recursive_set_attention_slice(child, slice_size)
908
+
909
+ reversed_slice_size = list(reversed(slice_size))
910
+ for module in self.children():
911
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
912
+
913
+ def _set_gradient_checkpointing(self, module, value=False):
914
+ if hasattr(module, "gradient_checkpointing"):
915
+ module.gradient_checkpointing = value
916
+
917
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
918
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
919
+
920
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
921
+
922
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
923
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
924
+
925
+ Args:
926
+ s1 (`float`):
927
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
928
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
929
+ s2 (`float`):
930
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
931
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
932
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
933
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
934
+ """
935
+ for i, upsample_block in enumerate(self.up_blocks):
936
+ setattr(upsample_block, "s1", s1)
937
+ setattr(upsample_block, "s2", s2)
938
+ setattr(upsample_block, "b1", b1)
939
+ setattr(upsample_block, "b2", b2)
940
+
941
+ def disable_freeu(self):
942
+ """Disables the FreeU mechanism."""
943
+ freeu_keys = {"s1", "s2", "b1", "b2"}
944
+ for i, upsample_block in enumerate(self.up_blocks):
945
+ for k in freeu_keys:
946
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
947
+ setattr(upsample_block, k, None)
948
+
949
+ def fuse_qkv_projections(self):
950
+ """
951
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
952
+ are fused. For cross-attention modules, key and value projection matrices are fused.
953
+
954
+ <Tip warning={true}>
955
+
956
+ This API is 🧪 experimental.
957
+
958
+ </Tip>
959
+ """
960
+ self.original_attn_processors = None
961
+
962
+ for _, attn_processor in self.attn_processors.items():
963
+ if "Added" in str(attn_processor.__class__.__name__):
964
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
965
+
966
+ self.original_attn_processors = self.attn_processors
967
+
968
+ for module in self.modules():
969
+ if isinstance(module, Attention):
970
+ module.fuse_projections(fuse=True)
971
+
972
+ self.set_attn_processor(FusedAttnProcessor2_0())
973
+
974
+ def unfuse_qkv_projections(self):
975
+ """Disables the fused QKV projection if enabled.
976
+
977
+ <Tip warning={true}>
978
+
979
+ This API is 🧪 experimental.
980
+
981
+ </Tip>
982
+
983
+ """
984
+ if self.original_attn_processors is not None:
985
+ self.set_attn_processor(self.original_attn_processors)
986
+
987
+ def get_time_embed(
988
+ self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
989
+ ) -> Optional[torch.Tensor]:
990
+ timesteps = timestep
991
+ if not torch.is_tensor(timesteps):
992
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
993
+ # This would be a good case for the `match` statement (Python 3.10+)
994
+ is_mps = sample.device.type == "mps"
995
+ if isinstance(timestep, float):
996
+ dtype = torch.float32 if is_mps else torch.float64
997
+ else:
998
+ dtype = torch.int32 if is_mps else torch.int64
999
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1000
+ elif len(timesteps.shape) == 0:
1001
+ timesteps = timesteps[None].to(sample.device)
1002
+
1003
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1004
+ timesteps = timesteps.expand(sample.shape[0])
1005
+
1006
+ t_emb = self.time_proj(timesteps)
1007
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1008
+ # but time_embedding might actually be running in fp16. so we need to cast here.
1009
+ # there might be better ways to encapsulate this.
1010
+ t_emb = t_emb.to(dtype=sample.dtype)
1011
+ return t_emb
1012
+
1013
+ def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
1014
+ class_emb = None
1015
+ if self.class_embedding is not None:
1016
+ if class_labels is None:
1017
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
1018
+
1019
+ if self.config.class_embed_type == "timestep":
1020
+ class_labels = self.time_proj(class_labels)
1021
+
1022
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1023
+ # there might be better ways to encapsulate this.
1024
+ class_labels = class_labels.to(dtype=sample.dtype)
1025
+
1026
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
1027
+ return class_emb
1028
+
1029
+ def get_aug_embed(
1030
+ self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1031
+ ) -> Optional[torch.Tensor]:
1032
+ aug_emb = None
1033
+ if self.config.addition_embed_type == "text":
1034
+ aug_emb = self.add_embedding(encoder_hidden_states)
1035
+ elif self.config.addition_embed_type == "text_image":
1036
+ # Kandinsky 2.1 - style
1037
+ if "image_embeds" not in added_cond_kwargs:
1038
+ raise ValueError(
1039
+ 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`"
1040
+ )
1041
+
1042
+ image_embs = added_cond_kwargs.get("image_embeds")
1043
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
1044
+ aug_emb = self.add_embedding(text_embs, image_embs)
1045
+ elif self.config.addition_embed_type == "text_time":
1046
+ # SDXL - style
1047
+ if "text_embeds" not in added_cond_kwargs:
1048
+ raise ValueError(
1049
+ 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`"
1050
+ )
1051
+ text_embeds = added_cond_kwargs.get("text_embeds")
1052
+ if "time_ids" not in added_cond_kwargs:
1053
+ raise ValueError(
1054
+ 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`"
1055
+ )
1056
+ time_ids = added_cond_kwargs.get("time_ids")
1057
+ time_embeds = self.add_time_proj(time_ids.flatten())
1058
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1059
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1060
+ add_embeds = add_embeds.to(emb.dtype)
1061
+ aug_emb = self.add_embedding(add_embeds)
1062
+ elif self.config.addition_embed_type == "image":
1063
+ # Kandinsky 2.2 - style
1064
+ if "image_embeds" not in added_cond_kwargs:
1065
+ raise ValueError(
1066
+ 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`"
1067
+ )
1068
+ image_embs = added_cond_kwargs.get("image_embeds")
1069
+ aug_emb = self.add_embedding(image_embs)
1070
+ elif self.config.addition_embed_type == "image_hint":
1071
+ # Kandinsky 2.2 ControlNet - style
1072
+ if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1073
+ raise ValueError(
1074
+ 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`"
1075
+ )
1076
+ image_embs = added_cond_kwargs.get("image_embeds")
1077
+ hint = added_cond_kwargs.get("hint")
1078
+ aug_emb = self.add_embedding(image_embs, hint)
1079
+ return aug_emb
1080
+
1081
+ def process_encoder_hidden_states(
1082
+ self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1083
+ ) -> torch.Tensor:
1084
+ if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1085
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1086
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1087
+ # Kandinsky 2.1 - style
1088
+ if "image_embeds" not in added_cond_kwargs:
1089
+ raise ValueError(
1090
+ 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_cond_kwargs`"
1091
+ )
1092
+
1093
+ image_embeds = added_cond_kwargs.get("image_embeds")
1094
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1095
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1096
+ # Kandinsky 2.2 - style
1097
+ if "image_embeds" not in added_cond_kwargs:
1098
+ raise ValueError(
1099
+ 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_cond_kwargs`"
1100
+ )
1101
+ image_embeds = added_cond_kwargs.get("image_embeds")
1102
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1103
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1104
+ if "image_embeds" not in added_cond_kwargs:
1105
+ raise ValueError(
1106
+ 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_cond_kwargs`"
1107
+ )
1108
+
1109
+ if hasattr(self, "text_encoder_hid_proj") and self.text_encoder_hid_proj is not None:
1110
+ encoder_hidden_states = self.text_encoder_hid_proj(encoder_hidden_states)
1111
+
1112
+ image_embeds = added_cond_kwargs.get("image_embeds")
1113
+ image_embeds = self.encoder_hid_proj(image_embeds)
1114
+ encoder_hidden_states = (encoder_hidden_states, image_embeds)
1115
+ return encoder_hidden_states
1116
+
1117
+ def forward(
1118
+ self,
1119
+ sample: torch.Tensor,
1120
+ timestep: Union[torch.Tensor, float, int],
1121
+ encoder_hidden_states: torch.Tensor,
1122
+ class_labels: Optional[torch.Tensor] = None,
1123
+ timestep_cond: Optional[torch.Tensor] = None,
1124
+ attention_mask: Optional[torch.Tensor] = None,
1125
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1126
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1127
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1128
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
1129
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1130
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1131
+ return_dict: bool = True,
1132
+ ) -> Union[UNet2DConditionOutput, Tuple]:
1133
+ r"""
1134
+ The [`UNet2DConditionModel`] forward method.
1135
+
1136
+ Args:
1137
+ sample (`torch.Tensor`):
1138
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
1139
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
1140
+ encoder_hidden_states (`torch.Tensor`):
1141
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1142
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1143
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1144
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1145
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1146
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
1147
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1148
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1149
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1150
+ negative values to the attention scores corresponding to "discard" tokens.
1151
+ cross_attention_kwargs (`dict`, *optional*):
1152
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1153
+ `self.processor` in
1154
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1155
+ added_cond_kwargs: (`dict`, *optional*):
1156
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1157
+ are passed along to the UNet blocks.
1158
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1159
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
1160
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
1161
+ A tensor that if specified is added to the residual of the middle unet block.
1162
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1163
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1164
+ encoder_attention_mask (`torch.Tensor`):
1165
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1166
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1167
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
1168
+ return_dict (`bool`, *optional*, defaults to `True`):
1169
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1170
+ tuple.
1171
+
1172
+ Returns:
1173
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1174
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1175
+ otherwise a `tuple` is returned where the first element is the sample tensor.
1176
+ """
1177
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
1178
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1179
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
1180
+ # on the fly if necessary.
1181
+ default_overall_up_factor = 2**self.num_upsamplers
1182
+
1183
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1184
+ forward_upsample_size = False
1185
+ upsample_size = None
1186
+
1187
+ for dim in sample.shape[-2:]:
1188
+ if dim % default_overall_up_factor != 0:
1189
+ # Forward upsample size to force interpolation output size.
1190
+ forward_upsample_size = True
1191
+ break
1192
+
1193
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1194
+ # expects mask of shape:
1195
+ # [batch, key_tokens]
1196
+ # adds singleton query_tokens dimension:
1197
+ # [batch, 1, key_tokens]
1198
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1199
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1200
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1201
+ if attention_mask is not None:
1202
+ # assume that mask is expressed as:
1203
+ # (1 = keep, 0 = discard)
1204
+ # convert mask into a bias that can be added to attention scores:
1205
+ # (keep = +0, discard = -10000.0)
1206
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1207
+ attention_mask = attention_mask.unsqueeze(1)
1208
+
1209
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
1210
+ if encoder_attention_mask is not None:
1211
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1212
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1213
+
1214
+ # 0. center input if necessary
1215
+ if self.config.center_input_sample:
1216
+ sample = 2 * sample - 1.0
1217
+
1218
+ # 1. time
1219
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1220
+ emb = self.time_embedding(t_emb, timestep_cond)
1221
+
1222
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1223
+ if class_emb is not None:
1224
+ if self.config.class_embeddings_concat:
1225
+ emb = torch.cat([emb, class_emb], dim=-1)
1226
+ else:
1227
+ emb = emb + class_emb
1228
+
1229
+ aug_emb = self.get_aug_embed(
1230
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1231
+ )
1232
+ if self.config.addition_embed_type == "image_hint":
1233
+ aug_emb, hint = aug_emb
1234
+ sample = torch.cat([sample, hint], dim=1)
1235
+
1236
+
1237
+ emb = emb + aug_emb if aug_emb is not None else emb
1238
+
1239
+ if self.time_embed_act is not None:
1240
+ emb = self.time_embed_act(emb)
1241
+
1242
+ encoder_hidden_states = self.process_encoder_hidden_states(
1243
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1244
+ )
1245
+
1246
+ sample_img = sample[:, :4, :, :]
1247
+ sample_dem = sample[:, 4:, :, :]
1248
+ # 2. pre-process using the two different heads
1249
+ sample_img = self.conv_in_img(sample_img)
1250
+ sample_dem = self.conv_in_dem(sample_dem)
1251
+
1252
+ # 2.5 GLIGEN position net
1253
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1254
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1255
+ gligen_args = cross_attention_kwargs.pop("gligen")
1256
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1257
+
1258
+ # 3. down
1259
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1260
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1261
+ if cross_attention_kwargs is not None:
1262
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1263
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1264
+ else:
1265
+ lora_scale = 1.0
1266
+
1267
+ if USE_PEFT_BACKEND:
1268
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1269
+ scale_lora_layers(self, lora_scale)
1270
+
1271
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1272
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1273
+ is_adapter = down_intrablock_additional_residuals is not None
1274
+ if (down_intrablock_additional_residuals is not None) or is_adapter:
1275
+ raise NotImplementedError("additional_residuals")
1276
+
1277
+
1278
+ # go through the heads
1279
+ head_img_res_sample = (sample_img,)
1280
+ # RGB head
1281
+ if hasattr(self.head_img, "has_cross_attention") and self.head_img.has_cross_attention:
1282
+ # For t2i-adapter CrossAttnDownBlock2D
1283
+ additional_residuals = {}
1284
+ sample_img, res_samples_img = self.head_img(
1285
+ hidden_states=sample_img,
1286
+ temb=emb,
1287
+ encoder_hidden_states=encoder_hidden_states,
1288
+ attention_mask=attention_mask,
1289
+ cross_attention_kwargs=cross_attention_kwargs,
1290
+ encoder_attention_mask=encoder_attention_mask,
1291
+ **additional_residuals,
1292
+ )
1293
+ else:
1294
+ sample_img, res_samples_img = self.head_img(hidden_states=sample, temb=emb)
1295
+ head_img_res_sample += res_samples_img[:2]
1296
+
1297
+
1298
+
1299
+ head_dem_res_sample = (sample_dem,)
1300
+ # DEM head
1301
+ if hasattr(self.head_dem, "has_cross_attention") and self.head_dem.has_cross_attention:
1302
+ # For t2i-adapter CrossAttnDownBlock2D
1303
+ additional_residuals = {}
1304
+
1305
+ sample_dem, res_samples_dem = self.head_dem(
1306
+ hidden_states=sample_dem,
1307
+ temb=emb,
1308
+ encoder_hidden_states=encoder_hidden_states,
1309
+ attention_mask=attention_mask,
1310
+ cross_attention_kwargs=cross_attention_kwargs,
1311
+ encoder_attention_mask=encoder_attention_mask,
1312
+ **additional_residuals,
1313
+ )
1314
+ else:
1315
+ # sample_dem, res_samples_dem = self.head_dem(hidden_states=sample, temb=emb)
1316
+ sample_dem, res_samples_dem = self.head_img(hidden_states=sample, temb=emb) # shared weights
1317
+
1318
+ head_dem_res_sample += res_samples_dem[:2]
1319
+
1320
+ #average the two heads and pass them through the down blocks
1321
+ sample = (sample_img + sample_dem) / 2
1322
+ #####
1323
+ res_samples_img_dem = (res_samples_img[2] + res_samples_dem[2]) / 2
1324
+ down_block_res_samples = (res_samples_img_dem,)
1325
+
1326
+
1327
+ for downsample_block in self.down_blocks:
1328
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1329
+ # For t2i-adapter CrossAttnDownBlock2D
1330
+ additional_residuals = {}
1331
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1332
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1333
+
1334
+ sample, res_samples = downsample_block(
1335
+ hidden_states=sample,
1336
+ temb=emb,
1337
+ encoder_hidden_states=encoder_hidden_states,
1338
+ attention_mask=attention_mask,
1339
+ cross_attention_kwargs=cross_attention_kwargs,
1340
+ encoder_attention_mask=encoder_attention_mask,
1341
+ **additional_residuals,
1342
+ )
1343
+ else:
1344
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1345
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1346
+ sample += down_intrablock_additional_residuals.pop(0)
1347
+
1348
+ down_block_res_samples += res_samples
1349
+
1350
+ if is_controlnet:
1351
+ new_down_block_res_samples = ()
1352
+
1353
+ for down_block_res_sample, down_block_additional_residual in zip(
1354
+ down_block_res_samples, down_block_additional_residuals
1355
+ ):
1356
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
1357
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1358
+
1359
+ down_block_res_samples = new_down_block_res_samples
1360
+
1361
+
1362
+ # 4. mid
1363
+ if self.mid_block is not None:
1364
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1365
+ sample = self.mid_block(
1366
+ sample,
1367
+ emb,
1368
+ encoder_hidden_states=encoder_hidden_states,
1369
+ attention_mask=attention_mask,
1370
+ cross_attention_kwargs=cross_attention_kwargs,
1371
+ encoder_attention_mask=encoder_attention_mask,
1372
+ )
1373
+ else:
1374
+ sample = self.mid_block(sample, emb)
1375
+
1376
+ # To support T2I-Adapter-XL
1377
+ if (
1378
+ is_adapter
1379
+ and len(down_intrablock_additional_residuals) > 0
1380
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1381
+ ):
1382
+ sample += down_intrablock_additional_residuals.pop(0)
1383
+
1384
+ if is_controlnet:
1385
+ sample = sample + mid_block_additional_residual
1386
+
1387
+ # 5. up
1388
+ for i, upsample_block in enumerate(self.up_blocks):
1389
+
1390
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1391
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1392
+
1393
+ # if we have not reached the final block and need to forward the
1394
+ # upsample size, we do it here
1395
+ if forward_upsample_size:
1396
+ upsample_size = down_block_res_samples[-1].shape[2:]
1397
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1398
+ sample = upsample_block(
1399
+ hidden_states=sample,
1400
+ temb=emb,
1401
+ res_hidden_states_tuple=res_samples,
1402
+ encoder_hidden_states=encoder_hidden_states,
1403
+ cross_attention_kwargs=cross_attention_kwargs,
1404
+ upsample_size=upsample_size,
1405
+ attention_mask=attention_mask,
1406
+ encoder_attention_mask=encoder_attention_mask,
1407
+ )
1408
+
1409
+ else:
1410
+ sample = upsample_block(
1411
+ hidden_states=sample,
1412
+ temb=emb,
1413
+ res_hidden_states_tuple=res_samples,
1414
+ upsample_size=upsample_size)
1415
+
1416
+
1417
+ # go through each head
1418
+
1419
+ sample_img = sample
1420
+
1421
+ if hasattr(self.head_out_img, "has_cross_attention") and self.head_out_img.has_cross_attention:
1422
+ sample_img = self.head_out_img(
1423
+ hidden_states=sample_img,
1424
+ temb=emb,
1425
+ res_hidden_states_tuple=head_img_res_sample,
1426
+ encoder_hidden_states=encoder_hidden_states,
1427
+ cross_attention_kwargs=cross_attention_kwargs,
1428
+ upsample_size=upsample_size,
1429
+ attention_mask=attention_mask,
1430
+ encoder_attention_mask=encoder_attention_mask,
1431
+ )
1432
+ else:
1433
+ sample_img = self.head_out_img(sample_img,
1434
+ hidden_states=sample,
1435
+ temb=emb,
1436
+ res_hidden_states_tuple=head_img_res_sample,
1437
+ upsample_size=upsample_size,
1438
+ )
1439
+ if self.conv_norm_out_img:
1440
+ sample_img = self.conv_norm_out_img(sample_img)
1441
+ sample_img = self.conv_act(sample_img)
1442
+ sample_img = self.conv_out_img(sample_img)
1443
+
1444
+ sample_dem = sample
1445
+
1446
+ if hasattr(self.head_out_dem, "has_cross_attention") and self.head_out_dem.has_cross_attention:
1447
+ sample_dem = self.head_out_dem(
1448
+ hidden_states=sample_dem,
1449
+ temb=emb,
1450
+ res_hidden_states_tuple=head_dem_res_sample,
1451
+ encoder_hidden_states=encoder_hidden_states,
1452
+ cross_attention_kwargs=cross_attention_kwargs,
1453
+ upsample_size=upsample_size,
1454
+ attention_mask=attention_mask,
1455
+ encoder_attention_mask=encoder_attention_mask,
1456
+ )
1457
+ else:
1458
+ sample_dem = self.head_out_dem(sample_dem,
1459
+ hidden_states=sample,
1460
+ temb=emb,
1461
+ res_hidden_states_tuple=head_dem_res_sample,
1462
+ upsample_size=upsample_size,
1463
+ )
1464
+
1465
+ if self.conv_norm_out_dem:
1466
+ sample_dem = self.conv_norm_out_dem(sample_dem)
1467
+ sample_dem = self.conv_act(sample_dem)
1468
+ sample_dem = self.conv_out_dem(sample_dem)
1469
+
1470
+ sample = torch.cat([sample_img,sample_dem],dim=1)
1471
+
1472
+ if USE_PEFT_BACKEND:
1473
+ # remove `lora_scale` from each PEFT layer
1474
+ unscale_lora_layers(self, lora_scale)
1475
+
1476
+ if not return_dict:
1477
+ return (sample,)
1478
+
1479
+ return UNet2DConditionOutput(sample=sample)
1480
+
1481
+
1482
+
1483
+ def load_weights_from_pretrained(pretrain_model,model_dem):
1484
+ dem_state_dict = model_dem.state_dict()
1485
+ for name, param in pretrain_model.named_parameters():
1486
+ block = name.split(".")[0]
1487
+ if block == "conv_in":
1488
+ new_name_img = name.replace("conv_in","conv_in_img")
1489
+ dem_state_dict[new_name_img] = param
1490
+ new_name_dem = name.replace("conv_in","conv_in_dem")
1491
+ dem_state_dict[new_name_dem] = param
1492
+ if block == "down_blocks":
1493
+ block_num = int(name.split(".")[1])
1494
+ if block_num == 0:
1495
+ new_name_img = name.replace("down_blocks.0","head_img")
1496
+ dem_state_dict[new_name_img] = param
1497
+ new_name_dem = name.replace("down_blocks.0","head_dem")
1498
+ dem_state_dict[new_name_dem] = param
1499
+ elif block_num > 0:
1500
+ new_name = name.replace(f"down_blocks.{block_num}",f"down_blocks.{block_num-1}")
1501
+ dem_state_dict[new_name] = param
1502
+ if block == "mid_block":
1503
+ dem_state_dict[name] = param
1504
+ if block == "time_embedding":
1505
+ dem_state_dict[name] = param
1506
+ if block == "up_blocks":
1507
+ block_num = int(name.split(".")[1])
1508
+ if block_num == 3:
1509
+ new_name = name.replace("up_blocks.3","head_out_img")
1510
+ dem_state_dict[new_name] = param
1511
+ new_name = name.replace("up_blocks.3","head_out_dem")
1512
+ dem_state_dict[new_name] = param
1513
+ else:
1514
+ dem_state_dict[name] = param
1515
+ if block == "conv_out":
1516
+ new_name = name.replace("conv_out","conv_out_img")
1517
+ dem_state_dict[new_name] = param
1518
+ new_name = name.replace("conv_out","conv_out_dem")
1519
+ dem_state_dict[new_name] = param
1520
+ if block == "conv_norm_out":
1521
+ new_name = name.replace("conv_norm_out","conv_norm_out_img")
1522
+ dem_state_dict[new_name] = param
1523
+ new_name = name.replace("conv_norm_out","conv_norm_out_dem")
1524
+ dem_state_dict[new_name] = param
1525
+
1526
+ model_dem.load_state_dict(dem_state_dict)
1527
+
1528
+ return model_dem
src/.ipynb_checkpoints/pipeline_terrain-checkpoint.py ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###########################################################################
2
+ # References:
3
+ # https://github.com/huggingface/diffusers/
4
+ ###########################################################################
5
+
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ import inspect
11
+ from typing import Any, Callable, Dict, List, Optional, Union
12
+
13
+ import torch
14
+ from packaging import version
15
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
16
+
17
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
18
+ from diffusers.configuration_utils import FrozenDict
19
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
20
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
21
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
22
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
23
+ from diffusers.schedulers import KarrasDiffusionSchedulers
24
+ from diffusers.utils import (
25
+ USE_PEFT_BACKEND,
26
+ deprecate,
27
+ is_torch_xla_available,
28
+ logging,
29
+ replace_example_docstring,
30
+ scale_lora_layers,
31
+ unscale_lora_layers,
32
+ )
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
35
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
36
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
37
+
38
+
39
+ if is_torch_xla_available():
40
+ import torch_xla.core.xla_model as xm
41
+
42
+ XLA_AVAILABLE = True
43
+ else:
44
+ XLA_AVAILABLE = False
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```py
51
+ >>> import torch
52
+ >>> from diffusers import StableDiffusionPipeline
53
+
54
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
55
+ >>> pipe = pipe.to("cuda")
56
+
57
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
58
+ >>> image = pipe(prompt).images[0]
59
+ ```
60
+ """
61
+
62
+
63
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
64
+ """
65
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
66
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
67
+ """
68
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
69
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
70
+ # rescale the results from guidance (fixes overexposure)
71
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
72
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
73
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
74
+ return noise_cfg
75
+
76
+
77
+ def retrieve_timesteps(
78
+ scheduler,
79
+ num_inference_steps: Optional[int] = None,
80
+ device: Optional[Union[str, torch.device]] = None,
81
+ timesteps: Optional[List[int]] = None,
82
+ sigmas: Optional[List[float]] = None,
83
+ **kwargs,
84
+ ):
85
+ """
86
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
87
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
88
+
89
+ Args:
90
+ scheduler (`SchedulerMixin`):
91
+ The scheduler to get timesteps from.
92
+ num_inference_steps (`int`):
93
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
94
+ must be `None`.
95
+ device (`str` or `torch.device`, *optional*):
96
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
97
+ timesteps (`List[int]`, *optional*):
98
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
99
+ `num_inference_steps` and `sigmas` must be `None`.
100
+ sigmas (`List[float]`, *optional*):
101
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
102
+ `num_inference_steps` and `timesteps` must be `None`.
103
+
104
+ Returns:
105
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
106
+ second element is the number of inference steps.
107
+ """
108
+ if timesteps is not None and sigmas is not None:
109
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
110
+ if timesteps is not None:
111
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
112
+ if not accepts_timesteps:
113
+ raise ValueError(
114
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
115
+ f" timestep schedules. Please check whether you are using the correct scheduler."
116
+ )
117
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
118
+ timesteps = scheduler.timesteps
119
+ num_inference_steps = len(timesteps)
120
+ elif sigmas is not None:
121
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
122
+ if not accept_sigmas:
123
+ raise ValueError(
124
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
125
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
126
+ )
127
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
128
+ timesteps = scheduler.timesteps
129
+ num_inference_steps = len(timesteps)
130
+ else:
131
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ return timesteps, num_inference_steps
134
+
135
+
136
+ class TerrainDiffusionPipeline(
137
+ DiffusionPipeline,
138
+ StableDiffusionMixin,
139
+ TextualInversionLoaderMixin,
140
+ StableDiffusionLoraLoaderMixin,
141
+ IPAdapterMixin,
142
+ FromSingleFileMixin,
143
+ ):
144
+ r"""
145
+ Pipeline for text-to-image generation using Stable Diffusion.
146
+
147
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
148
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
149
+
150
+ The pipeline also inherits the following loading methods:
151
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
152
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
153
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
154
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
155
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
156
+
157
+ Args:
158
+ vae ([`AutoencoderKL`]):
159
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
160
+ text_encoder ([`~transformers.CLIPTextModel`]):
161
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
162
+ tokenizer ([`~transformers.CLIPTokenizer`]):
163
+ A `CLIPTokenizer` to tokenize text.
164
+ unet ([`UNet2DConditionModel`]):
165
+ A `UNet2DConditionModel` to denoise the encoded image latents.
166
+ scheduler ([`SchedulerMixin`]):
167
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
168
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
169
+ safety_checker ([`StableDiffusionSafetyChecker`]):
170
+ Classification module that estimates whether generated images could be considered offensive or harmful.
171
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
172
+ about a model's potential harms.
173
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
174
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
175
+ """
176
+
177
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
178
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
179
+ _exclude_from_cpu_offload = ["safety_checker"]
180
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
181
+
182
+ def __init__(
183
+ self,
184
+ vae: AutoencoderKL,
185
+ text_encoder: CLIPTextModel,
186
+ tokenizer: CLIPTokenizer,
187
+ unet: UNet2DConditionModel,
188
+ scheduler: KarrasDiffusionSchedulers,
189
+ safety_checker: StableDiffusionSafetyChecker,
190
+ feature_extractor: CLIPImageProcessor,
191
+ image_encoder: CLIPVisionModelWithProjection = None,
192
+ requires_safety_checker: bool = True,
193
+ ):
194
+ super().__init__()
195
+
196
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
197
+ deprecation_message = (
198
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
199
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
200
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
201
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
202
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
203
+ " file"
204
+ )
205
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
206
+ new_config = dict(scheduler.config)
207
+ new_config["steps_offset"] = 1
208
+ scheduler._internal_dict = FrozenDict(new_config)
209
+
210
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
211
+ deprecation_message = (
212
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
213
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
214
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
215
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
216
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
217
+ )
218
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
219
+ new_config = dict(scheduler.config)
220
+ new_config["clip_sample"] = False
221
+ scheduler._internal_dict = FrozenDict(new_config)
222
+
223
+ if safety_checker is None and requires_safety_checker:
224
+ logger.warning(
225
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
226
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
227
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
228
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
229
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
230
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
231
+ )
232
+
233
+ if safety_checker is not None and feature_extractor is None:
234
+ raise ValueError(
235
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
236
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
237
+ )
238
+
239
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
240
+ version.parse(unet.config._diffusers_version).base_version
241
+ ) < version.parse("0.9.0.dev0")
242
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
243
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
244
+ deprecation_message = (
245
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
246
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
247
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
248
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
249
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
250
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
251
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
252
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
253
+ " the `unet/config.json` file"
254
+ )
255
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
256
+ new_config = dict(unet.config)
257
+ new_config["sample_size"] = 64
258
+ unet._internal_dict = FrozenDict(new_config)
259
+
260
+ self.register_modules(
261
+ vae=vae,
262
+ text_encoder=text_encoder,
263
+ tokenizer=tokenizer,
264
+ unet=unet,
265
+ scheduler=scheduler,
266
+ safety_checker=safety_checker,
267
+ feature_extractor=feature_extractor,
268
+ image_encoder=image_encoder,
269
+ )
270
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
271
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
272
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
273
+
274
+ def _encode_prompt(
275
+ self,
276
+ prompt,
277
+ device,
278
+ num_images_per_prompt,
279
+ do_classifier_free_guidance,
280
+ negative_prompt=None,
281
+ prompt_embeds: Optional[torch.Tensor] = None,
282
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
283
+ lora_scale: Optional[float] = None,
284
+ **kwargs,
285
+ ):
286
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
287
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
288
+
289
+ prompt_embeds_tuple = self.encode_prompt(
290
+ prompt=prompt,
291
+ device=device,
292
+ num_images_per_prompt=num_images_per_prompt,
293
+ do_classifier_free_guidance=do_classifier_free_guidance,
294
+ negative_prompt=negative_prompt,
295
+ prompt_embeds=prompt_embeds,
296
+ negative_prompt_embeds=negative_prompt_embeds,
297
+ lora_scale=lora_scale,
298
+ **kwargs,
299
+ )
300
+
301
+ # concatenate for backwards comp
302
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
303
+
304
+ return prompt_embeds
305
+
306
+ def encode_prompt(
307
+ self,
308
+ prompt,
309
+ device,
310
+ num_images_per_prompt,
311
+ do_classifier_free_guidance,
312
+ negative_prompt=None,
313
+ prompt_embeds: Optional[torch.Tensor] = None,
314
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
315
+ lora_scale: Optional[float] = None,
316
+ clip_skip: Optional[int] = None,
317
+ ):
318
+ r"""
319
+ Encodes the prompt into text encoder hidden states.
320
+
321
+ Args:
322
+ prompt (`str` or `List[str]`, *optional*):
323
+ prompt to be encoded
324
+ device: (`torch.device`):
325
+ torch device
326
+ num_images_per_prompt (`int`):
327
+ number of images that should be generated per prompt
328
+ do_classifier_free_guidance (`bool`):
329
+ whether to use classifier free guidance or not
330
+ negative_prompt (`str` or `List[str]`, *optional*):
331
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
332
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
333
+ less than `1`).
334
+ prompt_embeds (`torch.Tensor`, *optional*):
335
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
336
+ provided, text embeddings will be generated from `prompt` input argument.
337
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
338
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
339
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
340
+ argument.
341
+ lora_scale (`float`, *optional*):
342
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
343
+ clip_skip (`int`, *optional*):
344
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
345
+ the output of the pre-final layer will be used for computing the prompt embeddings.
346
+ """
347
+ # set lora scale so that monkey patched LoRA
348
+ # function of text encoder can correctly access it
349
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
350
+ self._lora_scale = lora_scale
351
+
352
+ # dynamically adjust the LoRA scale
353
+ if not USE_PEFT_BACKEND:
354
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
355
+ else:
356
+ scale_lora_layers(self.text_encoder, lora_scale)
357
+
358
+ if prompt is not None and isinstance(prompt, str):
359
+ batch_size = 1
360
+ elif prompt is not None and isinstance(prompt, list):
361
+ batch_size = len(prompt)
362
+ else:
363
+ batch_size = prompt_embeds.shape[0]
364
+
365
+ if prompt_embeds is None:
366
+ # textual inversion: process multi-vector tokens if necessary
367
+ if isinstance(self, TextualInversionLoaderMixin):
368
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
369
+
370
+ text_inputs = self.tokenizer(
371
+ prompt,
372
+ padding="max_length",
373
+ max_length=self.tokenizer.model_max_length,
374
+ truncation=True,
375
+ return_tensors="pt",
376
+ )
377
+ text_input_ids = text_inputs.input_ids
378
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
379
+
380
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
381
+ text_input_ids, untruncated_ids
382
+ ):
383
+ removed_text = self.tokenizer.batch_decode(
384
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
385
+ )
386
+ logger.warning(
387
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
388
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
389
+ )
390
+
391
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
392
+ attention_mask = text_inputs.attention_mask.to(device)
393
+ else:
394
+ attention_mask = None
395
+
396
+ if clip_skip is None:
397
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
398
+ prompt_embeds = prompt_embeds[0]
399
+ else:
400
+ prompt_embeds = self.text_encoder(
401
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
402
+ )
403
+ # Access the `hidden_states` first, that contains a tuple of
404
+ # all the hidden states from the encoder layers. Then index into
405
+ # the tuple to access the hidden states from the desired layer.
406
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
407
+ # We also need to apply the final LayerNorm here to not mess with the
408
+ # representations. The `last_hidden_states` that we typically use for
409
+ # obtaining the final prompt representations passes through the LayerNorm
410
+ # layer.
411
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
412
+
413
+ if self.text_encoder is not None:
414
+ prompt_embeds_dtype = self.text_encoder.dtype
415
+ elif self.unet is not None:
416
+ prompt_embeds_dtype = self.unet.dtype
417
+ else:
418
+ prompt_embeds_dtype = prompt_embeds.dtype
419
+
420
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
421
+
422
+ bs_embed, seq_len, _ = prompt_embeds.shape
423
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
424
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
425
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
426
+
427
+ # get unconditional embeddings for classifier free guidance
428
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
429
+ uncond_tokens: List[str]
430
+ if negative_prompt is None:
431
+ uncond_tokens = [""] * batch_size
432
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
433
+ raise TypeError(
434
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
435
+ f" {type(prompt)}."
436
+ )
437
+ elif isinstance(negative_prompt, str):
438
+ uncond_tokens = [negative_prompt]
439
+ elif batch_size != len(negative_prompt):
440
+ raise ValueError(
441
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
442
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
443
+ " the batch size of `prompt`."
444
+ )
445
+ else:
446
+ uncond_tokens = negative_prompt
447
+
448
+ # textual inversion: process multi-vector tokens if necessary
449
+ if isinstance(self, TextualInversionLoaderMixin):
450
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
451
+
452
+ max_length = prompt_embeds.shape[1]
453
+ uncond_input = self.tokenizer(
454
+ uncond_tokens,
455
+ padding="max_length",
456
+ max_length=max_length,
457
+ truncation=True,
458
+ return_tensors="pt",
459
+ )
460
+
461
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
462
+ attention_mask = uncond_input.attention_mask.to(device)
463
+ else:
464
+ attention_mask = None
465
+
466
+ negative_prompt_embeds = self.text_encoder(
467
+ uncond_input.input_ids.to(device),
468
+ attention_mask=attention_mask,
469
+ )
470
+ negative_prompt_embeds = negative_prompt_embeds[0]
471
+
472
+ if do_classifier_free_guidance:
473
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
474
+ seq_len = negative_prompt_embeds.shape[1]
475
+
476
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
477
+
478
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
479
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
480
+
481
+ if self.text_encoder is not None:
482
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
483
+ # Retrieve the original scale by scaling back the LoRA layers
484
+ unscale_lora_layers(self.text_encoder, lora_scale)
485
+
486
+ return prompt_embeds, negative_prompt_embeds
487
+
488
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
489
+ dtype = next(self.image_encoder.parameters()).dtype
490
+
491
+ if not isinstance(image, torch.Tensor):
492
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
493
+
494
+ image = image.to(device=device, dtype=dtype)
495
+ if output_hidden_states:
496
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
497
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
498
+ uncond_image_enc_hidden_states = self.image_encoder(
499
+ torch.zeros_like(image), output_hidden_states=True
500
+ ).hidden_states[-2]
501
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
502
+ num_images_per_prompt, dim=0
503
+ )
504
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
505
+ else:
506
+ image_embeds = self.image_encoder(image).image_embeds
507
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
508
+ uncond_image_embeds = torch.zeros_like(image_embeds)
509
+
510
+ return image_embeds, uncond_image_embeds
511
+
512
+ def prepare_ip_adapter_image_embeds(
513
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
514
+ ):
515
+ image_embeds = []
516
+ if do_classifier_free_guidance:
517
+ negative_image_embeds = []
518
+ if ip_adapter_image_embeds is None:
519
+ if not isinstance(ip_adapter_image, list):
520
+ ip_adapter_image = [ip_adapter_image]
521
+
522
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
523
+ raise ValueError(
524
+ 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."
525
+ )
526
+
527
+ for single_ip_adapter_image, image_proj_layer in zip(
528
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
529
+ ):
530
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
531
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
532
+ single_ip_adapter_image, device, 1, output_hidden_state
533
+ )
534
+
535
+ image_embeds.append(single_image_embeds[None, :])
536
+ if do_classifier_free_guidance:
537
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
538
+ else:
539
+ for single_image_embeds in ip_adapter_image_embeds:
540
+ if do_classifier_free_guidance:
541
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
542
+ negative_image_embeds.append(single_negative_image_embeds)
543
+ image_embeds.append(single_image_embeds)
544
+
545
+ ip_adapter_image_embeds = []
546
+ for i, single_image_embeds in enumerate(image_embeds):
547
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
548
+ if do_classifier_free_guidance:
549
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
550
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
551
+
552
+ single_image_embeds = single_image_embeds.to(device=device)
553
+ ip_adapter_image_embeds.append(single_image_embeds)
554
+
555
+ return ip_adapter_image_embeds
556
+
557
+
558
+ def decode_latents(self, latents):
559
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
560
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
561
+
562
+ latents = 1 / self.vae.config.scaling_factor * latents
563
+ image = self.vae.decode(latents, return_dict=False)[0]
564
+ image = (image / 2 + 0.5).clamp(0, 1)
565
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
566
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
567
+ return image
568
+
569
+ def prepare_extra_step_kwargs(self, generator, eta):
570
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
571
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
572
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
573
+ # and should be between [0, 1]
574
+
575
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
576
+ extra_step_kwargs = {}
577
+ if accepts_eta:
578
+ extra_step_kwargs["eta"] = eta
579
+
580
+ # check if the scheduler accepts generator
581
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
582
+ if accepts_generator:
583
+ extra_step_kwargs["generator"] = generator
584
+ return extra_step_kwargs
585
+
586
+ def check_inputs(
587
+ self,
588
+ prompt,
589
+ height,
590
+ width,
591
+ callback_steps,
592
+ negative_prompt=None,
593
+ prompt_embeds=None,
594
+ negative_prompt_embeds=None,
595
+ ip_adapter_image=None,
596
+ ip_adapter_image_embeds=None,
597
+ callback_on_step_end_tensor_inputs=None,
598
+ ):
599
+ if height % 8 != 0 or width % 8 != 0:
600
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
601
+
602
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
603
+ raise ValueError(
604
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
605
+ f" {type(callback_steps)}."
606
+ )
607
+ if callback_on_step_end_tensor_inputs is not None and not all(
608
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
609
+ ):
610
+ raise ValueError(
611
+ 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]}"
612
+ )
613
+
614
+ if prompt is not None and prompt_embeds is not None:
615
+ raise ValueError(
616
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
617
+ " only forward one of the two."
618
+ )
619
+ elif prompt is None and prompt_embeds is None:
620
+ raise ValueError(
621
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
622
+ )
623
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
624
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
625
+
626
+ if negative_prompt is not None and negative_prompt_embeds is not None:
627
+ raise ValueError(
628
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
629
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
630
+ )
631
+
632
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
633
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
634
+ raise ValueError(
635
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
636
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
637
+ f" {negative_prompt_embeds.shape}."
638
+ )
639
+
640
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
641
+ raise ValueError(
642
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
643
+ )
644
+
645
+ if ip_adapter_image_embeds is not None:
646
+ if not isinstance(ip_adapter_image_embeds, list):
647
+ raise ValueError(
648
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
649
+ )
650
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
651
+ raise ValueError(
652
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
653
+ )
654
+
655
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
656
+ shape = (
657
+ batch_size,
658
+ num_channels_latents,
659
+ int(height) // self.vae_scale_factor,
660
+ int(width) // self.vae_scale_factor,
661
+ )
662
+ if isinstance(generator, list) and len(generator) != batch_size:
663
+ raise ValueError(
664
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
665
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
666
+ )
667
+
668
+ if latents is None:
669
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
670
+ else:
671
+ latents = latents.to(device)
672
+
673
+ # scale the initial noise by the standard deviation required by the scheduler
674
+ latents = latents * self.scheduler.init_noise_sigma
675
+ return latents
676
+
677
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
678
+ def get_guidance_scale_embedding(
679
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
680
+ ) -> torch.Tensor:
681
+ """
682
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
683
+
684
+ Args:
685
+ w (`torch.Tensor`):
686
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
687
+ embedding_dim (`int`, *optional*, defaults to 512):
688
+ Dimension of the embeddings to generate.
689
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
690
+ Data type of the generated embeddings.
691
+
692
+ Returns:
693
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
694
+ """
695
+ assert len(w.shape) == 1
696
+ w = w * 1000.0
697
+
698
+ half_dim = embedding_dim // 2
699
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
700
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
701
+ emb = w.to(dtype)[:, None] * emb[None, :]
702
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
703
+ if embedding_dim % 2 == 1: # zero pad
704
+ emb = torch.nn.functional.pad(emb, (0, 1))
705
+ assert emb.shape == (w.shape[0], embedding_dim)
706
+ return emb
707
+
708
+ @property
709
+ def guidance_scale(self):
710
+ return self._guidance_scale
711
+
712
+ @property
713
+ def guidance_rescale(self):
714
+ return self._guidance_rescale
715
+
716
+ @property
717
+ def clip_skip(self):
718
+ return self._clip_skip
719
+
720
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
721
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
722
+ # corresponds to doing no classifier free guidance.
723
+ @property
724
+ def do_classifier_free_guidance(self):
725
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
726
+
727
+ @property
728
+ def cross_attention_kwargs(self):
729
+ return self._cross_attention_kwargs
730
+
731
+ @property
732
+ def num_timesteps(self):
733
+ return self._num_timesteps
734
+
735
+ @property
736
+ def interrupt(self):
737
+ return self._interrupt
738
+
739
+ def decode_rgbd(self, latents,generator,output_type="np"):
740
+ dem_latents = latents[:,4:,:,:]
741
+ img_latents = latents[:,:4,:,:]
742
+ image = self.vae.decode(img_latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
743
+ 0
744
+ ]
745
+ dem = self.vae.decode(dem_latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
746
+ 0
747
+ ]
748
+ do_denormalize = [True] * image.shape[0]
749
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
750
+ dem = self.image_processor.postprocess(dem, output_type=output_type, do_denormalize=do_denormalize)
751
+ return image,dem
752
+
753
+ @torch.no_grad()
754
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
755
+ def __call__(
756
+ self,
757
+ prompt: Union[str, List[str]] = None,
758
+ height: Optional[int] = None,
759
+ width: Optional[int] = None,
760
+ num_inference_steps: int = 50,
761
+ timesteps: List[int] = None,
762
+ sigmas: List[float] = None,
763
+ guidance_scale: float = 7.5,
764
+ negative_prompt: Optional[Union[str, List[str]]] = None,
765
+ num_images_per_prompt: Optional[int] = 1,
766
+ eta: float = 0.0,
767
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
768
+ latents: Optional[torch.Tensor] = None,
769
+ prompt_embeds: Optional[torch.Tensor] = None,
770
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
771
+ ip_adapter_image: Optional[PipelineImageInput] = None,
772
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
773
+ output_type: Optional[str] = "np",
774
+ return_dict: bool = True,
775
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
776
+ guidance_rescale: float = 0.0,
777
+ clip_skip: Optional[int] = None,
778
+ callback_on_step_end: Optional[
779
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
780
+ ] = None,
781
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
782
+ **kwargs,
783
+ ):
784
+ r"""
785
+ The call function to the pipeline for generation.
786
+
787
+ Args:
788
+ prompt (`str` or `List[str]`, *optional*):
789
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
790
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
791
+ The height in pixels of the generated image.
792
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
793
+ The width in pixels of the generated image.
794
+ num_inference_steps (`int`, *optional*, defaults to 50):
795
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
796
+ expense of slower inference.
797
+ timesteps (`List[int]`, *optional*):
798
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
799
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
800
+ passed will be used. Must be in descending order.
801
+ sigmas (`List[float]`, *optional*):
802
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
803
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
804
+ will be used.
805
+ guidance_scale (`float`, *optional*, defaults to 7.5):
806
+ A higher guidance scale value encourages the model to generate images closely linked to the text
807
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
808
+ negative_prompt (`str` or `List[str]`, *optional*):
809
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
810
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
811
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
812
+ The number of images to generate per prompt.
813
+ eta (`float`, *optional*, defaults to 0.0):
814
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
815
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
816
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
817
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
818
+ generation deterministic.
819
+ latents (`torch.Tensor`, *optional*):
820
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
821
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
822
+ tensor is generated by sampling using the supplied random `generator`.
823
+ prompt_embeds (`torch.Tensor`, *optional*):
824
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
825
+ provided, text embeddings are generated from the `prompt` input argument.
826
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
827
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
828
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
829
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
830
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
831
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
832
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
833
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
834
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
835
+ output_type (`str`, *optional*, defaults to `"pil"`):
836
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
837
+ return_dict (`bool`, *optional*, defaults to `True`):
838
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
839
+ plain tuple.
840
+ cross_attention_kwargs (`dict`, *optional*):
841
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
842
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
843
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
844
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
845
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
846
+ using zero terminal SNR.
847
+ clip_skip (`int`, *optional*):
848
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
849
+ the output of the pre-final layer will be used for computing the prompt embeddings.
850
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
851
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
852
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
853
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
854
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
855
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
856
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
857
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
858
+ `._callback_tensor_inputs` attribute of your pipeline class.
859
+
860
+ Examples:
861
+
862
+ Returns:
863
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
864
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
865
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
866
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
867
+ "not-safe-for-work" (nsfw) content.
868
+ """
869
+
870
+ callback = kwargs.pop("callback", None)
871
+ callback_steps = kwargs.pop("callback_steps", None)
872
+
873
+ if callback is not None:
874
+ deprecate(
875
+ "callback",
876
+ "1.0.0",
877
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
878
+ )
879
+ if callback_steps is not None:
880
+ deprecate(
881
+ "callback_steps",
882
+ "1.0.0",
883
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
884
+ )
885
+
886
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
887
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
888
+
889
+ # 0. Default height and width to unet
890
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
891
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
892
+ # to deal with lora scaling and other possible forward hooks
893
+
894
+ # 1. Check inputs. Raise error if not correct
895
+ self.check_inputs(
896
+ prompt,
897
+ height,
898
+ width,
899
+ callback_steps,
900
+ negative_prompt,
901
+ prompt_embeds,
902
+ negative_prompt_embeds,
903
+ ip_adapter_image,
904
+ ip_adapter_image_embeds,
905
+ callback_on_step_end_tensor_inputs,
906
+ )
907
+
908
+ self._guidance_scale = guidance_scale
909
+ self._guidance_rescale = guidance_rescale
910
+ self._clip_skip = clip_skip
911
+ self._cross_attention_kwargs = cross_attention_kwargs
912
+ self._interrupt = False
913
+
914
+ # 2. Define call parameters
915
+ if prompt is not None and isinstance(prompt, str):
916
+ batch_size = 1
917
+ elif prompt is not None and isinstance(prompt, list):
918
+ batch_size = len(prompt)
919
+ else:
920
+ batch_size = prompt_embeds.shape[0]
921
+
922
+ device = self._execution_device
923
+
924
+ # 3. Encode input prompt
925
+ lora_scale = (
926
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
927
+ )
928
+
929
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
930
+ prompt,
931
+ device,
932
+ num_images_per_prompt,
933
+ self.do_classifier_free_guidance,
934
+ negative_prompt,
935
+ prompt_embeds=prompt_embeds,
936
+ negative_prompt_embeds=negative_prompt_embeds,
937
+ lora_scale=lora_scale,
938
+ clip_skip=self.clip_skip,
939
+ )
940
+
941
+ # For classifier free guidance, we need to do two forward passes.
942
+ # Here we concatenate the unconditional and text embeddings into a single batch
943
+ # to avoid doing two forward passes
944
+ if self.do_classifier_free_guidance:
945
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
946
+
947
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
948
+ image_embeds = self.prepare_ip_adapter_image_embeds(
949
+ ip_adapter_image,
950
+ ip_adapter_image_embeds,
951
+ device,
952
+ batch_size * num_images_per_prompt,
953
+ self.do_classifier_free_guidance,
954
+ )
955
+
956
+ # 4. Prepare timesteps
957
+ timesteps, num_inference_steps = retrieve_timesteps(
958
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
959
+ )
960
+
961
+ # 5. Prepare latent variables
962
+ num_channels_latents = self.unet.config.in_channels*2
963
+ latents = self.prepare_latents(
964
+ batch_size * num_images_per_prompt,
965
+ num_channels_latents,
966
+ height,
967
+ width,
968
+ prompt_embeds.dtype,
969
+ device,
970
+ generator,
971
+ latents,
972
+ )
973
+
974
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
975
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
976
+
977
+ # 6.1 Add image embeds for IP-Adapter
978
+ added_cond_kwargs = (
979
+ {"image_embeds": image_embeds}
980
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
981
+ else None
982
+ )
983
+
984
+ # 6.2 Optionally get Guidance Scale Embedding
985
+ timestep_cond = None
986
+ if self.unet.config.time_cond_proj_dim is not None:
987
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
988
+ timestep_cond = self.get_guidance_scale_embedding(
989
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
990
+ ).to(device=device, dtype=latents.dtype)
991
+
992
+ # 7. Denoising loop
993
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
994
+ self._num_timesteps = len(timesteps)
995
+ # intermediate_latents = []
996
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
997
+ for i, t in enumerate(timesteps):
998
+ if self.interrupt:
999
+ continue
1000
+
1001
+ # expand the latents if we are doing classifier free guidance
1002
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1003
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1004
+
1005
+ # predict the noise residual
1006
+ noise_pred = self.unet(
1007
+ latent_model_input,
1008
+ t,
1009
+ encoder_hidden_states=prompt_embeds,
1010
+ timestep_cond=timestep_cond,
1011
+ cross_attention_kwargs=self.cross_attention_kwargs,
1012
+ added_cond_kwargs=added_cond_kwargs,
1013
+ return_dict=False,
1014
+ )[0]
1015
+
1016
+ # perform guidance
1017
+ if self.do_classifier_free_guidance:
1018
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1019
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1020
+
1021
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1022
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1023
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1024
+
1025
+ # compute the previous noisy sample x_t -> x_t-1
1026
+ scheduler_output = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=True)
1027
+ latents = scheduler_output.prev_sample
1028
+ # if i % 10 == 0:
1029
+ # intermediate_latents.append(scheduler_output.pred_original_sample)
1030
+ if callback_on_step_end is not None:
1031
+ callback_kwargs = {}
1032
+ for k in callback_on_step_end_tensor_inputs:
1033
+ callback_kwargs[k] = locals()[k]
1034
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1035
+
1036
+ latents = callback_outputs.pop("latents", latents)
1037
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1038
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1039
+
1040
+ # call the callback, if provided
1041
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1042
+ progress_bar.update()
1043
+ if callback is not None and i % callback_steps == 0:
1044
+ step_idx = i // getattr(self.scheduler, "order", 1)
1045
+ callback(step_idx, t, latents)
1046
+
1047
+ if XLA_AVAILABLE:
1048
+ xm.mark_step()
1049
+
1050
+ image,dem = self.decode_rgbd(latents,generator,output_type)
1051
+
1052
+ # intermediate = [self.decode_rgbd(latent,generator,output_type)for latent in intermediate_latents]
1053
+
1054
+ # Offload all models
1055
+ self.maybe_free_model_hooks()
1056
+
1057
+ return image,dem
src/.ipynb_checkpoints/utils-checkpoint.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import trimesh
3
+ import tempfile
4
+ import torch
5
+ from scipy.spatial import Delaunay
6
+ from .build_pipe import *
7
+
8
+ pipe = build_pipe()
9
+
10
+ def generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
11
+ """Generates terrain data (RGB and elevation) from a text prompt."""
12
+ if prefix and not prefix.endswith(' '):
13
+ prefix += ' ' # Ensure prefix ends with a space
14
+
15
+ full_prompt = prefix + prompt
16
+ generator = torch.Generator("cuda").manual_seed(seed)
17
+ image, dem = pipe(full_prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator)
18
+
19
+ # Center crop the image and dem
20
+ h, w, c = image[0].shape
21
+ start_h = (h - crop_size) // 2
22
+ start_w = (w - crop_size) // 2
23
+ end_h = start_h + crop_size
24
+ end_w = start_w + crop_size
25
+
26
+ cropped_image = image[0][start_h:end_h, start_w:end_w, :]
27
+ cropped_dem = dem[0][start_h:end_h, start_w:end_w, :]
28
+
29
+ return (255 * cropped_image).astype(np.uint8), 500*cropped_dem.mean(-1)
30
+
31
+ def simplify_mesh(mesh, target_face_count):
32
+ """Simplifies a mesh using quadric decimation."""
33
+ simplified_mesh = mesh.simplify_quadric_decimation(target_face_count)
34
+ return simplified_mesh
35
+
36
+ def create_3d_mesh(rgb, elevation):
37
+ """Creates a 3D mesh from RGB and elevation data."""
38
+ x, y = np.meshgrid(np.arange(elevation.shape[1]), np.arange(elevation.shape[0]))
39
+ points = np.stack([x.flatten(), y.flatten()], axis=-1)
40
+ tri = Delaunay(points)
41
+
42
+ vertices = np.stack([x.flatten(), y.flatten(), elevation.flatten()], axis=-1)
43
+ faces = tri.simplices
44
+
45
+ mesh = trimesh.Trimesh(vertices=vertices, faces=faces, vertex_colors=rgb.reshape(-1, 3))
46
+
47
+ #mesh = simplify_mesh(mesh, target_face_count=100)
48
+ return mesh
49
+
50
+ def generate_and_display(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
51
+ """Generates terrain and displays it as a 3D model."""
52
+ rgb, elevation = generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix)
53
+ mesh = create_3d_mesh(rgb, elevation)
54
+
55
+ with tempfile.NamedTemporaryFile(suffix=".obj", delete=False) as temp_file:
56
+ mesh.export(temp_file.name)
57
+ file_path = temp_file.name
58
+
59
+ return file_path
src/__pycache__/build_pipe.cpython-38.pyc ADDED
Binary file (775 Bytes). View file
 
src/__pycache__/pipeline_terrain.cpython-38.pyc ADDED
Binary file (35.4 kB). View file
 
src/__pycache__/utils.cpython-38.pyc ADDED
Binary file (2.12 kB). View file
 
src/build_pipe.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .pipeline_terrain import TerrainDiffusionPipeline
2
+ #import models
3
+ from huggingface_hub import hf_hub_download, snapshot_download
4
+ import os
5
+ import torch
6
+
7
+ def build_pipe():
8
+ print('Downloading weights...')
9
+ try:
10
+ os.mkdir('./weights/')
11
+ except:
12
+ True
13
+ snapshot_download(repo_id="NewtNewt/MESA", local_dir="./weights")
14
+ weight_path = './weights'
15
+ print('[DONE]')
16
+
17
+ print('Instantiating Model...')
18
+ pipe = TerrainDiffusionPipeline.from_pretrained(weight_path, torch_dtype=torch.float16)
19
+ pipe.to("cuda")
20
+ print('[DONE]')
21
+
22
+ return pipe
src/pipeline_terrain.py ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###########################################################################
2
+ # References:
3
+ # https://github.com/huggingface/diffusers/
4
+ ###########################################################################
5
+
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ import inspect
11
+ from typing import Any, Callable, Dict, List, Optional, Union
12
+
13
+ import torch
14
+ from packaging import version
15
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
16
+
17
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
18
+ from diffusers.configuration_utils import FrozenDict
19
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
20
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
21
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
22
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
23
+ from diffusers.schedulers import KarrasDiffusionSchedulers
24
+ from diffusers.utils import (
25
+ USE_PEFT_BACKEND,
26
+ deprecate,
27
+ is_torch_xla_available,
28
+ logging,
29
+ replace_example_docstring,
30
+ scale_lora_layers,
31
+ unscale_lora_layers,
32
+ )
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
35
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
36
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
37
+
38
+
39
+ if is_torch_xla_available():
40
+ import torch_xla.core.xla_model as xm
41
+
42
+ XLA_AVAILABLE = True
43
+ else:
44
+ XLA_AVAILABLE = False
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```py
51
+ >>> import torch
52
+ >>> from diffusers import StableDiffusionPipeline
53
+
54
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
55
+ >>> pipe = pipe.to("cuda")
56
+
57
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
58
+ >>> image = pipe(prompt).images[0]
59
+ ```
60
+ """
61
+
62
+
63
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
64
+ """
65
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
66
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
67
+ """
68
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
69
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
70
+ # rescale the results from guidance (fixes overexposure)
71
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
72
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
73
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
74
+ return noise_cfg
75
+
76
+
77
+ def retrieve_timesteps(
78
+ scheduler,
79
+ num_inference_steps: Optional[int] = None,
80
+ device: Optional[Union[str, torch.device]] = None,
81
+ timesteps: Optional[List[int]] = None,
82
+ sigmas: Optional[List[float]] = None,
83
+ **kwargs,
84
+ ):
85
+ """
86
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
87
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
88
+
89
+ Args:
90
+ scheduler (`SchedulerMixin`):
91
+ The scheduler to get timesteps from.
92
+ num_inference_steps (`int`):
93
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
94
+ must be `None`.
95
+ device (`str` or `torch.device`, *optional*):
96
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
97
+ timesteps (`List[int]`, *optional*):
98
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
99
+ `num_inference_steps` and `sigmas` must be `None`.
100
+ sigmas (`List[float]`, *optional*):
101
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
102
+ `num_inference_steps` and `timesteps` must be `None`.
103
+
104
+ Returns:
105
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
106
+ second element is the number of inference steps.
107
+ """
108
+ if timesteps is not None and sigmas is not None:
109
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
110
+ if timesteps is not None:
111
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
112
+ if not accepts_timesteps:
113
+ raise ValueError(
114
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
115
+ f" timestep schedules. Please check whether you are using the correct scheduler."
116
+ )
117
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
118
+ timesteps = scheduler.timesteps
119
+ num_inference_steps = len(timesteps)
120
+ elif sigmas is not None:
121
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
122
+ if not accept_sigmas:
123
+ raise ValueError(
124
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
125
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
126
+ )
127
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
128
+ timesteps = scheduler.timesteps
129
+ num_inference_steps = len(timesteps)
130
+ else:
131
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ return timesteps, num_inference_steps
134
+
135
+
136
+ class TerrainDiffusionPipeline(
137
+ DiffusionPipeline,
138
+ StableDiffusionMixin,
139
+ TextualInversionLoaderMixin,
140
+ StableDiffusionLoraLoaderMixin,
141
+ IPAdapterMixin,
142
+ FromSingleFileMixin,
143
+ ):
144
+ r"""
145
+ Pipeline for text-to-image generation using Stable Diffusion.
146
+
147
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
148
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
149
+
150
+ The pipeline also inherits the following loading methods:
151
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
152
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
153
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
154
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
155
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
156
+
157
+ Args:
158
+ vae ([`AutoencoderKL`]):
159
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
160
+ text_encoder ([`~transformers.CLIPTextModel`]):
161
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
162
+ tokenizer ([`~transformers.CLIPTokenizer`]):
163
+ A `CLIPTokenizer` to tokenize text.
164
+ unet ([`UNet2DConditionModel`]):
165
+ A `UNet2DConditionModel` to denoise the encoded image latents.
166
+ scheduler ([`SchedulerMixin`]):
167
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
168
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
169
+ safety_checker ([`StableDiffusionSafetyChecker`]):
170
+ Classification module that estimates whether generated images could be considered offensive or harmful.
171
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
172
+ about a model's potential harms.
173
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
174
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
175
+ """
176
+
177
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
178
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
179
+ _exclude_from_cpu_offload = ["safety_checker"]
180
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
181
+
182
+ def __init__(
183
+ self,
184
+ vae: AutoencoderKL,
185
+ text_encoder: CLIPTextModel,
186
+ tokenizer: CLIPTokenizer,
187
+ unet: UNet2DConditionModel,
188
+ scheduler: KarrasDiffusionSchedulers,
189
+ safety_checker: StableDiffusionSafetyChecker,
190
+ feature_extractor: CLIPImageProcessor,
191
+ image_encoder: CLIPVisionModelWithProjection = None,
192
+ requires_safety_checker: bool = True,
193
+ ):
194
+ super().__init__()
195
+
196
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
197
+ deprecation_message = (
198
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
199
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
200
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
201
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
202
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
203
+ " file"
204
+ )
205
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
206
+ new_config = dict(scheduler.config)
207
+ new_config["steps_offset"] = 1
208
+ scheduler._internal_dict = FrozenDict(new_config)
209
+
210
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
211
+ deprecation_message = (
212
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
213
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
214
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
215
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
216
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
217
+ )
218
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
219
+ new_config = dict(scheduler.config)
220
+ new_config["clip_sample"] = False
221
+ scheduler._internal_dict = FrozenDict(new_config)
222
+
223
+ if safety_checker is None and requires_safety_checker:
224
+ logger.warning(
225
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
226
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
227
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
228
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
229
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
230
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
231
+ )
232
+
233
+ if safety_checker is not None and feature_extractor is None:
234
+ raise ValueError(
235
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
236
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
237
+ )
238
+
239
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
240
+ version.parse(unet.config._diffusers_version).base_version
241
+ ) < version.parse("0.9.0.dev0")
242
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
243
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
244
+ deprecation_message = (
245
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
246
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
247
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
248
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
249
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
250
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
251
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
252
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
253
+ " the `unet/config.json` file"
254
+ )
255
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
256
+ new_config = dict(unet.config)
257
+ new_config["sample_size"] = 64
258
+ unet._internal_dict = FrozenDict(new_config)
259
+
260
+ self.register_modules(
261
+ vae=vae,
262
+ text_encoder=text_encoder,
263
+ tokenizer=tokenizer,
264
+ unet=unet,
265
+ scheduler=scheduler,
266
+ safety_checker=safety_checker,
267
+ feature_extractor=feature_extractor,
268
+ image_encoder=image_encoder,
269
+ )
270
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
271
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
272
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
273
+
274
+ def _encode_prompt(
275
+ self,
276
+ prompt,
277
+ device,
278
+ num_images_per_prompt,
279
+ do_classifier_free_guidance,
280
+ negative_prompt=None,
281
+ prompt_embeds: Optional[torch.Tensor] = None,
282
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
283
+ lora_scale: Optional[float] = None,
284
+ **kwargs,
285
+ ):
286
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
287
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
288
+
289
+ prompt_embeds_tuple = self.encode_prompt(
290
+ prompt=prompt,
291
+ device=device,
292
+ num_images_per_prompt=num_images_per_prompt,
293
+ do_classifier_free_guidance=do_classifier_free_guidance,
294
+ negative_prompt=negative_prompt,
295
+ prompt_embeds=prompt_embeds,
296
+ negative_prompt_embeds=negative_prompt_embeds,
297
+ lora_scale=lora_scale,
298
+ **kwargs,
299
+ )
300
+
301
+ # concatenate for backwards comp
302
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
303
+
304
+ return prompt_embeds
305
+
306
+ def encode_prompt(
307
+ self,
308
+ prompt,
309
+ device,
310
+ num_images_per_prompt,
311
+ do_classifier_free_guidance,
312
+ negative_prompt=None,
313
+ prompt_embeds: Optional[torch.Tensor] = None,
314
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
315
+ lora_scale: Optional[float] = None,
316
+ clip_skip: Optional[int] = None,
317
+ ):
318
+ r"""
319
+ Encodes the prompt into text encoder hidden states.
320
+
321
+ Args:
322
+ prompt (`str` or `List[str]`, *optional*):
323
+ prompt to be encoded
324
+ device: (`torch.device`):
325
+ torch device
326
+ num_images_per_prompt (`int`):
327
+ number of images that should be generated per prompt
328
+ do_classifier_free_guidance (`bool`):
329
+ whether to use classifier free guidance or not
330
+ negative_prompt (`str` or `List[str]`, *optional*):
331
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
332
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
333
+ less than `1`).
334
+ prompt_embeds (`torch.Tensor`, *optional*):
335
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
336
+ provided, text embeddings will be generated from `prompt` input argument.
337
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
338
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
339
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
340
+ argument.
341
+ lora_scale (`float`, *optional*):
342
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
343
+ clip_skip (`int`, *optional*):
344
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
345
+ the output of the pre-final layer will be used for computing the prompt embeddings.
346
+ """
347
+ # set lora scale so that monkey patched LoRA
348
+ # function of text encoder can correctly access it
349
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
350
+ self._lora_scale = lora_scale
351
+
352
+ # dynamically adjust the LoRA scale
353
+ if not USE_PEFT_BACKEND:
354
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
355
+ else:
356
+ scale_lora_layers(self.text_encoder, lora_scale)
357
+
358
+ if prompt is not None and isinstance(prompt, str):
359
+ batch_size = 1
360
+ elif prompt is not None and isinstance(prompt, list):
361
+ batch_size = len(prompt)
362
+ else:
363
+ batch_size = prompt_embeds.shape[0]
364
+
365
+ if prompt_embeds is None:
366
+ # textual inversion: process multi-vector tokens if necessary
367
+ if isinstance(self, TextualInversionLoaderMixin):
368
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
369
+
370
+ text_inputs = self.tokenizer(
371
+ prompt,
372
+ padding="max_length",
373
+ max_length=self.tokenizer.model_max_length,
374
+ truncation=True,
375
+ return_tensors="pt",
376
+ )
377
+ text_input_ids = text_inputs.input_ids
378
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
379
+
380
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
381
+ text_input_ids, untruncated_ids
382
+ ):
383
+ removed_text = self.tokenizer.batch_decode(
384
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
385
+ )
386
+ logger.warning(
387
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
388
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
389
+ )
390
+
391
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
392
+ attention_mask = text_inputs.attention_mask.to(device)
393
+ else:
394
+ attention_mask = None
395
+
396
+ if clip_skip is None:
397
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
398
+ prompt_embeds = prompt_embeds[0]
399
+ else:
400
+ prompt_embeds = self.text_encoder(
401
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
402
+ )
403
+ # Access the `hidden_states` first, that contains a tuple of
404
+ # all the hidden states from the encoder layers. Then index into
405
+ # the tuple to access the hidden states from the desired layer.
406
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
407
+ # We also need to apply the final LayerNorm here to not mess with the
408
+ # representations. The `last_hidden_states` that we typically use for
409
+ # obtaining the final prompt representations passes through the LayerNorm
410
+ # layer.
411
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
412
+
413
+ if self.text_encoder is not None:
414
+ prompt_embeds_dtype = self.text_encoder.dtype
415
+ elif self.unet is not None:
416
+ prompt_embeds_dtype = self.unet.dtype
417
+ else:
418
+ prompt_embeds_dtype = prompt_embeds.dtype
419
+
420
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
421
+
422
+ bs_embed, seq_len, _ = prompt_embeds.shape
423
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
424
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
425
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
426
+
427
+ # get unconditional embeddings for classifier free guidance
428
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
429
+ uncond_tokens: List[str]
430
+ if negative_prompt is None:
431
+ uncond_tokens = [""] * batch_size
432
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
433
+ raise TypeError(
434
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
435
+ f" {type(prompt)}."
436
+ )
437
+ elif isinstance(negative_prompt, str):
438
+ uncond_tokens = [negative_prompt]
439
+ elif batch_size != len(negative_prompt):
440
+ raise ValueError(
441
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
442
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
443
+ " the batch size of `prompt`."
444
+ )
445
+ else:
446
+ uncond_tokens = negative_prompt
447
+
448
+ # textual inversion: process multi-vector tokens if necessary
449
+ if isinstance(self, TextualInversionLoaderMixin):
450
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
451
+
452
+ max_length = prompt_embeds.shape[1]
453
+ uncond_input = self.tokenizer(
454
+ uncond_tokens,
455
+ padding="max_length",
456
+ max_length=max_length,
457
+ truncation=True,
458
+ return_tensors="pt",
459
+ )
460
+
461
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
462
+ attention_mask = uncond_input.attention_mask.to(device)
463
+ else:
464
+ attention_mask = None
465
+
466
+ negative_prompt_embeds = self.text_encoder(
467
+ uncond_input.input_ids.to(device),
468
+ attention_mask=attention_mask,
469
+ )
470
+ negative_prompt_embeds = negative_prompt_embeds[0]
471
+
472
+ if do_classifier_free_guidance:
473
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
474
+ seq_len = negative_prompt_embeds.shape[1]
475
+
476
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
477
+
478
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
479
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
480
+
481
+ if self.text_encoder is not None:
482
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
483
+ # Retrieve the original scale by scaling back the LoRA layers
484
+ unscale_lora_layers(self.text_encoder, lora_scale)
485
+
486
+ return prompt_embeds, negative_prompt_embeds
487
+
488
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
489
+ dtype = next(self.image_encoder.parameters()).dtype
490
+
491
+ if not isinstance(image, torch.Tensor):
492
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
493
+
494
+ image = image.to(device=device, dtype=dtype)
495
+ if output_hidden_states:
496
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
497
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
498
+ uncond_image_enc_hidden_states = self.image_encoder(
499
+ torch.zeros_like(image), output_hidden_states=True
500
+ ).hidden_states[-2]
501
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
502
+ num_images_per_prompt, dim=0
503
+ )
504
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
505
+ else:
506
+ image_embeds = self.image_encoder(image).image_embeds
507
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
508
+ uncond_image_embeds = torch.zeros_like(image_embeds)
509
+
510
+ return image_embeds, uncond_image_embeds
511
+
512
+ def prepare_ip_adapter_image_embeds(
513
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
514
+ ):
515
+ image_embeds = []
516
+ if do_classifier_free_guidance:
517
+ negative_image_embeds = []
518
+ if ip_adapter_image_embeds is None:
519
+ if not isinstance(ip_adapter_image, list):
520
+ ip_adapter_image = [ip_adapter_image]
521
+
522
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
523
+ raise ValueError(
524
+ 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."
525
+ )
526
+
527
+ for single_ip_adapter_image, image_proj_layer in zip(
528
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
529
+ ):
530
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
531
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
532
+ single_ip_adapter_image, device, 1, output_hidden_state
533
+ )
534
+
535
+ image_embeds.append(single_image_embeds[None, :])
536
+ if do_classifier_free_guidance:
537
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
538
+ else:
539
+ for single_image_embeds in ip_adapter_image_embeds:
540
+ if do_classifier_free_guidance:
541
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
542
+ negative_image_embeds.append(single_negative_image_embeds)
543
+ image_embeds.append(single_image_embeds)
544
+
545
+ ip_adapter_image_embeds = []
546
+ for i, single_image_embeds in enumerate(image_embeds):
547
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
548
+ if do_classifier_free_guidance:
549
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
550
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
551
+
552
+ single_image_embeds = single_image_embeds.to(device=device)
553
+ ip_adapter_image_embeds.append(single_image_embeds)
554
+
555
+ return ip_adapter_image_embeds
556
+
557
+
558
+ def decode_latents(self, latents):
559
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
560
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
561
+
562
+ latents = 1 / self.vae.config.scaling_factor * latents
563
+ image = self.vae.decode(latents, return_dict=False)[0]
564
+ image = (image / 2 + 0.5).clamp(0, 1)
565
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
566
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
567
+ return image
568
+
569
+ def prepare_extra_step_kwargs(self, generator, eta):
570
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
571
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
572
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
573
+ # and should be between [0, 1]
574
+
575
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
576
+ extra_step_kwargs = {}
577
+ if accepts_eta:
578
+ extra_step_kwargs["eta"] = eta
579
+
580
+ # check if the scheduler accepts generator
581
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
582
+ if accepts_generator:
583
+ extra_step_kwargs["generator"] = generator
584
+ return extra_step_kwargs
585
+
586
+ def check_inputs(
587
+ self,
588
+ prompt,
589
+ height,
590
+ width,
591
+ callback_steps,
592
+ negative_prompt=None,
593
+ prompt_embeds=None,
594
+ negative_prompt_embeds=None,
595
+ ip_adapter_image=None,
596
+ ip_adapter_image_embeds=None,
597
+ callback_on_step_end_tensor_inputs=None,
598
+ ):
599
+ if height % 8 != 0 or width % 8 != 0:
600
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
601
+
602
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
603
+ raise ValueError(
604
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
605
+ f" {type(callback_steps)}."
606
+ )
607
+ if callback_on_step_end_tensor_inputs is not None and not all(
608
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
609
+ ):
610
+ raise ValueError(
611
+ 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]}"
612
+ )
613
+
614
+ if prompt is not None and prompt_embeds is not None:
615
+ raise ValueError(
616
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
617
+ " only forward one of the two."
618
+ )
619
+ elif prompt is None and prompt_embeds is None:
620
+ raise ValueError(
621
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
622
+ )
623
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
624
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
625
+
626
+ if negative_prompt is not None and negative_prompt_embeds is not None:
627
+ raise ValueError(
628
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
629
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
630
+ )
631
+
632
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
633
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
634
+ raise ValueError(
635
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
636
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
637
+ f" {negative_prompt_embeds.shape}."
638
+ )
639
+
640
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
641
+ raise ValueError(
642
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
643
+ )
644
+
645
+ if ip_adapter_image_embeds is not None:
646
+ if not isinstance(ip_adapter_image_embeds, list):
647
+ raise ValueError(
648
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
649
+ )
650
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
651
+ raise ValueError(
652
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
653
+ )
654
+
655
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
656
+ shape = (
657
+ batch_size,
658
+ num_channels_latents,
659
+ int(height) // self.vae_scale_factor,
660
+ int(width) // self.vae_scale_factor,
661
+ )
662
+ if isinstance(generator, list) and len(generator) != batch_size:
663
+ raise ValueError(
664
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
665
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
666
+ )
667
+
668
+ if latents is None:
669
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
670
+ else:
671
+ latents = latents.to(device)
672
+
673
+ # scale the initial noise by the standard deviation required by the scheduler
674
+ latents = latents * self.scheduler.init_noise_sigma
675
+ return latents
676
+
677
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
678
+ def get_guidance_scale_embedding(
679
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
680
+ ) -> torch.Tensor:
681
+ """
682
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
683
+
684
+ Args:
685
+ w (`torch.Tensor`):
686
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
687
+ embedding_dim (`int`, *optional*, defaults to 512):
688
+ Dimension of the embeddings to generate.
689
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
690
+ Data type of the generated embeddings.
691
+
692
+ Returns:
693
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
694
+ """
695
+ assert len(w.shape) == 1
696
+ w = w * 1000.0
697
+
698
+ half_dim = embedding_dim // 2
699
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
700
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
701
+ emb = w.to(dtype)[:, None] * emb[None, :]
702
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
703
+ if embedding_dim % 2 == 1: # zero pad
704
+ emb = torch.nn.functional.pad(emb, (0, 1))
705
+ assert emb.shape == (w.shape[0], embedding_dim)
706
+ return emb
707
+
708
+ @property
709
+ def guidance_scale(self):
710
+ return self._guidance_scale
711
+
712
+ @property
713
+ def guidance_rescale(self):
714
+ return self._guidance_rescale
715
+
716
+ @property
717
+ def clip_skip(self):
718
+ return self._clip_skip
719
+
720
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
721
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
722
+ # corresponds to doing no classifier free guidance.
723
+ @property
724
+ def do_classifier_free_guidance(self):
725
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
726
+
727
+ @property
728
+ def cross_attention_kwargs(self):
729
+ return self._cross_attention_kwargs
730
+
731
+ @property
732
+ def num_timesteps(self):
733
+ return self._num_timesteps
734
+
735
+ @property
736
+ def interrupt(self):
737
+ return self._interrupt
738
+
739
+ def decode_rgbd(self, latents,generator,output_type="np"):
740
+ dem_latents = latents[:,4:,:,:]
741
+ img_latents = latents[:,:4,:,:]
742
+ image = self.vae.decode(img_latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
743
+ 0
744
+ ]
745
+ dem = self.vae.decode(dem_latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
746
+ 0
747
+ ]
748
+ do_denormalize = [True] * image.shape[0]
749
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
750
+ dem = self.image_processor.postprocess(dem, output_type=output_type, do_denormalize=do_denormalize)
751
+ return image,dem
752
+
753
+ @torch.no_grad()
754
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
755
+ def __call__(
756
+ self,
757
+ prompt: Union[str, List[str]] = None,
758
+ height: Optional[int] = None,
759
+ width: Optional[int] = None,
760
+ num_inference_steps: int = 50,
761
+ timesteps: List[int] = None,
762
+ sigmas: List[float] = None,
763
+ guidance_scale: float = 7.5,
764
+ negative_prompt: Optional[Union[str, List[str]]] = None,
765
+ num_images_per_prompt: Optional[int] = 1,
766
+ eta: float = 0.0,
767
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
768
+ latents: Optional[torch.Tensor] = None,
769
+ prompt_embeds: Optional[torch.Tensor] = None,
770
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
771
+ ip_adapter_image: Optional[PipelineImageInput] = None,
772
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
773
+ output_type: Optional[str] = "np",
774
+ return_dict: bool = True,
775
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
776
+ guidance_rescale: float = 0.0,
777
+ clip_skip: Optional[int] = None,
778
+ callback_on_step_end: Optional[
779
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
780
+ ] = None,
781
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
782
+ **kwargs,
783
+ ):
784
+ r"""
785
+ The call function to the pipeline for generation.
786
+
787
+ Args:
788
+ prompt (`str` or `List[str]`, *optional*):
789
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
790
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
791
+ The height in pixels of the generated image.
792
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
793
+ The width in pixels of the generated image.
794
+ num_inference_steps (`int`, *optional*, defaults to 50):
795
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
796
+ expense of slower inference.
797
+ timesteps (`List[int]`, *optional*):
798
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
799
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
800
+ passed will be used. Must be in descending order.
801
+ sigmas (`List[float]`, *optional*):
802
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
803
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
804
+ will be used.
805
+ guidance_scale (`float`, *optional*, defaults to 7.5):
806
+ A higher guidance scale value encourages the model to generate images closely linked to the text
807
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
808
+ negative_prompt (`str` or `List[str]`, *optional*):
809
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
810
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
811
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
812
+ The number of images to generate per prompt.
813
+ eta (`float`, *optional*, defaults to 0.0):
814
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
815
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
816
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
817
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
818
+ generation deterministic.
819
+ latents (`torch.Tensor`, *optional*):
820
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
821
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
822
+ tensor is generated by sampling using the supplied random `generator`.
823
+ prompt_embeds (`torch.Tensor`, *optional*):
824
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
825
+ provided, text embeddings are generated from the `prompt` input argument.
826
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
827
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
828
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
829
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
830
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
831
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
832
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
833
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
834
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
835
+ output_type (`str`, *optional*, defaults to `"pil"`):
836
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
837
+ return_dict (`bool`, *optional*, defaults to `True`):
838
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
839
+ plain tuple.
840
+ cross_attention_kwargs (`dict`, *optional*):
841
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
842
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
843
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
844
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
845
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
846
+ using zero terminal SNR.
847
+ clip_skip (`int`, *optional*):
848
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
849
+ the output of the pre-final layer will be used for computing the prompt embeddings.
850
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
851
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
852
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
853
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
854
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
855
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
856
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
857
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
858
+ `._callback_tensor_inputs` attribute of your pipeline class.
859
+
860
+ Examples:
861
+
862
+ Returns:
863
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
864
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
865
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
866
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
867
+ "not-safe-for-work" (nsfw) content.
868
+ """
869
+
870
+ callback = kwargs.pop("callback", None)
871
+ callback_steps = kwargs.pop("callback_steps", None)
872
+
873
+ if callback is not None:
874
+ deprecate(
875
+ "callback",
876
+ "1.0.0",
877
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
878
+ )
879
+ if callback_steps is not None:
880
+ deprecate(
881
+ "callback_steps",
882
+ "1.0.0",
883
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
884
+ )
885
+
886
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
887
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
888
+
889
+ # 0. Default height and width to unet
890
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
891
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
892
+ # to deal with lora scaling and other possible forward hooks
893
+
894
+ # 1. Check inputs. Raise error if not correct
895
+ self.check_inputs(
896
+ prompt,
897
+ height,
898
+ width,
899
+ callback_steps,
900
+ negative_prompt,
901
+ prompt_embeds,
902
+ negative_prompt_embeds,
903
+ ip_adapter_image,
904
+ ip_adapter_image_embeds,
905
+ callback_on_step_end_tensor_inputs,
906
+ )
907
+
908
+ self._guidance_scale = guidance_scale
909
+ self._guidance_rescale = guidance_rescale
910
+ self._clip_skip = clip_skip
911
+ self._cross_attention_kwargs = cross_attention_kwargs
912
+ self._interrupt = False
913
+
914
+ # 2. Define call parameters
915
+ if prompt is not None and isinstance(prompt, str):
916
+ batch_size = 1
917
+ elif prompt is not None and isinstance(prompt, list):
918
+ batch_size = len(prompt)
919
+ else:
920
+ batch_size = prompt_embeds.shape[0]
921
+
922
+ device = self._execution_device
923
+
924
+ # 3. Encode input prompt
925
+ lora_scale = (
926
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
927
+ )
928
+
929
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
930
+ prompt,
931
+ device,
932
+ num_images_per_prompt,
933
+ self.do_classifier_free_guidance,
934
+ negative_prompt,
935
+ prompt_embeds=prompt_embeds,
936
+ negative_prompt_embeds=negative_prompt_embeds,
937
+ lora_scale=lora_scale,
938
+ clip_skip=self.clip_skip,
939
+ )
940
+
941
+ # For classifier free guidance, we need to do two forward passes.
942
+ # Here we concatenate the unconditional and text embeddings into a single batch
943
+ # to avoid doing two forward passes
944
+ if self.do_classifier_free_guidance:
945
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
946
+
947
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
948
+ image_embeds = self.prepare_ip_adapter_image_embeds(
949
+ ip_adapter_image,
950
+ ip_adapter_image_embeds,
951
+ device,
952
+ batch_size * num_images_per_prompt,
953
+ self.do_classifier_free_guidance,
954
+ )
955
+
956
+ # 4. Prepare timesteps
957
+ timesteps, num_inference_steps = retrieve_timesteps(
958
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
959
+ )
960
+
961
+ # 5. Prepare latent variables
962
+ num_channels_latents = self.unet.config.in_channels*2
963
+ latents = self.prepare_latents(
964
+ batch_size * num_images_per_prompt,
965
+ num_channels_latents,
966
+ height,
967
+ width,
968
+ prompt_embeds.dtype,
969
+ device,
970
+ generator,
971
+ latents,
972
+ )
973
+
974
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
975
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
976
+
977
+ # 6.1 Add image embeds for IP-Adapter
978
+ added_cond_kwargs = (
979
+ {"image_embeds": image_embeds}
980
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
981
+ else None
982
+ )
983
+
984
+ # 6.2 Optionally get Guidance Scale Embedding
985
+ timestep_cond = None
986
+ if self.unet.config.time_cond_proj_dim is not None:
987
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
988
+ timestep_cond = self.get_guidance_scale_embedding(
989
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
990
+ ).to(device=device, dtype=latents.dtype)
991
+
992
+ # 7. Denoising loop
993
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
994
+ self._num_timesteps = len(timesteps)
995
+ # intermediate_latents = []
996
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
997
+ for i, t in enumerate(timesteps):
998
+ if self.interrupt:
999
+ continue
1000
+
1001
+ # expand the latents if we are doing classifier free guidance
1002
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1003
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1004
+
1005
+ # predict the noise residual
1006
+ noise_pred = self.unet(
1007
+ latent_model_input,
1008
+ t,
1009
+ encoder_hidden_states=prompt_embeds,
1010
+ timestep_cond=timestep_cond,
1011
+ cross_attention_kwargs=self.cross_attention_kwargs,
1012
+ added_cond_kwargs=added_cond_kwargs,
1013
+ return_dict=False,
1014
+ )[0]
1015
+
1016
+ # perform guidance
1017
+ if self.do_classifier_free_guidance:
1018
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1019
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1020
+
1021
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1022
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1023
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1024
+
1025
+ # compute the previous noisy sample x_t -> x_t-1
1026
+ scheduler_output = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=True)
1027
+ latents = scheduler_output.prev_sample
1028
+ # if i % 10 == 0:
1029
+ # intermediate_latents.append(scheduler_output.pred_original_sample)
1030
+ if callback_on_step_end is not None:
1031
+ callback_kwargs = {}
1032
+ for k in callback_on_step_end_tensor_inputs:
1033
+ callback_kwargs[k] = locals()[k]
1034
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1035
+
1036
+ latents = callback_outputs.pop("latents", latents)
1037
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1038
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1039
+
1040
+ # call the callback, if provided
1041
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1042
+ progress_bar.update()
1043
+ if callback is not None and i % callback_steps == 0:
1044
+ step_idx = i // getattr(self.scheduler, "order", 1)
1045
+ callback(step_idx, t, latents)
1046
+
1047
+ if XLA_AVAILABLE:
1048
+ xm.mark_step()
1049
+
1050
+ image,dem = self.decode_rgbd(latents,generator,output_type)
1051
+
1052
+ # intermediate = [self.decode_rgbd(latent,generator,output_type)for latent in intermediate_latents]
1053
+
1054
+ # Offload all models
1055
+ self.maybe_free_model_hooks()
1056
+
1057
+ return image,dem
src/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import trimesh
3
+ import tempfile
4
+ import torch
5
+ from scipy.spatial import Delaunay
6
+ from .build_pipe import *
7
+
8
+ pipe = build_pipe()
9
+
10
+ def generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
11
+ """Generates terrain data (RGB and elevation) from a text prompt."""
12
+ if prefix and not prefix.endswith(' '):
13
+ prefix += ' ' # Ensure prefix ends with a space
14
+
15
+ full_prompt = prefix + prompt
16
+ generator = torch.Generator("cuda").manual_seed(seed)
17
+ image, dem = pipe(full_prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator)
18
+
19
+ # Center crop the image and dem
20
+ h, w, c = image[0].shape
21
+ start_h = (h - crop_size) // 2
22
+ start_w = (w - crop_size) // 2
23
+ end_h = start_h + crop_size
24
+ end_w = start_w + crop_size
25
+
26
+ cropped_image = image[0][start_h:end_h, start_w:end_w, :]
27
+ cropped_dem = dem[0][start_h:end_h, start_w:end_w, :]
28
+
29
+ return (255 * cropped_image).astype(np.uint8), 500*cropped_dem.mean(-1)
30
+
31
+ def simplify_mesh(mesh, target_face_count):
32
+ """Simplifies a mesh using quadric decimation."""
33
+ simplified_mesh = mesh.simplify_quadric_decimation(target_face_count)
34
+ return simplified_mesh
35
+
36
+ def create_3d_mesh(rgb, elevation):
37
+ """Creates a 3D mesh from RGB and elevation data."""
38
+ x, y = np.meshgrid(np.arange(elevation.shape[1]), np.arange(elevation.shape[0]))
39
+ points = np.stack([x.flatten(), y.flatten()], axis=-1)
40
+ tri = Delaunay(points)
41
+
42
+ vertices = np.stack([x.flatten(), y.flatten(), elevation.flatten()], axis=-1)
43
+ faces = tri.simplices
44
+
45
+ mesh = trimesh.Trimesh(vertices=vertices, faces=faces, vertex_colors=rgb.reshape(-1, 3))
46
+
47
+ #mesh = simplify_mesh(mesh, target_face_count=100)
48
+ return mesh
49
+
50
+ def generate_and_display(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix):
51
+ """Generates terrain and displays it as a 3D model."""
52
+ rgb, elevation = generate_terrain(prompt, num_inference_steps, guidance_scale, seed, crop_size, prefix)
53
+ mesh = create_3d_mesh(rgb, elevation)
54
+
55
+ with tempfile.NamedTemporaryFile(suffix=".obj", delete=False) as temp_file:
56
+ mesh.export(temp_file.name)
57
+ file_path = temp_file.name
58
+
59
+ return file_path