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lock,
|
5 |
+
SequentialPipelineBlocks,
|
6 |
+
PipelineState,
|
7 |
+
InputParam,
|
8 |
+
OutputParam,
|
9 |
+
ComponentSpec,
|
10 |
+
AutoPipelineBlocks
|
11 |
+
)
|
12 |
+
from diffusers.image_processor import VaeImageProcessor
|
13 |
+
from diffusers.schedulers import EulerDiscreteScheduler
|
14 |
+
from diffusers.models import AutoencoderKL
|
15 |
+
from diffusers.configuration_utils import FrozenDict
|
16 |
+
|
17 |
+
from diffusers.modular_pipelines.stable_diffusion_xl.before_denoise import prepare_latents_img2img
|
18 |
+
from diffusers.modular_pipelines.stable_diffusion_xl.denoise import (
|
19 |
+
StableDiffusionXLDenoiseLoopWrapper,
|
20 |
+
StableDiffusionXLDenoiseLoopDenoiser,
|
21 |
+
StableDiffusionXLControlNetDenoiseLoopDenoiser,
|
22 |
+
StableDiffusionXLDenoiseLoopAfterDenoiser
|
23 |
+
)
|
24 |
+
from diffusers.modular_pipelines.stable_diffusion_xl.modular_pipeline_block_mappings import (
|
25 |
+
IMAGE2IMAGE_BLOCKS,
|
26 |
+
TEXT2IMAGE_BLOCKS
|
27 |
+
)
|
28 |
+
|
29 |
+
import torch
|
30 |
+
from typing import List, Tuple, Any, Optional
|
31 |
+
|
32 |
+
class SDXLDiffDiffPrepareLatentsStep(PipelineBlock):
|
33 |
+
model_name = "stable-diffusion-xl"
|
34 |
+
|
35 |
+
@property
|
36 |
+
def description(self) -> str:
|
37 |
+
return (
|
38 |
+
"Step that prepares the latents for the differential diffusion generation process"
|
39 |
+
)
|
40 |
+
|
41 |
+
@property
|
42 |
+
def expected_components(self) -> List[ComponentSpec]:
|
43 |
+
return [
|
44 |
+
ComponentSpec("vae", AutoencoderKL),
|
45 |
+
ComponentSpec("scheduler", EulerDiscreteScheduler),
|
46 |
+
ComponentSpec(
|
47 |
+
"mask_processor",
|
48 |
+
VaeImageProcessor,
|
49 |
+
config=FrozenDict({"do_normalize": False, "do_convert_grayscale": True}),
|
50 |
+
default_creation_method="from_config",
|
51 |
+
)
|
52 |
+
]
|
53 |
+
|
54 |
+
@property
|
55 |
+
def inputs(self) -> List[Tuple[str, Any]]:
|
56 |
+
return [
|
57 |
+
InputParam("diffdiff_map",required=True),
|
58 |
+
InputParam(
|
59 |
+
"latents",
|
60 |
+
type_hint=Optional[torch.Tensor],
|
61 |
+
description="Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`."
|
62 |
+
),
|
63 |
+
InputParam(
|
64 |
+
"num_images_per_prompt",
|
65 |
+
default=1,
|
66 |
+
type_hint=int,
|
67 |
+
description="The number of images to generate per prompt"
|
68 |
+
),
|
69 |
+
InputParam(
|
70 |
+
"denoising_start",
|
71 |
+
type_hint=Optional[float],
|
72 |
+
description="When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be bypassed before it is initiated. The initial part of the denoising process is skipped and it is assumed that the passed `image` is a partly denoised image. Note that when this is specified, strength will be ignored. Useful for 'Mixture of Denoisers' multi-pipeline setups."
|
73 |
+
),
|
74 |
+
]
|
75 |
+
|
76 |
+
@property
|
77 |
+
def intermediates_inputs(self) -> List[InputParam]:
|
78 |
+
return [
|
79 |
+
InputParam("generator"),
|
80 |
+
InputParam("timesteps",type_hint=torch.Tensor, description="The timesteps to use for sampling. Can be generated in set_timesteps step."),
|
81 |
+
InputParam("image_latents", type_hint=torch.Tensor, description="The latents representing the reference image for image-to-image/inpainting generation. Can be generated in vae_encode step."),
|
82 |
+
InputParam("batch_size", type_hint=int, description="Number of prompts, the final batch size of model inputs should be batch_size * num_images_per_prompt. Can be generated in input step."),
|
83 |
+
InputParam("num_inference_steps", type_hint=int, description="The number of inference steps to use for the denoising process. Can be generated in set_timesteps step."),
|
84 |
+
]
|
85 |
+
|
86 |
+
@property
|
87 |
+
def intermediates_outputs(self) -> List[OutputParam]:
|
88 |
+
return [
|
89 |
+
OutputParam("latents", type_hint=torch.Tensor, description="The initial latents to use for the denoising process"),
|
90 |
+
OutputParam("original_latents", type_hint=torch.Tensor, description="The initial latents to use for the denoising process"),
|
91 |
+
OutputParam("diffdiff_masks", type_hint=torch.Tensor, description="The masks used for the differential diffusion denoising process"),
|
92 |
+
]
|
93 |
+
|
94 |
+
|
95 |
+
|
96 |
+
@torch.no_grad()
|
97 |
+
def __call__(self, components, state: PipelineState):
|
98 |
+
block_state = self.get_block_state(state)
|
99 |
+
|
100 |
+
block_state.dtype = components.vae.dtype
|
101 |
+
block_state.device = components._execution_device
|
102 |
+
|
103 |
+
block_state.add_noise = True if block_state.denoising_start is None else False
|
104 |
+
components.scheduler.set_begin_index(None)
|
105 |
+
|
106 |
+
if block_state.latents is None:
|
107 |
+
block_state.latents = prepare_latents_img2img(
|
108 |
+
components.vae,
|
109 |
+
components.scheduler,
|
110 |
+
block_state.image_latents,
|
111 |
+
block_state.timesteps,
|
112 |
+
block_state.batch_size,
|
113 |
+
block_state.num_images_per_prompt,
|
114 |
+
block_state.dtype,
|
115 |
+
block_state.device,
|
116 |
+
block_state.generator,
|
117 |
+
block_state.add_noise,
|
118 |
+
)
|
119 |
+
|
120 |
+
latent_height = block_state.image_latents.shape[-2]
|
121 |
+
latent_width = block_state.image_latents.shape[-1]
|
122 |
+
diffdiff_map = components.mask_processor.preprocess(block_state.diffdiff_map, height=latent_height, width=latent_width)
|
123 |
+
|
124 |
+
diffdiff_map = diffdiff_map.squeeze(0).to(block_state.device)
|
125 |
+
thresholds = torch.arange(block_state.num_inference_steps, dtype=diffdiff_map.dtype) / block_state.num_inference_steps
|
126 |
+
thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(block_state.device)
|
127 |
+
block_state.diffdiff_masks = diffdiff_map > (thresholds + (block_state.denoising_start or 0))
|
128 |
+
block_state.original_latents = block_state.latents
|
129 |
+
|
130 |
+
self.add_block_state(state, block_state)
|
131 |
+
|
132 |
+
return components, state
|
133 |
+
|
134 |
+
|
135 |
+
class SDXLDiffDiffDenoiseLoopBeforeDenoiser(PipelineBlock):
|
136 |
+
model_name = "stable-diffusion-xl"
|
137 |
+
|
138 |
+
@property
|
139 |
+
def description(self) -> str:
|
140 |
+
return (
|
141 |
+
"Step within the denoising loop for differential diffusion that prepare the latent input for the denoiser"
|
142 |
+
)
|
143 |
+
|
144 |
+
@property
|
145 |
+
def inputs(self) -> List[Tuple[str, Any]]:
|
146 |
+
return [
|
147 |
+
InputParam("denoising_start"),
|
148 |
+
]
|
149 |
+
|
150 |
+
@property
|
151 |
+
def intermediates_inputs(self) -> List[str]:
|
152 |
+
return [
|
153 |
+
InputParam(
|
154 |
+
"latents",
|
155 |
+
type_hint=torch.Tensor,
|
156 |
+
description="The initial latents to use for the denoising process. Can be generated in prepare_latent step."
|
157 |
+
),
|
158 |
+
InputParam(
|
159 |
+
"original_latents",
|
160 |
+
type_hint=torch.Tensor,
|
161 |
+
description="The initial latents to use for the denoising process. Can be generated in prepare_latent step."
|
162 |
+
),
|
163 |
+
InputParam(
|
164 |
+
"diffdiff_masks",
|
165 |
+
type_hint=torch.Tensor,
|
166 |
+
description="The masks used for the differential diffusion denoising process, can be generated in DiffDiffInput step."
|
167 |
+
),
|
168 |
+
]
|
169 |
+
|
170 |
+
@property
|
171 |
+
def intermediates_outputs(self) -> List[OutputParam]:
|
172 |
+
return [OutputParam("latents", type_hint=torch.Tensor, description="The denoised latents")]
|
173 |
+
|
174 |
+
@property
|
175 |
+
def expected_components(self) -> List[ComponentSpec]:
|
176 |
+
return [
|
177 |
+
ComponentSpec("scheduler", EulerDiscreteScheduler)
|
178 |
+
]
|
179 |
+
|
180 |
+
@torch.no_grad()
|
181 |
+
def __call__(self, components, block_state, i, t) -> PipelineState:
|
182 |
+
|
183 |
+
# diff diff
|
184 |
+
if i == 0 and block_state.denoising_start is None:
|
185 |
+
block_state.latents = block_state.original_latents[:1]
|
186 |
+
else:
|
187 |
+
block_state.mask = block_state.diffdiff_masks[i].unsqueeze(0)
|
188 |
+
# cast mask to the same type as latents etc
|
189 |
+
block_state.mask = block_state.mask.to(block_state.latents.dtype)
|
190 |
+
block_state.mask = block_state.mask.unsqueeze(1) # fit shape
|
191 |
+
block_state.latents = block_state.original_latents[i] * block_state.mask + block_state.latents * (1 - block_state.mask)
|
192 |
+
# end diff diff
|
193 |
+
|
194 |
+
# expand the latents if we are doing classifier free guidance
|
195 |
+
block_state.scaled_latents = components.scheduler.scale_model_input(block_state.latents, t)
|
196 |
+
|
197 |
+
return components, block_state
|
198 |
+
|
199 |
+
|
200 |
+
class SDXLDiffDiffDenoiseLoop(StableDiffusionXLDenoiseLoopWrapper):
|
201 |
+
block_classes = [SDXLDiffDiffDenoiseLoopBeforeDenoiser, StableDiffusionXLDenoiseLoopDenoiser, StableDiffusionXLDenoiseLoopAfterDenoiser]
|
202 |
+
block_names = ["before_denoiser", "denoiser", "after_denoiser"]
|
203 |
+
|
204 |
+
# control_cond
|
205 |
+
class SDXLDiffDiffControlNetDenoiseLoop(StableDiffusionXLDenoiseLoopWrapper):
|
206 |
+
block_classes = [SDXLDiffDiffDenoiseLoopBeforeDenoiser, StableDiffusionXLControlNetDenoiseLoopDenoiser, StableDiffusionXLDenoiseLoopAfterDenoiser]
|
207 |
+
block_names = ["before_denoiser", "denoiser", "after_denoiser"]
|
208 |
+
|
209 |
+
class SDXLDiffDiffDenoiseStep(AutoPipelineBlocks):
|
210 |
+
block_classes = [SDXLDiffDiffControlNetDenoiseLoop, SDXLDiffDiffDenoiseLoop]
|
211 |
+
block_names = ["controlnet_denoise", "denoise"]
|
212 |
+
block_trigger_inputs = ["controlnet_cond", None]
|
213 |
+
|
214 |
+
|
215 |
+
DIFFDIFF_BLOCKS = IMAGE2IMAGE_BLOCKS.copy()
|
216 |
+
DIFFDIFF_BLOCKS["denoise"] = SDXLDiffDiffDenoiseStep
|
217 |
+
DIFFDIFF_BLOCKS["prepare_latents"] = SDXLDiffDiffPrepareLatentsStep
|
218 |
+
DIFFDIFF_BLOCKS["set_timesteps"] = TEXT2IMAGE_BLOCKS["set_timesteps"]
|
219 |
+
|
220 |
+
|
221 |
+
class DiffDiffBlocks(SequentialPipelineBlocks):
|
222 |
+
block_classes = list(DIFFDIFF_BLOCKS.values())
|
223 |
+
block_names = list(DIFFDIFF_BLOCKS.keys())
|
224 |
+
|