diffusers 0.23.1__py3-none-any.whl → 0.24.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +16 -2
- diffusers/configuration_utils.py +1 -0
- diffusers/dependency_versions_check.py +0 -1
- diffusers/dependency_versions_table.py +4 -5
- diffusers/image_processor.py +186 -14
- diffusers/loaders/__init__.py +82 -0
- diffusers/loaders/ip_adapter.py +157 -0
- diffusers/loaders/lora.py +1415 -0
- diffusers/loaders/lora_conversion_utils.py +284 -0
- diffusers/loaders/single_file.py +631 -0
- diffusers/loaders/textual_inversion.py +459 -0
- diffusers/loaders/unet.py +735 -0
- diffusers/loaders/utils.py +59 -0
- diffusers/models/__init__.py +12 -1
- diffusers/models/attention.py +165 -14
- diffusers/models/attention_flax.py +9 -1
- diffusers/models/attention_processor.py +286 -1
- diffusers/models/autoencoder_asym_kl.py +14 -9
- diffusers/models/autoencoder_kl.py +3 -18
- diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
- diffusers/models/autoencoder_tiny.py +20 -24
- diffusers/models/consistency_decoder_vae.py +37 -30
- diffusers/models/controlnet.py +59 -39
- diffusers/models/controlnet_flax.py +19 -18
- diffusers/models/embeddings_flax.py +2 -0
- diffusers/models/lora.py +131 -1
- diffusers/models/modeling_flax_utils.py +2 -1
- diffusers/models/modeling_outputs.py +17 -0
- diffusers/models/modeling_utils.py +27 -19
- diffusers/models/normalization.py +2 -2
- diffusers/models/resnet.py +390 -59
- diffusers/models/transformer_2d.py +20 -3
- diffusers/models/transformer_temporal.py +183 -1
- diffusers/models/unet_2d_blocks_flax.py +5 -0
- diffusers/models/unet_2d_condition.py +9 -0
- diffusers/models/unet_2d_condition_flax.py +13 -13
- diffusers/models/unet_3d_blocks.py +957 -173
- diffusers/models/unet_3d_condition.py +16 -8
- diffusers/models/unet_kandi3.py +589 -0
- diffusers/models/unet_motion_model.py +48 -33
- diffusers/models/unet_spatio_temporal_condition.py +489 -0
- diffusers/models/vae.py +63 -13
- diffusers/models/vae_flax.py +7 -0
- diffusers/models/vq_model.py +3 -1
- diffusers/optimization.py +16 -9
- diffusers/pipelines/__init__.py +65 -12
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
- diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
- diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
- diffusers/pipelines/auto_pipeline.py +6 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
- diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
- diffusers/pipelines/dit/pipeline_dit.py +1 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
- diffusers/pipelines/kandinsky3/__init__.py +49 -0
- diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
- diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
- diffusers/pipelines/pipeline_flax_utils.py +4 -2
- diffusers/pipelines/pipeline_utils.py +33 -13
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
- diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
- diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
- diffusers/pipelines/stable_diffusion/__init__.py +64 -21
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
- diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
- diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
- diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
- diffusers/schedulers/__init__.py +2 -4
- diffusers/schedulers/deprecated/__init__.py +50 -0
- diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
- diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
- diffusers/schedulers/scheduling_ddim.py +1 -3
- diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
- diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
- diffusers/schedulers/scheduling_ddpm.py +1 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
- diffusers/schedulers/scheduling_deis_multistep.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
- diffusers/schedulers/scheduling_euler_discrete.py +40 -13
- diffusers/schedulers/scheduling_heun_discrete.py +15 -5
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
- diffusers/schedulers/scheduling_lcm.py +123 -29
- diffusers/schedulers/scheduling_lms_discrete.py +1 -3
- diffusers/schedulers/scheduling_pndm.py +1 -3
- diffusers/schedulers/scheduling_repaint.py +1 -3
- diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
- diffusers/utils/__init__.py +1 -0
- diffusers/utils/constants.py +8 -7
- diffusers/utils/dummy_pt_objects.py +45 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
- diffusers/utils/dynamic_modules_utils.py +4 -4
- diffusers/utils/export_utils.py +8 -3
- diffusers/utils/logging.py +10 -10
- diffusers/utils/outputs.py +5 -5
- diffusers/utils/peft_utils.py +88 -44
- diffusers/utils/torch_utils.py +2 -2
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
- diffusers/loaders.py +0 -3336
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,460 @@
|
|
1
|
+
import inspect
|
2
|
+
from typing import Callable, List, Optional, Union
|
3
|
+
|
4
|
+
import numpy as np
|
5
|
+
import PIL
|
6
|
+
import PIL.Image
|
7
|
+
import torch
|
8
|
+
from transformers import T5EncoderModel, T5Tokenizer
|
9
|
+
|
10
|
+
from ...loaders import LoraLoaderMixin
|
11
|
+
from ...models import Kandinsky3UNet, VQModel
|
12
|
+
from ...schedulers import DDPMScheduler
|
13
|
+
from ...utils import (
|
14
|
+
is_accelerate_available,
|
15
|
+
logging,
|
16
|
+
)
|
17
|
+
from ...utils.torch_utils import randn_tensor
|
18
|
+
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
19
|
+
|
20
|
+
|
21
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
22
|
+
|
23
|
+
|
24
|
+
def downscale_height_and_width(height, width, scale_factor=8):
|
25
|
+
new_height = height // scale_factor**2
|
26
|
+
if height % scale_factor**2 != 0:
|
27
|
+
new_height += 1
|
28
|
+
new_width = width // scale_factor**2
|
29
|
+
if width % scale_factor**2 != 0:
|
30
|
+
new_width += 1
|
31
|
+
return new_height * scale_factor, new_width * scale_factor
|
32
|
+
|
33
|
+
|
34
|
+
def prepare_image(pil_image):
|
35
|
+
arr = np.array(pil_image.convert("RGB"))
|
36
|
+
arr = arr.astype(np.float32) / 127.5 - 1
|
37
|
+
arr = np.transpose(arr, [2, 0, 1])
|
38
|
+
image = torch.from_numpy(arr).unsqueeze(0)
|
39
|
+
return image
|
40
|
+
|
41
|
+
|
42
|
+
class Kandinsky3Img2ImgPipeline(DiffusionPipeline, LoraLoaderMixin):
|
43
|
+
model_cpu_offload_seq = "text_encoder->unet->movq"
|
44
|
+
|
45
|
+
def __init__(
|
46
|
+
self,
|
47
|
+
tokenizer: T5Tokenizer,
|
48
|
+
text_encoder: T5EncoderModel,
|
49
|
+
unet: Kandinsky3UNet,
|
50
|
+
scheduler: DDPMScheduler,
|
51
|
+
movq: VQModel,
|
52
|
+
):
|
53
|
+
super().__init__()
|
54
|
+
|
55
|
+
self.register_modules(
|
56
|
+
tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
|
57
|
+
)
|
58
|
+
|
59
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
60
|
+
# get the original timestep using init_timestep
|
61
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
62
|
+
|
63
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
64
|
+
timesteps = self.scheduler.timesteps[t_start:]
|
65
|
+
|
66
|
+
return timesteps, num_inference_steps - t_start
|
67
|
+
|
68
|
+
def remove_all_hooks(self):
|
69
|
+
if is_accelerate_available():
|
70
|
+
from accelerate.hooks import remove_hook_from_module
|
71
|
+
else:
|
72
|
+
raise ImportError("Please install accelerate via `pip install accelerate`")
|
73
|
+
|
74
|
+
for model in [self.text_encoder, self.unet]:
|
75
|
+
if model is not None:
|
76
|
+
remove_hook_from_module(model, recurse=True)
|
77
|
+
|
78
|
+
self.unet_offload_hook = None
|
79
|
+
self.text_encoder_offload_hook = None
|
80
|
+
self.final_offload_hook = None
|
81
|
+
|
82
|
+
def _process_embeds(self, embeddings, attention_mask, cut_context):
|
83
|
+
# return embeddings, attention_mask
|
84
|
+
if cut_context:
|
85
|
+
embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
|
86
|
+
max_seq_length = attention_mask.sum(-1).max() + 1
|
87
|
+
embeddings = embeddings[:, :max_seq_length]
|
88
|
+
attention_mask = attention_mask[:, :max_seq_length]
|
89
|
+
return embeddings, attention_mask
|
90
|
+
|
91
|
+
@torch.no_grad()
|
92
|
+
def encode_prompt(
|
93
|
+
self,
|
94
|
+
prompt,
|
95
|
+
do_classifier_free_guidance=True,
|
96
|
+
num_images_per_prompt=1,
|
97
|
+
device=None,
|
98
|
+
negative_prompt=None,
|
99
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
100
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
101
|
+
_cut_context=False,
|
102
|
+
):
|
103
|
+
r"""
|
104
|
+
Encodes the prompt into text encoder hidden states.
|
105
|
+
|
106
|
+
Args:
|
107
|
+
prompt (`str` or `List[str]`, *optional*):
|
108
|
+
prompt to be encoded
|
109
|
+
device: (`torch.device`, *optional*):
|
110
|
+
torch device to place the resulting embeddings on
|
111
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
112
|
+
number of images that should be generated per prompt
|
113
|
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
114
|
+
whether to use classifier free guidance or not
|
115
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
116
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
117
|
+
`negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
|
118
|
+
Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
|
119
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
120
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
121
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
122
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
123
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
124
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
125
|
+
argument.
|
126
|
+
"""
|
127
|
+
if prompt is not None and negative_prompt is not None:
|
128
|
+
if type(prompt) is not type(negative_prompt):
|
129
|
+
raise TypeError(
|
130
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
131
|
+
f" {type(prompt)}."
|
132
|
+
)
|
133
|
+
|
134
|
+
if device is None:
|
135
|
+
device = self._execution_device
|
136
|
+
|
137
|
+
if prompt is not None and isinstance(prompt, str):
|
138
|
+
batch_size = 1
|
139
|
+
elif prompt is not None and isinstance(prompt, list):
|
140
|
+
batch_size = len(prompt)
|
141
|
+
else:
|
142
|
+
batch_size = prompt_embeds.shape[0]
|
143
|
+
|
144
|
+
max_length = 128
|
145
|
+
|
146
|
+
if prompt_embeds is None:
|
147
|
+
text_inputs = self.tokenizer(
|
148
|
+
prompt,
|
149
|
+
padding="max_length",
|
150
|
+
max_length=max_length,
|
151
|
+
truncation=True,
|
152
|
+
return_tensors="pt",
|
153
|
+
)
|
154
|
+
text_input_ids = text_inputs.input_ids.to(device)
|
155
|
+
attention_mask = text_inputs.attention_mask.to(device)
|
156
|
+
prompt_embeds = self.text_encoder(
|
157
|
+
text_input_ids,
|
158
|
+
attention_mask=attention_mask,
|
159
|
+
)
|
160
|
+
prompt_embeds = prompt_embeds[0]
|
161
|
+
prompt_embeds, attention_mask = self._process_embeds(prompt_embeds, attention_mask, _cut_context)
|
162
|
+
prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
|
163
|
+
|
164
|
+
if self.text_encoder is not None:
|
165
|
+
dtype = self.text_encoder.dtype
|
166
|
+
else:
|
167
|
+
dtype = None
|
168
|
+
|
169
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
170
|
+
|
171
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
172
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
173
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
174
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
175
|
+
attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
|
176
|
+
# get unconditional embeddings for classifier free guidance
|
177
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
178
|
+
uncond_tokens: List[str]
|
179
|
+
|
180
|
+
if negative_prompt is None:
|
181
|
+
uncond_tokens = [""] * batch_size
|
182
|
+
elif isinstance(negative_prompt, str):
|
183
|
+
uncond_tokens = [negative_prompt]
|
184
|
+
elif batch_size != len(negative_prompt):
|
185
|
+
raise ValueError(
|
186
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
187
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
188
|
+
" the batch size of `prompt`."
|
189
|
+
)
|
190
|
+
else:
|
191
|
+
uncond_tokens = negative_prompt
|
192
|
+
if negative_prompt is not None:
|
193
|
+
uncond_input = self.tokenizer(
|
194
|
+
uncond_tokens,
|
195
|
+
padding="max_length",
|
196
|
+
max_length=128,
|
197
|
+
truncation=True,
|
198
|
+
return_attention_mask=True,
|
199
|
+
return_tensors="pt",
|
200
|
+
)
|
201
|
+
text_input_ids = uncond_input.input_ids.to(device)
|
202
|
+
negative_attention_mask = uncond_input.attention_mask.to(device)
|
203
|
+
|
204
|
+
negative_prompt_embeds = self.text_encoder(
|
205
|
+
text_input_ids,
|
206
|
+
attention_mask=negative_attention_mask,
|
207
|
+
)
|
208
|
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
209
|
+
negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
|
210
|
+
negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
|
211
|
+
negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
|
212
|
+
|
213
|
+
else:
|
214
|
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
215
|
+
negative_attention_mask = torch.zeros_like(attention_mask)
|
216
|
+
|
217
|
+
if do_classifier_free_guidance:
|
218
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
219
|
+
seq_len = negative_prompt_embeds.shape[1]
|
220
|
+
|
221
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
|
222
|
+
if negative_prompt_embeds.shape != prompt_embeds.shape:
|
223
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
224
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
225
|
+
negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
|
226
|
+
|
227
|
+
# For classifier free guidance, we need to do two forward passes.
|
228
|
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
229
|
+
# to avoid doing two forward passes
|
230
|
+
else:
|
231
|
+
negative_prompt_embeds = None
|
232
|
+
negative_attention_mask = None
|
233
|
+
return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
|
234
|
+
|
235
|
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
|
236
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
237
|
+
raise ValueError(
|
238
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
239
|
+
)
|
240
|
+
|
241
|
+
image = image.to(device=device, dtype=dtype)
|
242
|
+
|
243
|
+
batch_size = batch_size * num_images_per_prompt
|
244
|
+
|
245
|
+
if image.shape[1] == 4:
|
246
|
+
init_latents = image
|
247
|
+
|
248
|
+
else:
|
249
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
250
|
+
raise ValueError(
|
251
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
252
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
253
|
+
)
|
254
|
+
|
255
|
+
elif isinstance(generator, list):
|
256
|
+
init_latents = [
|
257
|
+
self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
|
258
|
+
]
|
259
|
+
init_latents = torch.cat(init_latents, dim=0)
|
260
|
+
else:
|
261
|
+
init_latents = self.movq.encode(image).latent_dist.sample(generator)
|
262
|
+
|
263
|
+
init_latents = self.movq.config.scaling_factor * init_latents
|
264
|
+
|
265
|
+
init_latents = torch.cat([init_latents], dim=0)
|
266
|
+
|
267
|
+
shape = init_latents.shape
|
268
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
269
|
+
|
270
|
+
# get latents
|
271
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
272
|
+
|
273
|
+
latents = init_latents
|
274
|
+
|
275
|
+
return latents
|
276
|
+
|
277
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
278
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
279
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
280
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
281
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
282
|
+
# and should be between [0, 1]
|
283
|
+
|
284
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
285
|
+
extra_step_kwargs = {}
|
286
|
+
if accepts_eta:
|
287
|
+
extra_step_kwargs["eta"] = eta
|
288
|
+
|
289
|
+
# check if the scheduler accepts generator
|
290
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
291
|
+
if accepts_generator:
|
292
|
+
extra_step_kwargs["generator"] = generator
|
293
|
+
return extra_step_kwargs
|
294
|
+
|
295
|
+
def check_inputs(
|
296
|
+
self,
|
297
|
+
prompt,
|
298
|
+
callback_steps,
|
299
|
+
negative_prompt=None,
|
300
|
+
prompt_embeds=None,
|
301
|
+
negative_prompt_embeds=None,
|
302
|
+
):
|
303
|
+
if (callback_steps is None) or (
|
304
|
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
305
|
+
):
|
306
|
+
raise ValueError(
|
307
|
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
308
|
+
f" {type(callback_steps)}."
|
309
|
+
)
|
310
|
+
|
311
|
+
if prompt is not None and prompt_embeds is not None:
|
312
|
+
raise ValueError(
|
313
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
314
|
+
" only forward one of the two."
|
315
|
+
)
|
316
|
+
elif prompt is None and prompt_embeds is None:
|
317
|
+
raise ValueError(
|
318
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
319
|
+
)
|
320
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
321
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
322
|
+
|
323
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
324
|
+
raise ValueError(
|
325
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
326
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
327
|
+
)
|
328
|
+
|
329
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
330
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
331
|
+
raise ValueError(
|
332
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
333
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
334
|
+
f" {negative_prompt_embeds.shape}."
|
335
|
+
)
|
336
|
+
|
337
|
+
@torch.no_grad()
|
338
|
+
def __call__(
|
339
|
+
self,
|
340
|
+
prompt: Union[str, List[str]] = None,
|
341
|
+
image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] = None,
|
342
|
+
strength: float = 0.3,
|
343
|
+
num_inference_steps: int = 25,
|
344
|
+
guidance_scale: float = 3.0,
|
345
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
346
|
+
num_images_per_prompt: Optional[int] = 1,
|
347
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
348
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
349
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
350
|
+
output_type: Optional[str] = "pil",
|
351
|
+
return_dict: bool = True,
|
352
|
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
353
|
+
callback_steps: int = 1,
|
354
|
+
latents=None,
|
355
|
+
):
|
356
|
+
cut_context = True
|
357
|
+
# 1. Check inputs. Raise error if not correct
|
358
|
+
self.check_inputs(prompt, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
|
359
|
+
|
360
|
+
if prompt is not None and isinstance(prompt, str):
|
361
|
+
batch_size = 1
|
362
|
+
elif prompt is not None and isinstance(prompt, list):
|
363
|
+
batch_size = len(prompt)
|
364
|
+
else:
|
365
|
+
batch_size = prompt_embeds.shape[0]
|
366
|
+
|
367
|
+
device = self._execution_device
|
368
|
+
|
369
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
370
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
371
|
+
# corresponds to doing no classifier free guidance.
|
372
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
373
|
+
|
374
|
+
# 3. Encode input prompt
|
375
|
+
prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
|
376
|
+
prompt,
|
377
|
+
do_classifier_free_guidance,
|
378
|
+
num_images_per_prompt=num_images_per_prompt,
|
379
|
+
device=device,
|
380
|
+
negative_prompt=negative_prompt,
|
381
|
+
prompt_embeds=prompt_embeds,
|
382
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
383
|
+
_cut_context=cut_context,
|
384
|
+
)
|
385
|
+
|
386
|
+
if do_classifier_free_guidance:
|
387
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
388
|
+
attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
|
389
|
+
if not isinstance(image, list):
|
390
|
+
image = [image]
|
391
|
+
if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image):
|
392
|
+
raise ValueError(
|
393
|
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor"
|
394
|
+
)
|
395
|
+
|
396
|
+
image = torch.cat([prepare_image(i) for i in image], dim=0)
|
397
|
+
image = image.to(dtype=prompt_embeds.dtype, device=device)
|
398
|
+
# 4. Prepare timesteps
|
399
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
400
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
401
|
+
# 5. Prepare latents
|
402
|
+
latents = self.movq.encode(image)["latents"]
|
403
|
+
latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
|
404
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
405
|
+
latents = self.prepare_latents(
|
406
|
+
latents, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
|
407
|
+
)
|
408
|
+
if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
|
409
|
+
self.text_encoder_offload_hook.offload()
|
410
|
+
|
411
|
+
# 7. Denoising loop
|
412
|
+
# TODO(Yiyi): Correct the following line and use correctly
|
413
|
+
# num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
414
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
415
|
+
for i, t in enumerate(timesteps):
|
416
|
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
417
|
+
|
418
|
+
# predict the noise residual
|
419
|
+
noise_pred = self.unet(
|
420
|
+
latent_model_input,
|
421
|
+
t,
|
422
|
+
encoder_hidden_states=prompt_embeds,
|
423
|
+
encoder_attention_mask=attention_mask,
|
424
|
+
)[0]
|
425
|
+
if do_classifier_free_guidance:
|
426
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
427
|
+
|
428
|
+
noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
|
429
|
+
|
430
|
+
# compute the previous noisy sample x_t -> x_t-1
|
431
|
+
latents = self.scheduler.step(
|
432
|
+
noise_pred,
|
433
|
+
t,
|
434
|
+
latents,
|
435
|
+
generator=generator,
|
436
|
+
).prev_sample
|
437
|
+
progress_bar.update()
|
438
|
+
if callback is not None and i % callback_steps == 0:
|
439
|
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
440
|
+
callback(step_idx, t, latents)
|
441
|
+
# post-processing
|
442
|
+
image = self.movq.decode(latents, force_not_quantize=True)["sample"]
|
443
|
+
|
444
|
+
if output_type not in ["pt", "np", "pil"]:
|
445
|
+
raise ValueError(
|
446
|
+
f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"
|
447
|
+
)
|
448
|
+
|
449
|
+
if output_type in ["np", "pil"]:
|
450
|
+
image = image * 0.5 + 0.5
|
451
|
+
image = image.clamp(0, 1)
|
452
|
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
453
|
+
|
454
|
+
if output_type == "pil":
|
455
|
+
image = self.numpy_to_pil(image)
|
456
|
+
|
457
|
+
if not return_dict:
|
458
|
+
return (image,)
|
459
|
+
|
460
|
+
return ImagePipelineOutput(images=image)
|
@@ -44,15 +44,64 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
|
44
44
|
|
45
45
|
|
46
46
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
47
|
-
def retrieve_latents(
|
48
|
-
|
47
|
+
def retrieve_latents(
|
48
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
49
|
+
):
|
50
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
49
51
|
return encoder_output.latent_dist.sample(generator)
|
52
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
53
|
+
return encoder_output.latent_dist.mode()
|
50
54
|
elif hasattr(encoder_output, "latents"):
|
51
55
|
return encoder_output.latents
|
52
56
|
else:
|
53
57
|
raise AttributeError("Could not access latents of provided encoder_output")
|
54
58
|
|
55
59
|
|
60
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
61
|
+
def retrieve_timesteps(
|
62
|
+
scheduler,
|
63
|
+
num_inference_steps: Optional[int] = None,
|
64
|
+
device: Optional[Union[str, torch.device]] = None,
|
65
|
+
timesteps: Optional[List[int]] = None,
|
66
|
+
**kwargs,
|
67
|
+
):
|
68
|
+
"""
|
69
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
70
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
71
|
+
|
72
|
+
Args:
|
73
|
+
scheduler (`SchedulerMixin`):
|
74
|
+
The scheduler to get timesteps from.
|
75
|
+
num_inference_steps (`int`):
|
76
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
77
|
+
`timesteps` must be `None`.
|
78
|
+
device (`str` or `torch.device`, *optional*):
|
79
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
80
|
+
timesteps (`List[int]`, *optional*):
|
81
|
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
82
|
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
83
|
+
must be `None`.
|
84
|
+
|
85
|
+
Returns:
|
86
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
87
|
+
second element is the number of inference steps.
|
88
|
+
"""
|
89
|
+
if timesteps is not None:
|
90
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
91
|
+
if not accepts_timesteps:
|
92
|
+
raise ValueError(
|
93
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
94
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
95
|
+
)
|
96
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
97
|
+
timesteps = scheduler.timesteps
|
98
|
+
num_inference_steps = len(timesteps)
|
99
|
+
else:
|
100
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
101
|
+
timesteps = scheduler.timesteps
|
102
|
+
return timesteps, num_inference_steps
|
103
|
+
|
104
|
+
|
56
105
|
EXAMPLE_DOC_STRING = """
|
57
106
|
Examples:
|
58
107
|
```py
|
@@ -115,6 +164,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
115
164
|
requires_safety_checker (`bool`, *optional*, defaults to `True`):
|
116
165
|
Whether the pipeline requires a safety checker component.
|
117
166
|
"""
|
167
|
+
|
118
168
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
119
169
|
_optional_components = ["safety_checker", "feature_extractor"]
|
120
170
|
_exclude_from_cpu_offload = ["safety_checker"]
|
@@ -591,6 +641,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
591
641
|
num_inference_steps: int = 4,
|
592
642
|
strength: float = 0.8,
|
593
643
|
original_inference_steps: int = None,
|
644
|
+
timesteps: List[int] = None,
|
594
645
|
guidance_scale: float = 8.5,
|
595
646
|
num_images_per_prompt: Optional[int] = 1,
|
596
647
|
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
@@ -622,6 +673,10 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
622
673
|
we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule,
|
623
674
|
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
|
624
675
|
scheduler's `original_inference_steps` attribute.
|
676
|
+
timesteps (`List[int]`, *optional*):
|
677
|
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
678
|
+
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
|
679
|
+
order.
|
625
680
|
guidance_scale (`float`, *optional*, defaults to 7.5):
|
626
681
|
A higher guidance scale value encourages the model to generate images closely linked to the text
|
627
682
|
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
@@ -659,7 +714,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
659
714
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
660
715
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
661
716
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
662
|
-
`._callback_tensor_inputs` attribute of your
|
717
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
663
718
|
|
664
719
|
Examples:
|
665
720
|
|
@@ -727,10 +782,14 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
727
782
|
image = self.image_processor.preprocess(image)
|
728
783
|
|
729
784
|
# 5. Prepare timesteps
|
730
|
-
|
731
|
-
|
785
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
786
|
+
self.scheduler,
|
787
|
+
num_inference_steps,
|
788
|
+
device,
|
789
|
+
timesteps,
|
790
|
+
original_inference_steps=original_inference_steps,
|
791
|
+
strength=strength,
|
732
792
|
)
|
733
|
-
timesteps = self.scheduler.timesteps
|
734
793
|
|
735
794
|
# 6. Prepare latent variables
|
736
795
|
original_inference_steps = (
|
@@ -61,6 +61,51 @@ EXAMPLE_DOC_STRING = """
|
|
61
61
|
"""
|
62
62
|
|
63
63
|
|
64
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
65
|
+
def retrieve_timesteps(
|
66
|
+
scheduler,
|
67
|
+
num_inference_steps: Optional[int] = None,
|
68
|
+
device: Optional[Union[str, torch.device]] = None,
|
69
|
+
timesteps: Optional[List[int]] = None,
|
70
|
+
**kwargs,
|
71
|
+
):
|
72
|
+
"""
|
73
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
74
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
75
|
+
|
76
|
+
Args:
|
77
|
+
scheduler (`SchedulerMixin`):
|
78
|
+
The scheduler to get timesteps from.
|
79
|
+
num_inference_steps (`int`):
|
80
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
81
|
+
`timesteps` must be `None`.
|
82
|
+
device (`str` or `torch.device`, *optional*):
|
83
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
84
|
+
timesteps (`List[int]`, *optional*):
|
85
|
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
86
|
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
87
|
+
must be `None`.
|
88
|
+
|
89
|
+
Returns:
|
90
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
91
|
+
second element is the number of inference steps.
|
92
|
+
"""
|
93
|
+
if timesteps is not None:
|
94
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
95
|
+
if not accepts_timesteps:
|
96
|
+
raise ValueError(
|
97
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
98
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
99
|
+
)
|
100
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
101
|
+
timesteps = scheduler.timesteps
|
102
|
+
num_inference_steps = len(timesteps)
|
103
|
+
else:
|
104
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
105
|
+
timesteps = scheduler.timesteps
|
106
|
+
return timesteps, num_inference_steps
|
107
|
+
|
108
|
+
|
64
109
|
class LatentConsistencyModelPipeline(
|
65
110
|
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
66
111
|
):
|
@@ -97,6 +142,7 @@ class LatentConsistencyModelPipeline(
|
|
97
142
|
requires_safety_checker (`bool`, *optional*, defaults to `True`):
|
98
143
|
Whether the pipeline requires a safety checker component.
|
99
144
|
"""
|
145
|
+
|
100
146
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
101
147
|
_optional_components = ["safety_checker", "feature_extractor"]
|
102
148
|
_exclude_from_cpu_offload = ["safety_checker"]
|
@@ -529,6 +575,7 @@ class LatentConsistencyModelPipeline(
|
|
529
575
|
width: Optional[int] = None,
|
530
576
|
num_inference_steps: int = 4,
|
531
577
|
original_inference_steps: int = None,
|
578
|
+
timesteps: List[int] = None,
|
532
579
|
guidance_scale: float = 8.5,
|
533
580
|
num_images_per_prompt: Optional[int] = 1,
|
534
581
|
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
@@ -560,6 +607,10 @@ class LatentConsistencyModelPipeline(
|
|
560
607
|
we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule,
|
561
608
|
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
|
562
609
|
scheduler's `original_inference_steps` attribute.
|
610
|
+
timesteps (`List[int]`, *optional*):
|
611
|
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
612
|
+
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
|
613
|
+
order.
|
563
614
|
guidance_scale (`float`, *optional*, defaults to 7.5):
|
564
615
|
A higher guidance scale value encourages the model to generate images closely linked to the text
|
565
616
|
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
@@ -597,7 +648,7 @@ class LatentConsistencyModelPipeline(
|
|
597
648
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
598
649
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
599
650
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
600
|
-
`._callback_tensor_inputs` attribute of your
|
651
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
601
652
|
|
602
653
|
Examples:
|
603
654
|
|
@@ -667,8 +718,9 @@ class LatentConsistencyModelPipeline(
|
|
667
718
|
)
|
668
719
|
|
669
720
|
# 4. Prepare timesteps
|
670
|
-
|
671
|
-
|
721
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
722
|
+
self.scheduler, num_inference_steps, device, timesteps, original_inference_steps=original_inference_steps
|
723
|
+
)
|
672
724
|
|
673
725
|
# 5. Prepare latent variable
|
674
726
|
num_channels_latents = self.unet.config.in_channels
|
@@ -49,6 +49,7 @@ class LDMTextToImagePipeline(DiffusionPipeline):
|
|
49
49
|
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
50
50
|
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
51
51
|
"""
|
52
|
+
|
52
53
|
model_cpu_offload_seq = "bert->unet->vqvae"
|
53
54
|
|
54
55
|
def __init__(
|