Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/image_processing_vitmatte.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/modeling_vitmatte.py +338 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/__init__.py +787 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/configuration_utils.py +703 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/dependency_versions_check.py +34 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/dependency_versions_table.py +45 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/image_processor.py +990 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/optimization.py +361 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/__init__.py +581 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/auto_pipeline.py +987 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/__init__.py +153 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__init__.py +53 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_alt_diffusion.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_alt_diffusion_img2img.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_output.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +124 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +946 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1018 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__init__.py +18 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__pycache__/pipeline_latent_diffusion_uncond.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +130 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__init__.py +18 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__pycache__/pipeline_pndm.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +121 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/score_sde_ve/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/score_sde_ve/__pycache__/pipeline_score_sde_ve.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__init__.py +75 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/continuous_encoder.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/midi_utils.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/notes_encoder.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/pipeline_spectrogram_diffusion.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +92 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +667 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +86 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +269 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__init__.py +71 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/modeling_text_unet.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_dual_guided.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_image_variation.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_text_to_image.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +421 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +556 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +397 -0
evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/image_processing_vitmatte.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/vitmatte/modeling_vitmatte.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HUST-VL and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch ViTMatte model."""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ... import AutoBackbone
|
| 24 |
+
from ...modeling_utils import PreTrainedModel
|
| 25 |
+
from ...utils import (
|
| 26 |
+
ModelOutput,
|
| 27 |
+
add_start_docstrings,
|
| 28 |
+
add_start_docstrings_to_model_forward,
|
| 29 |
+
replace_return_docstrings,
|
| 30 |
+
)
|
| 31 |
+
from .configuration_vitmatte import VitMatteConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
VITMATTE_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 35 |
+
"hustvl/vitmatte-small-composition-1k",
|
| 36 |
+
# See all VitMatte models at https://huggingface.co/models?filter=vitmatte
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# General docstring
|
| 41 |
+
_CONFIG_FOR_DOC = "VitMatteConfig"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass
|
| 45 |
+
class ImageMattingOutput(ModelOutput):
|
| 46 |
+
"""
|
| 47 |
+
Class for outputs of image matting models.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 51 |
+
Loss.
|
| 52 |
+
alphas (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 53 |
+
Estimated alpha values.
|
| 54 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 55 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 56 |
+
one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
|
| 57 |
+
(also called feature maps) of the model at the output of each stage.
|
| 58 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 59 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
|
| 60 |
+
sequence_length)`.
|
| 61 |
+
|
| 62 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 63 |
+
heads.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
loss: Optional[torch.FloatTensor] = None
|
| 67 |
+
alphas: torch.FloatTensor = None
|
| 68 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 69 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class VitMattePreTrainedModel(PreTrainedModel):
|
| 73 |
+
"""
|
| 74 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 75 |
+
models.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
config_class = VitMatteConfig
|
| 79 |
+
main_input_name = "pixel_values"
|
| 80 |
+
supports_gradient_checkpointing = True
|
| 81 |
+
|
| 82 |
+
def _init_weights(self, module):
|
| 83 |
+
if isinstance(module, nn.Conv2d):
|
| 84 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 85 |
+
if module.bias is not None:
|
| 86 |
+
module.bias.data.zero_()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class VitMatteBasicConv3x3(nn.Module):
|
| 90 |
+
"""
|
| 91 |
+
Basic convolution layers including: Conv3x3, BatchNorm2d, ReLU layers.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, config, in_channels, out_channels, stride=2, padding=1):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.conv = nn.Conv2d(
|
| 97 |
+
in_channels=in_channels,
|
| 98 |
+
out_channels=out_channels,
|
| 99 |
+
kernel_size=3,
|
| 100 |
+
stride=stride,
|
| 101 |
+
padding=padding,
|
| 102 |
+
bias=False,
|
| 103 |
+
)
|
| 104 |
+
self.batch_norm = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
|
| 105 |
+
self.relu = nn.ReLU()
|
| 106 |
+
|
| 107 |
+
def forward(self, hidden_state):
|
| 108 |
+
hidden_state = self.conv(hidden_state)
|
| 109 |
+
hidden_state = self.batch_norm(hidden_state)
|
| 110 |
+
hidden_state = self.relu(hidden_state)
|
| 111 |
+
|
| 112 |
+
return hidden_state
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class VitMatteConvStream(nn.Module):
|
| 116 |
+
"""
|
| 117 |
+
Simple ConvStream containing a series of basic conv3x3 layers to extract detail features.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
def __init__(self, config):
|
| 121 |
+
super().__init__()
|
| 122 |
+
|
| 123 |
+
in_channels = config.backbone_config.num_channels
|
| 124 |
+
out_channels = config.convstream_hidden_sizes
|
| 125 |
+
|
| 126 |
+
self.convs = nn.ModuleList()
|
| 127 |
+
self.conv_chans = [in_channels] + out_channels
|
| 128 |
+
|
| 129 |
+
for i in range(len(self.conv_chans) - 1):
|
| 130 |
+
in_chan_ = self.conv_chans[i]
|
| 131 |
+
out_chan_ = self.conv_chans[i + 1]
|
| 132 |
+
self.convs.append(VitMatteBasicConv3x3(config, in_chan_, out_chan_))
|
| 133 |
+
|
| 134 |
+
def forward(self, pixel_values):
|
| 135 |
+
out_dict = {"detailed_feature_map_0": pixel_values}
|
| 136 |
+
embeddings = pixel_values
|
| 137 |
+
for i in range(len(self.convs)):
|
| 138 |
+
embeddings = self.convs[i](embeddings)
|
| 139 |
+
name_ = "detailed_feature_map_" + str(i + 1)
|
| 140 |
+
out_dict[name_] = embeddings
|
| 141 |
+
|
| 142 |
+
return out_dict
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class VitMatteFusionBlock(nn.Module):
|
| 146 |
+
"""
|
| 147 |
+
Simple fusion block to fuse features from ConvStream and Plain Vision Transformer.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(self, config, in_channels, out_channels):
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.conv = VitMatteBasicConv3x3(config, in_channels, out_channels, stride=1, padding=1)
|
| 153 |
+
|
| 154 |
+
def forward(self, features, detailed_feature_map):
|
| 155 |
+
upscaled_features = nn.functional.interpolate(features, scale_factor=2, mode="bilinear", align_corners=False)
|
| 156 |
+
out = torch.cat([detailed_feature_map, upscaled_features], dim=1)
|
| 157 |
+
out = self.conv(out)
|
| 158 |
+
|
| 159 |
+
return out
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class VitMatteHead(nn.Module):
|
| 163 |
+
"""
|
| 164 |
+
Simple Matting Head, containing only conv3x3 and conv1x1 layers.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self, config):
|
| 168 |
+
super().__init__()
|
| 169 |
+
|
| 170 |
+
in_channels = config.fusion_hidden_sizes[-1]
|
| 171 |
+
mid_channels = 16
|
| 172 |
+
|
| 173 |
+
self.matting_convs = nn.Sequential(
|
| 174 |
+
nn.Conv2d(in_channels, mid_channels, kernel_size=3, stride=1, padding=1),
|
| 175 |
+
nn.BatchNorm2d(mid_channels),
|
| 176 |
+
nn.ReLU(True),
|
| 177 |
+
nn.Conv2d(mid_channels, 1, kernel_size=1, stride=1, padding=0),
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def forward(self, hidden_state):
|
| 181 |
+
hidden_state = self.matting_convs(hidden_state)
|
| 182 |
+
|
| 183 |
+
return hidden_state
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class VitMatteDetailCaptureModule(nn.Module):
|
| 187 |
+
"""
|
| 188 |
+
Simple and lightweight Detail Capture Module for ViT Matting.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def __init__(self, config):
|
| 192 |
+
super().__init__()
|
| 193 |
+
if len(config.fusion_hidden_sizes) != len(config.convstream_hidden_sizes) + 1:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
"The length of fusion_hidden_sizes should be equal to the length of convstream_hidden_sizes + 1."
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
self.config = config
|
| 199 |
+
self.convstream = VitMatteConvStream(config)
|
| 200 |
+
self.conv_chans = self.convstream.conv_chans
|
| 201 |
+
|
| 202 |
+
self.fusion_blocks = nn.ModuleList()
|
| 203 |
+
self.fusion_channels = [config.hidden_size] + config.fusion_hidden_sizes
|
| 204 |
+
|
| 205 |
+
for i in range(len(self.fusion_channels) - 1):
|
| 206 |
+
self.fusion_blocks.append(
|
| 207 |
+
VitMatteFusionBlock(
|
| 208 |
+
config=config,
|
| 209 |
+
in_channels=self.fusion_channels[i] + self.conv_chans[-(i + 1)],
|
| 210 |
+
out_channels=self.fusion_channels[i + 1],
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
self.matting_head = VitMatteHead(config)
|
| 215 |
+
|
| 216 |
+
def forward(self, features, pixel_values):
|
| 217 |
+
detail_features = self.convstream(pixel_values)
|
| 218 |
+
for i in range(len(self.fusion_blocks)):
|
| 219 |
+
detailed_feature_map_name = "detailed_feature_map_" + str(len(self.fusion_blocks) - i - 1)
|
| 220 |
+
features = self.fusion_blocks[i](features, detail_features[detailed_feature_map_name])
|
| 221 |
+
|
| 222 |
+
alphas = torch.sigmoid(self.matting_head(features))
|
| 223 |
+
|
| 224 |
+
return alphas
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
VITMATTE_START_DOCSTRING = r"""
|
| 228 |
+
Parameters:
|
| 229 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 230 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 231 |
+
behavior.
|
| 232 |
+
config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
|
| 233 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 234 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
VITMATTE_INPUTS_DOCSTRING = r"""
|
| 238 |
+
Args:
|
| 239 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 240 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 241 |
+
[`AutoImageProcessor`]. See [`VitMatteImageProcessor.__call__`] for details.
|
| 242 |
+
output_attentions (`bool`, *optional*):
|
| 243 |
+
Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
|
| 244 |
+
`attentions` under returned tensors for more detail.
|
| 245 |
+
output_hidden_states (`bool`, *optional*):
|
| 246 |
+
Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under
|
| 247 |
+
returned tensors for more detail.
|
| 248 |
+
return_dict (`bool`, *optional*):
|
| 249 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@add_start_docstrings(
|
| 254 |
+
"""ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.""",
|
| 255 |
+
VITMATTE_START_DOCSTRING,
|
| 256 |
+
)
|
| 257 |
+
class VitMatteForImageMatting(VitMattePreTrainedModel):
|
| 258 |
+
def __init__(self, config):
|
| 259 |
+
super().__init__(config)
|
| 260 |
+
self.config = config
|
| 261 |
+
|
| 262 |
+
self.backbone = AutoBackbone.from_config(config.backbone_config)
|
| 263 |
+
self.decoder = VitMatteDetailCaptureModule(config)
|
| 264 |
+
|
| 265 |
+
# Initialize weights and apply final processing
|
| 266 |
+
self.post_init()
|
| 267 |
+
|
| 268 |
+
@add_start_docstrings_to_model_forward(VITMATTE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 269 |
+
@replace_return_docstrings(output_type=ImageMattingOutput, config_class=_CONFIG_FOR_DOC)
|
| 270 |
+
def forward(
|
| 271 |
+
self,
|
| 272 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 273 |
+
output_attentions: Optional[bool] = None,
|
| 274 |
+
output_hidden_states: Optional[bool] = None,
|
| 275 |
+
labels: Optional[torch.Tensor] = None,
|
| 276 |
+
return_dict: Optional[bool] = None,
|
| 277 |
+
):
|
| 278 |
+
"""
|
| 279 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 280 |
+
Ground truth image matting for computing the loss.
|
| 281 |
+
|
| 282 |
+
Returns:
|
| 283 |
+
|
| 284 |
+
Examples:
|
| 285 |
+
|
| 286 |
+
```python
|
| 287 |
+
>>> from transformers import VitMatteImageProcessor, VitMatteForImageMatting
|
| 288 |
+
>>> import torch
|
| 289 |
+
>>> from PIL import Image
|
| 290 |
+
>>> from huggingface_hub import hf_hub_download
|
| 291 |
+
|
| 292 |
+
>>> processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k")
|
| 293 |
+
>>> model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k")
|
| 294 |
+
|
| 295 |
+
>>> filepath = hf_hub_download(
|
| 296 |
+
... repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset"
|
| 297 |
+
... )
|
| 298 |
+
>>> image = Image.open(filepath).convert("RGB")
|
| 299 |
+
>>> filepath = hf_hub_download(
|
| 300 |
+
... repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset"
|
| 301 |
+
... )
|
| 302 |
+
>>> trimap = Image.open(filepath).convert("L")
|
| 303 |
+
|
| 304 |
+
>>> # prepare image + trimap for the model
|
| 305 |
+
>>> inputs = processor(images=image, trimaps=trimap, return_tensors="pt")
|
| 306 |
+
|
| 307 |
+
>>> with torch.no_grad():
|
| 308 |
+
... alphas = model(**inputs).alphas
|
| 309 |
+
>>> print(alphas.shape)
|
| 310 |
+
torch.Size([1, 1, 640, 960])
|
| 311 |
+
```"""
|
| 312 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 313 |
+
output_hidden_states = (
|
| 314 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 315 |
+
)
|
| 316 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 317 |
+
|
| 318 |
+
outputs = self.backbone.forward_with_filtered_kwargs(
|
| 319 |
+
pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
features = outputs.feature_maps[-1]
|
| 323 |
+
alphas = self.decoder(features, pixel_values)
|
| 324 |
+
|
| 325 |
+
loss = None
|
| 326 |
+
if labels is not None:
|
| 327 |
+
raise NotImplementedError("Training is not yet supported")
|
| 328 |
+
|
| 329 |
+
if not return_dict:
|
| 330 |
+
output = (alphas,) + outputs[1:]
|
| 331 |
+
return ((loss,) + output) if loss is not None else output
|
| 332 |
+
|
| 333 |
+
return ImageMattingOutput(
|
| 334 |
+
loss=loss,
|
| 335 |
+
alphas=alphas,
|
| 336 |
+
hidden_states=outputs.hidden_states,
|
| 337 |
+
attentions=outputs.attentions,
|
| 338 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/__init__.py
ADDED
|
@@ -0,0 +1,787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.27.2"
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from .utils import (
|
| 6 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 7 |
+
OptionalDependencyNotAvailable,
|
| 8 |
+
_LazyModule,
|
| 9 |
+
is_flax_available,
|
| 10 |
+
is_k_diffusion_available,
|
| 11 |
+
is_librosa_available,
|
| 12 |
+
is_note_seq_available,
|
| 13 |
+
is_onnx_available,
|
| 14 |
+
is_scipy_available,
|
| 15 |
+
is_torch_available,
|
| 16 |
+
is_torchsde_available,
|
| 17 |
+
is_transformers_available,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Lazy Import based on
|
| 22 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/__init__.py
|
| 23 |
+
|
| 24 |
+
# When adding a new object to this init, please add it to `_import_structure`. The `_import_structure` is a dictionary submodule to list of object names,
|
| 25 |
+
# and is used to defer the actual importing for when the objects are requested.
|
| 26 |
+
# This way `import diffusers` provides the names in the namespace without actually importing anything (and especially none of the backends).
|
| 27 |
+
|
| 28 |
+
_import_structure = {
|
| 29 |
+
"configuration_utils": ["ConfigMixin"],
|
| 30 |
+
"models": [],
|
| 31 |
+
"pipelines": [],
|
| 32 |
+
"schedulers": [],
|
| 33 |
+
"utils": [
|
| 34 |
+
"OptionalDependencyNotAvailable",
|
| 35 |
+
"is_flax_available",
|
| 36 |
+
"is_inflect_available",
|
| 37 |
+
"is_invisible_watermark_available",
|
| 38 |
+
"is_k_diffusion_available",
|
| 39 |
+
"is_k_diffusion_version",
|
| 40 |
+
"is_librosa_available",
|
| 41 |
+
"is_note_seq_available",
|
| 42 |
+
"is_onnx_available",
|
| 43 |
+
"is_scipy_available",
|
| 44 |
+
"is_torch_available",
|
| 45 |
+
"is_torchsde_available",
|
| 46 |
+
"is_transformers_available",
|
| 47 |
+
"is_transformers_version",
|
| 48 |
+
"is_unidecode_available",
|
| 49 |
+
"logging",
|
| 50 |
+
],
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
if not is_onnx_available():
|
| 55 |
+
raise OptionalDependencyNotAvailable()
|
| 56 |
+
except OptionalDependencyNotAvailable:
|
| 57 |
+
from .utils import dummy_onnx_objects # noqa F403
|
| 58 |
+
|
| 59 |
+
_import_structure["utils.dummy_onnx_objects"] = [
|
| 60 |
+
name for name in dir(dummy_onnx_objects) if not name.startswith("_")
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
_import_structure["pipelines"].extend(["OnnxRuntimeModel"])
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
if not is_torch_available():
|
| 68 |
+
raise OptionalDependencyNotAvailable()
|
| 69 |
+
except OptionalDependencyNotAvailable:
|
| 70 |
+
from .utils import dummy_pt_objects # noqa F403
|
| 71 |
+
|
| 72 |
+
_import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
|
| 73 |
+
|
| 74 |
+
else:
|
| 75 |
+
_import_structure["models"].extend(
|
| 76 |
+
[
|
| 77 |
+
"AsymmetricAutoencoderKL",
|
| 78 |
+
"AutoencoderKL",
|
| 79 |
+
"AutoencoderKLTemporalDecoder",
|
| 80 |
+
"AutoencoderTiny",
|
| 81 |
+
"ConsistencyDecoderVAE",
|
| 82 |
+
"ControlNetModel",
|
| 83 |
+
"I2VGenXLUNet",
|
| 84 |
+
"Kandinsky3UNet",
|
| 85 |
+
"ModelMixin",
|
| 86 |
+
"MotionAdapter",
|
| 87 |
+
"MultiAdapter",
|
| 88 |
+
"PriorTransformer",
|
| 89 |
+
"StableCascadeUNet",
|
| 90 |
+
"T2IAdapter",
|
| 91 |
+
"T5FilmDecoder",
|
| 92 |
+
"Transformer2DModel",
|
| 93 |
+
"UNet1DModel",
|
| 94 |
+
"UNet2DConditionModel",
|
| 95 |
+
"UNet2DModel",
|
| 96 |
+
"UNet3DConditionModel",
|
| 97 |
+
"UNetMotionModel",
|
| 98 |
+
"UNetSpatioTemporalConditionModel",
|
| 99 |
+
"UVit2DModel",
|
| 100 |
+
"VQModel",
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
_import_structure["optimization"] = [
|
| 105 |
+
"get_constant_schedule",
|
| 106 |
+
"get_constant_schedule_with_warmup",
|
| 107 |
+
"get_cosine_schedule_with_warmup",
|
| 108 |
+
"get_cosine_with_hard_restarts_schedule_with_warmup",
|
| 109 |
+
"get_linear_schedule_with_warmup",
|
| 110 |
+
"get_polynomial_decay_schedule_with_warmup",
|
| 111 |
+
"get_scheduler",
|
| 112 |
+
]
|
| 113 |
+
_import_structure["pipelines"].extend(
|
| 114 |
+
[
|
| 115 |
+
"AudioPipelineOutput",
|
| 116 |
+
"AutoPipelineForImage2Image",
|
| 117 |
+
"AutoPipelineForInpainting",
|
| 118 |
+
"AutoPipelineForText2Image",
|
| 119 |
+
"ConsistencyModelPipeline",
|
| 120 |
+
"DanceDiffusionPipeline",
|
| 121 |
+
"DDIMPipeline",
|
| 122 |
+
"DDPMPipeline",
|
| 123 |
+
"DiffusionPipeline",
|
| 124 |
+
"DiTPipeline",
|
| 125 |
+
"ImagePipelineOutput",
|
| 126 |
+
"KarrasVePipeline",
|
| 127 |
+
"LDMPipeline",
|
| 128 |
+
"LDMSuperResolutionPipeline",
|
| 129 |
+
"PNDMPipeline",
|
| 130 |
+
"RePaintPipeline",
|
| 131 |
+
"ScoreSdeVePipeline",
|
| 132 |
+
"StableDiffusionMixin",
|
| 133 |
+
]
|
| 134 |
+
)
|
| 135 |
+
_import_structure["schedulers"].extend(
|
| 136 |
+
[
|
| 137 |
+
"AmusedScheduler",
|
| 138 |
+
"CMStochasticIterativeScheduler",
|
| 139 |
+
"DDIMInverseScheduler",
|
| 140 |
+
"DDIMParallelScheduler",
|
| 141 |
+
"DDIMScheduler",
|
| 142 |
+
"DDPMParallelScheduler",
|
| 143 |
+
"DDPMScheduler",
|
| 144 |
+
"DDPMWuerstchenScheduler",
|
| 145 |
+
"DEISMultistepScheduler",
|
| 146 |
+
"DPMSolverMultistepInverseScheduler",
|
| 147 |
+
"DPMSolverMultistepScheduler",
|
| 148 |
+
"DPMSolverSinglestepScheduler",
|
| 149 |
+
"EDMDPMSolverMultistepScheduler",
|
| 150 |
+
"EDMEulerScheduler",
|
| 151 |
+
"EulerAncestralDiscreteScheduler",
|
| 152 |
+
"EulerDiscreteScheduler",
|
| 153 |
+
"HeunDiscreteScheduler",
|
| 154 |
+
"IPNDMScheduler",
|
| 155 |
+
"KarrasVeScheduler",
|
| 156 |
+
"KDPM2AncestralDiscreteScheduler",
|
| 157 |
+
"KDPM2DiscreteScheduler",
|
| 158 |
+
"LCMScheduler",
|
| 159 |
+
"PNDMScheduler",
|
| 160 |
+
"RePaintScheduler",
|
| 161 |
+
"SASolverScheduler",
|
| 162 |
+
"SchedulerMixin",
|
| 163 |
+
"ScoreSdeVeScheduler",
|
| 164 |
+
"TCDScheduler",
|
| 165 |
+
"UnCLIPScheduler",
|
| 166 |
+
"UniPCMultistepScheduler",
|
| 167 |
+
"VQDiffusionScheduler",
|
| 168 |
+
]
|
| 169 |
+
)
|
| 170 |
+
_import_structure["training_utils"] = ["EMAModel"]
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
if not (is_torch_available() and is_scipy_available()):
|
| 174 |
+
raise OptionalDependencyNotAvailable()
|
| 175 |
+
except OptionalDependencyNotAvailable:
|
| 176 |
+
from .utils import dummy_torch_and_scipy_objects # noqa F403
|
| 177 |
+
|
| 178 |
+
_import_structure["utils.dummy_torch_and_scipy_objects"] = [
|
| 179 |
+
name for name in dir(dummy_torch_and_scipy_objects) if not name.startswith("_")
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
else:
|
| 183 |
+
_import_structure["schedulers"].extend(["LMSDiscreteScheduler"])
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
if not (is_torch_available() and is_torchsde_available()):
|
| 187 |
+
raise OptionalDependencyNotAvailable()
|
| 188 |
+
except OptionalDependencyNotAvailable:
|
| 189 |
+
from .utils import dummy_torch_and_torchsde_objects # noqa F403
|
| 190 |
+
|
| 191 |
+
_import_structure["utils.dummy_torch_and_torchsde_objects"] = [
|
| 192 |
+
name for name in dir(dummy_torch_and_torchsde_objects) if not name.startswith("_")
|
| 193 |
+
]
|
| 194 |
+
|
| 195 |
+
else:
|
| 196 |
+
_import_structure["schedulers"].extend(["DPMSolverSDEScheduler"])
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 200 |
+
raise OptionalDependencyNotAvailable()
|
| 201 |
+
except OptionalDependencyNotAvailable:
|
| 202 |
+
from .utils import dummy_torch_and_transformers_objects # noqa F403
|
| 203 |
+
|
| 204 |
+
_import_structure["utils.dummy_torch_and_transformers_objects"] = [
|
| 205 |
+
name for name in dir(dummy_torch_and_transformers_objects) if not name.startswith("_")
|
| 206 |
+
]
|
| 207 |
+
|
| 208 |
+
else:
|
| 209 |
+
_import_structure["pipelines"].extend(
|
| 210 |
+
[
|
| 211 |
+
"AltDiffusionImg2ImgPipeline",
|
| 212 |
+
"AltDiffusionPipeline",
|
| 213 |
+
"AmusedImg2ImgPipeline",
|
| 214 |
+
"AmusedInpaintPipeline",
|
| 215 |
+
"AmusedPipeline",
|
| 216 |
+
"AnimateDiffPipeline",
|
| 217 |
+
"AnimateDiffVideoToVideoPipeline",
|
| 218 |
+
"AudioLDM2Pipeline",
|
| 219 |
+
"AudioLDM2ProjectionModel",
|
| 220 |
+
"AudioLDM2UNet2DConditionModel",
|
| 221 |
+
"AudioLDMPipeline",
|
| 222 |
+
"BlipDiffusionControlNetPipeline",
|
| 223 |
+
"BlipDiffusionPipeline",
|
| 224 |
+
"CLIPImageProjection",
|
| 225 |
+
"CycleDiffusionPipeline",
|
| 226 |
+
"I2VGenXLPipeline",
|
| 227 |
+
"IFImg2ImgPipeline",
|
| 228 |
+
"IFImg2ImgSuperResolutionPipeline",
|
| 229 |
+
"IFInpaintingPipeline",
|
| 230 |
+
"IFInpaintingSuperResolutionPipeline",
|
| 231 |
+
"IFPipeline",
|
| 232 |
+
"IFSuperResolutionPipeline",
|
| 233 |
+
"ImageTextPipelineOutput",
|
| 234 |
+
"Kandinsky3Img2ImgPipeline",
|
| 235 |
+
"Kandinsky3Pipeline",
|
| 236 |
+
"KandinskyCombinedPipeline",
|
| 237 |
+
"KandinskyImg2ImgCombinedPipeline",
|
| 238 |
+
"KandinskyImg2ImgPipeline",
|
| 239 |
+
"KandinskyInpaintCombinedPipeline",
|
| 240 |
+
"KandinskyInpaintPipeline",
|
| 241 |
+
"KandinskyPipeline",
|
| 242 |
+
"KandinskyPriorPipeline",
|
| 243 |
+
"KandinskyV22CombinedPipeline",
|
| 244 |
+
"KandinskyV22ControlnetImg2ImgPipeline",
|
| 245 |
+
"KandinskyV22ControlnetPipeline",
|
| 246 |
+
"KandinskyV22Img2ImgCombinedPipeline",
|
| 247 |
+
"KandinskyV22Img2ImgPipeline",
|
| 248 |
+
"KandinskyV22InpaintCombinedPipeline",
|
| 249 |
+
"KandinskyV22InpaintPipeline",
|
| 250 |
+
"KandinskyV22Pipeline",
|
| 251 |
+
"KandinskyV22PriorEmb2EmbPipeline",
|
| 252 |
+
"KandinskyV22PriorPipeline",
|
| 253 |
+
"LatentConsistencyModelImg2ImgPipeline",
|
| 254 |
+
"LatentConsistencyModelPipeline",
|
| 255 |
+
"LDMTextToImagePipeline",
|
| 256 |
+
"LEditsPPPipelineStableDiffusion",
|
| 257 |
+
"LEditsPPPipelineStableDiffusionXL",
|
| 258 |
+
"MusicLDMPipeline",
|
| 259 |
+
"PaintByExamplePipeline",
|
| 260 |
+
"PIAPipeline",
|
| 261 |
+
"PixArtAlphaPipeline",
|
| 262 |
+
"SemanticStableDiffusionPipeline",
|
| 263 |
+
"ShapEImg2ImgPipeline",
|
| 264 |
+
"ShapEPipeline",
|
| 265 |
+
"StableCascadeCombinedPipeline",
|
| 266 |
+
"StableCascadeDecoderPipeline",
|
| 267 |
+
"StableCascadePriorPipeline",
|
| 268 |
+
"StableDiffusionAdapterPipeline",
|
| 269 |
+
"StableDiffusionAttendAndExcitePipeline",
|
| 270 |
+
"StableDiffusionControlNetImg2ImgPipeline",
|
| 271 |
+
"StableDiffusionControlNetInpaintPipeline",
|
| 272 |
+
"StableDiffusionControlNetPipeline",
|
| 273 |
+
"StableDiffusionDepth2ImgPipeline",
|
| 274 |
+
"StableDiffusionDiffEditPipeline",
|
| 275 |
+
"StableDiffusionGLIGENPipeline",
|
| 276 |
+
"StableDiffusionGLIGENTextImagePipeline",
|
| 277 |
+
"StableDiffusionImageVariationPipeline",
|
| 278 |
+
"StableDiffusionImg2ImgPipeline",
|
| 279 |
+
"StableDiffusionInpaintPipeline",
|
| 280 |
+
"StableDiffusionInpaintPipelineLegacy",
|
| 281 |
+
"StableDiffusionInstructPix2PixPipeline",
|
| 282 |
+
"StableDiffusionLatentUpscalePipeline",
|
| 283 |
+
"StableDiffusionLDM3DPipeline",
|
| 284 |
+
"StableDiffusionModelEditingPipeline",
|
| 285 |
+
"StableDiffusionPanoramaPipeline",
|
| 286 |
+
"StableDiffusionParadigmsPipeline",
|
| 287 |
+
"StableDiffusionPipeline",
|
| 288 |
+
"StableDiffusionPipelineSafe",
|
| 289 |
+
"StableDiffusionPix2PixZeroPipeline",
|
| 290 |
+
"StableDiffusionSAGPipeline",
|
| 291 |
+
"StableDiffusionUpscalePipeline",
|
| 292 |
+
"StableDiffusionXLAdapterPipeline",
|
| 293 |
+
"StableDiffusionXLControlNetImg2ImgPipeline",
|
| 294 |
+
"StableDiffusionXLControlNetInpaintPipeline",
|
| 295 |
+
"StableDiffusionXLControlNetPipeline",
|
| 296 |
+
"StableDiffusionXLImg2ImgPipeline",
|
| 297 |
+
"StableDiffusionXLInpaintPipeline",
|
| 298 |
+
"StableDiffusionXLInstructPix2PixPipeline",
|
| 299 |
+
"StableDiffusionXLPipeline",
|
| 300 |
+
"StableUnCLIPImg2ImgPipeline",
|
| 301 |
+
"StableUnCLIPPipeline",
|
| 302 |
+
"StableVideoDiffusionPipeline",
|
| 303 |
+
"TextToVideoSDPipeline",
|
| 304 |
+
"TextToVideoZeroPipeline",
|
| 305 |
+
"TextToVideoZeroSDXLPipeline",
|
| 306 |
+
"UnCLIPImageVariationPipeline",
|
| 307 |
+
"UnCLIPPipeline",
|
| 308 |
+
"UniDiffuserModel",
|
| 309 |
+
"UniDiffuserPipeline",
|
| 310 |
+
"UniDiffuserTextDecoder",
|
| 311 |
+
"VersatileDiffusionDualGuidedPipeline",
|
| 312 |
+
"VersatileDiffusionImageVariationPipeline",
|
| 313 |
+
"VersatileDiffusionPipeline",
|
| 314 |
+
"VersatileDiffusionTextToImagePipeline",
|
| 315 |
+
"VideoToVideoSDPipeline",
|
| 316 |
+
"VQDiffusionPipeline",
|
| 317 |
+
"WuerstchenCombinedPipeline",
|
| 318 |
+
"WuerstchenDecoderPipeline",
|
| 319 |
+
"WuerstchenPriorPipeline",
|
| 320 |
+
]
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
try:
|
| 324 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 325 |
+
raise OptionalDependencyNotAvailable()
|
| 326 |
+
except OptionalDependencyNotAvailable:
|
| 327 |
+
from .utils import dummy_torch_and_transformers_and_k_diffusion_objects # noqa F403
|
| 328 |
+
|
| 329 |
+
_import_structure["utils.dummy_torch_and_transformers_and_k_diffusion_objects"] = [
|
| 330 |
+
name for name in dir(dummy_torch_and_transformers_and_k_diffusion_objects) if not name.startswith("_")
|
| 331 |
+
]
|
| 332 |
+
|
| 333 |
+
else:
|
| 334 |
+
_import_structure["pipelines"].extend(["StableDiffusionKDiffusionPipeline", "StableDiffusionXLKDiffusionPipeline"])
|
| 335 |
+
|
| 336 |
+
try:
|
| 337 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 338 |
+
raise OptionalDependencyNotAvailable()
|
| 339 |
+
except OptionalDependencyNotAvailable:
|
| 340 |
+
from .utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
|
| 341 |
+
|
| 342 |
+
_import_structure["utils.dummy_torch_and_transformers_and_onnx_objects"] = [
|
| 343 |
+
name for name in dir(dummy_torch_and_transformers_and_onnx_objects) if not name.startswith("_")
|
| 344 |
+
]
|
| 345 |
+
|
| 346 |
+
else:
|
| 347 |
+
_import_structure["pipelines"].extend(
|
| 348 |
+
[
|
| 349 |
+
"OnnxStableDiffusionImg2ImgPipeline",
|
| 350 |
+
"OnnxStableDiffusionInpaintPipeline",
|
| 351 |
+
"OnnxStableDiffusionInpaintPipelineLegacy",
|
| 352 |
+
"OnnxStableDiffusionPipeline",
|
| 353 |
+
"OnnxStableDiffusionUpscalePipeline",
|
| 354 |
+
"StableDiffusionOnnxPipeline",
|
| 355 |
+
]
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
try:
|
| 359 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 360 |
+
raise OptionalDependencyNotAvailable()
|
| 361 |
+
except OptionalDependencyNotAvailable:
|
| 362 |
+
from .utils import dummy_torch_and_librosa_objects # noqa F403
|
| 363 |
+
|
| 364 |
+
_import_structure["utils.dummy_torch_and_librosa_objects"] = [
|
| 365 |
+
name for name in dir(dummy_torch_and_librosa_objects) if not name.startswith("_")
|
| 366 |
+
]
|
| 367 |
+
|
| 368 |
+
else:
|
| 369 |
+
_import_structure["pipelines"].extend(["AudioDiffusionPipeline", "Mel"])
|
| 370 |
+
|
| 371 |
+
try:
|
| 372 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 373 |
+
raise OptionalDependencyNotAvailable()
|
| 374 |
+
except OptionalDependencyNotAvailable:
|
| 375 |
+
from .utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
|
| 376 |
+
|
| 377 |
+
_import_structure["utils.dummy_transformers_and_torch_and_note_seq_objects"] = [
|
| 378 |
+
name for name in dir(dummy_transformers_and_torch_and_note_seq_objects) if not name.startswith("_")
|
| 379 |
+
]
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
else:
|
| 383 |
+
_import_structure["pipelines"].extend(["SpectrogramDiffusionPipeline"])
|
| 384 |
+
|
| 385 |
+
try:
|
| 386 |
+
if not is_flax_available():
|
| 387 |
+
raise OptionalDependencyNotAvailable()
|
| 388 |
+
except OptionalDependencyNotAvailable:
|
| 389 |
+
from .utils import dummy_flax_objects # noqa F403
|
| 390 |
+
|
| 391 |
+
_import_structure["utils.dummy_flax_objects"] = [
|
| 392 |
+
name for name in dir(dummy_flax_objects) if not name.startswith("_")
|
| 393 |
+
]
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
else:
|
| 397 |
+
_import_structure["models.controlnet_flax"] = ["FlaxControlNetModel"]
|
| 398 |
+
_import_structure["models.modeling_flax_utils"] = ["FlaxModelMixin"]
|
| 399 |
+
_import_structure["models.unets.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
|
| 400 |
+
_import_structure["models.vae_flax"] = ["FlaxAutoencoderKL"]
|
| 401 |
+
_import_structure["pipelines"].extend(["FlaxDiffusionPipeline"])
|
| 402 |
+
_import_structure["schedulers"].extend(
|
| 403 |
+
[
|
| 404 |
+
"FlaxDDIMScheduler",
|
| 405 |
+
"FlaxDDPMScheduler",
|
| 406 |
+
"FlaxDPMSolverMultistepScheduler",
|
| 407 |
+
"FlaxEulerDiscreteScheduler",
|
| 408 |
+
"FlaxKarrasVeScheduler",
|
| 409 |
+
"FlaxLMSDiscreteScheduler",
|
| 410 |
+
"FlaxPNDMScheduler",
|
| 411 |
+
"FlaxSchedulerMixin",
|
| 412 |
+
"FlaxScoreSdeVeScheduler",
|
| 413 |
+
]
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
try:
|
| 418 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 419 |
+
raise OptionalDependencyNotAvailable()
|
| 420 |
+
except OptionalDependencyNotAvailable:
|
| 421 |
+
from .utils import dummy_flax_and_transformers_objects # noqa F403
|
| 422 |
+
|
| 423 |
+
_import_structure["utils.dummy_flax_and_transformers_objects"] = [
|
| 424 |
+
name for name in dir(dummy_flax_and_transformers_objects) if not name.startswith("_")
|
| 425 |
+
]
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
else:
|
| 429 |
+
_import_structure["pipelines"].extend(
|
| 430 |
+
[
|
| 431 |
+
"FlaxStableDiffusionControlNetPipeline",
|
| 432 |
+
"FlaxStableDiffusionImg2ImgPipeline",
|
| 433 |
+
"FlaxStableDiffusionInpaintPipeline",
|
| 434 |
+
"FlaxStableDiffusionPipeline",
|
| 435 |
+
"FlaxStableDiffusionXLPipeline",
|
| 436 |
+
]
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
try:
|
| 440 |
+
if not (is_note_seq_available()):
|
| 441 |
+
raise OptionalDependencyNotAvailable()
|
| 442 |
+
except OptionalDependencyNotAvailable:
|
| 443 |
+
from .utils import dummy_note_seq_objects # noqa F403
|
| 444 |
+
|
| 445 |
+
_import_structure["utils.dummy_note_seq_objects"] = [
|
| 446 |
+
name for name in dir(dummy_note_seq_objects) if not name.startswith("_")
|
| 447 |
+
]
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
else:
|
| 451 |
+
_import_structure["pipelines"].extend(["MidiProcessor"])
|
| 452 |
+
|
| 453 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 454 |
+
from .configuration_utils import ConfigMixin
|
| 455 |
+
|
| 456 |
+
try:
|
| 457 |
+
if not is_onnx_available():
|
| 458 |
+
raise OptionalDependencyNotAvailable()
|
| 459 |
+
except OptionalDependencyNotAvailable:
|
| 460 |
+
from .utils.dummy_onnx_objects import * # noqa F403
|
| 461 |
+
else:
|
| 462 |
+
from .pipelines import OnnxRuntimeModel
|
| 463 |
+
|
| 464 |
+
try:
|
| 465 |
+
if not is_torch_available():
|
| 466 |
+
raise OptionalDependencyNotAvailable()
|
| 467 |
+
except OptionalDependencyNotAvailable:
|
| 468 |
+
from .utils.dummy_pt_objects import * # noqa F403
|
| 469 |
+
else:
|
| 470 |
+
from .models import (
|
| 471 |
+
AsymmetricAutoencoderKL,
|
| 472 |
+
AutoencoderKL,
|
| 473 |
+
AutoencoderKLTemporalDecoder,
|
| 474 |
+
AutoencoderTiny,
|
| 475 |
+
ConsistencyDecoderVAE,
|
| 476 |
+
ControlNetModel,
|
| 477 |
+
I2VGenXLUNet,
|
| 478 |
+
Kandinsky3UNet,
|
| 479 |
+
ModelMixin,
|
| 480 |
+
MotionAdapter,
|
| 481 |
+
MultiAdapter,
|
| 482 |
+
PriorTransformer,
|
| 483 |
+
T2IAdapter,
|
| 484 |
+
T5FilmDecoder,
|
| 485 |
+
Transformer2DModel,
|
| 486 |
+
UNet1DModel,
|
| 487 |
+
UNet2DConditionModel,
|
| 488 |
+
UNet2DModel,
|
| 489 |
+
UNet3DConditionModel,
|
| 490 |
+
UNetMotionModel,
|
| 491 |
+
UNetSpatioTemporalConditionModel,
|
| 492 |
+
UVit2DModel,
|
| 493 |
+
VQModel,
|
| 494 |
+
)
|
| 495 |
+
from .optimization import (
|
| 496 |
+
get_constant_schedule,
|
| 497 |
+
get_constant_schedule_with_warmup,
|
| 498 |
+
get_cosine_schedule_with_warmup,
|
| 499 |
+
get_cosine_with_hard_restarts_schedule_with_warmup,
|
| 500 |
+
get_linear_schedule_with_warmup,
|
| 501 |
+
get_polynomial_decay_schedule_with_warmup,
|
| 502 |
+
get_scheduler,
|
| 503 |
+
)
|
| 504 |
+
from .pipelines import (
|
| 505 |
+
AudioPipelineOutput,
|
| 506 |
+
AutoPipelineForImage2Image,
|
| 507 |
+
AutoPipelineForInpainting,
|
| 508 |
+
AutoPipelineForText2Image,
|
| 509 |
+
BlipDiffusionControlNetPipeline,
|
| 510 |
+
BlipDiffusionPipeline,
|
| 511 |
+
CLIPImageProjection,
|
| 512 |
+
ConsistencyModelPipeline,
|
| 513 |
+
DanceDiffusionPipeline,
|
| 514 |
+
DDIMPipeline,
|
| 515 |
+
DDPMPipeline,
|
| 516 |
+
DiffusionPipeline,
|
| 517 |
+
DiTPipeline,
|
| 518 |
+
ImagePipelineOutput,
|
| 519 |
+
KarrasVePipeline,
|
| 520 |
+
LDMPipeline,
|
| 521 |
+
LDMSuperResolutionPipeline,
|
| 522 |
+
PNDMPipeline,
|
| 523 |
+
RePaintPipeline,
|
| 524 |
+
ScoreSdeVePipeline,
|
| 525 |
+
StableDiffusionMixin,
|
| 526 |
+
)
|
| 527 |
+
from .schedulers import (
|
| 528 |
+
AmusedScheduler,
|
| 529 |
+
CMStochasticIterativeScheduler,
|
| 530 |
+
DDIMInverseScheduler,
|
| 531 |
+
DDIMParallelScheduler,
|
| 532 |
+
DDIMScheduler,
|
| 533 |
+
DDPMParallelScheduler,
|
| 534 |
+
DDPMScheduler,
|
| 535 |
+
DDPMWuerstchenScheduler,
|
| 536 |
+
DEISMultistepScheduler,
|
| 537 |
+
DPMSolverMultistepInverseScheduler,
|
| 538 |
+
DPMSolverMultistepScheduler,
|
| 539 |
+
DPMSolverSinglestepScheduler,
|
| 540 |
+
EDMDPMSolverMultistepScheduler,
|
| 541 |
+
EDMEulerScheduler,
|
| 542 |
+
EulerAncestralDiscreteScheduler,
|
| 543 |
+
EulerDiscreteScheduler,
|
| 544 |
+
HeunDiscreteScheduler,
|
| 545 |
+
IPNDMScheduler,
|
| 546 |
+
KarrasVeScheduler,
|
| 547 |
+
KDPM2AncestralDiscreteScheduler,
|
| 548 |
+
KDPM2DiscreteScheduler,
|
| 549 |
+
LCMScheduler,
|
| 550 |
+
PNDMScheduler,
|
| 551 |
+
RePaintScheduler,
|
| 552 |
+
SASolverScheduler,
|
| 553 |
+
SchedulerMixin,
|
| 554 |
+
ScoreSdeVeScheduler,
|
| 555 |
+
TCDScheduler,
|
| 556 |
+
UnCLIPScheduler,
|
| 557 |
+
UniPCMultistepScheduler,
|
| 558 |
+
VQDiffusionScheduler,
|
| 559 |
+
)
|
| 560 |
+
from .training_utils import EMAModel
|
| 561 |
+
|
| 562 |
+
try:
|
| 563 |
+
if not (is_torch_available() and is_scipy_available()):
|
| 564 |
+
raise OptionalDependencyNotAvailable()
|
| 565 |
+
except OptionalDependencyNotAvailable:
|
| 566 |
+
from .utils.dummy_torch_and_scipy_objects import * # noqa F403
|
| 567 |
+
else:
|
| 568 |
+
from .schedulers import LMSDiscreteScheduler
|
| 569 |
+
|
| 570 |
+
try:
|
| 571 |
+
if not (is_torch_available() and is_torchsde_available()):
|
| 572 |
+
raise OptionalDependencyNotAvailable()
|
| 573 |
+
except OptionalDependencyNotAvailable:
|
| 574 |
+
from .utils.dummy_torch_and_torchsde_objects import * # noqa F403
|
| 575 |
+
else:
|
| 576 |
+
from .schedulers import DPMSolverSDEScheduler
|
| 577 |
+
|
| 578 |
+
try:
|
| 579 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 580 |
+
raise OptionalDependencyNotAvailable()
|
| 581 |
+
except OptionalDependencyNotAvailable:
|
| 582 |
+
from .utils.dummy_torch_and_transformers_objects import * # noqa F403
|
| 583 |
+
else:
|
| 584 |
+
from .pipelines import (
|
| 585 |
+
AltDiffusionImg2ImgPipeline,
|
| 586 |
+
AltDiffusionPipeline,
|
| 587 |
+
AmusedImg2ImgPipeline,
|
| 588 |
+
AmusedInpaintPipeline,
|
| 589 |
+
AmusedPipeline,
|
| 590 |
+
AnimateDiffPipeline,
|
| 591 |
+
AnimateDiffVideoToVideoPipeline,
|
| 592 |
+
AudioLDM2Pipeline,
|
| 593 |
+
AudioLDM2ProjectionModel,
|
| 594 |
+
AudioLDM2UNet2DConditionModel,
|
| 595 |
+
AudioLDMPipeline,
|
| 596 |
+
CLIPImageProjection,
|
| 597 |
+
CycleDiffusionPipeline,
|
| 598 |
+
I2VGenXLPipeline,
|
| 599 |
+
IFImg2ImgPipeline,
|
| 600 |
+
IFImg2ImgSuperResolutionPipeline,
|
| 601 |
+
IFInpaintingPipeline,
|
| 602 |
+
IFInpaintingSuperResolutionPipeline,
|
| 603 |
+
IFPipeline,
|
| 604 |
+
IFSuperResolutionPipeline,
|
| 605 |
+
ImageTextPipelineOutput,
|
| 606 |
+
Kandinsky3Img2ImgPipeline,
|
| 607 |
+
Kandinsky3Pipeline,
|
| 608 |
+
KandinskyCombinedPipeline,
|
| 609 |
+
KandinskyImg2ImgCombinedPipeline,
|
| 610 |
+
KandinskyImg2ImgPipeline,
|
| 611 |
+
KandinskyInpaintCombinedPipeline,
|
| 612 |
+
KandinskyInpaintPipeline,
|
| 613 |
+
KandinskyPipeline,
|
| 614 |
+
KandinskyPriorPipeline,
|
| 615 |
+
KandinskyV22CombinedPipeline,
|
| 616 |
+
KandinskyV22ControlnetImg2ImgPipeline,
|
| 617 |
+
KandinskyV22ControlnetPipeline,
|
| 618 |
+
KandinskyV22Img2ImgCombinedPipeline,
|
| 619 |
+
KandinskyV22Img2ImgPipeline,
|
| 620 |
+
KandinskyV22InpaintCombinedPipeline,
|
| 621 |
+
KandinskyV22InpaintPipeline,
|
| 622 |
+
KandinskyV22Pipeline,
|
| 623 |
+
KandinskyV22PriorEmb2EmbPipeline,
|
| 624 |
+
KandinskyV22PriorPipeline,
|
| 625 |
+
LatentConsistencyModelImg2ImgPipeline,
|
| 626 |
+
LatentConsistencyModelPipeline,
|
| 627 |
+
LDMTextToImagePipeline,
|
| 628 |
+
LEditsPPPipelineStableDiffusion,
|
| 629 |
+
LEditsPPPipelineStableDiffusionXL,
|
| 630 |
+
MusicLDMPipeline,
|
| 631 |
+
PaintByExamplePipeline,
|
| 632 |
+
PIAPipeline,
|
| 633 |
+
PixArtAlphaPipeline,
|
| 634 |
+
SemanticStableDiffusionPipeline,
|
| 635 |
+
ShapEImg2ImgPipeline,
|
| 636 |
+
ShapEPipeline,
|
| 637 |
+
StableCascadeCombinedPipeline,
|
| 638 |
+
StableCascadeDecoderPipeline,
|
| 639 |
+
StableCascadePriorPipeline,
|
| 640 |
+
StableDiffusionAdapterPipeline,
|
| 641 |
+
StableDiffusionAttendAndExcitePipeline,
|
| 642 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
| 643 |
+
StableDiffusionControlNetInpaintPipeline,
|
| 644 |
+
StableDiffusionControlNetPipeline,
|
| 645 |
+
StableDiffusionDepth2ImgPipeline,
|
| 646 |
+
StableDiffusionDiffEditPipeline,
|
| 647 |
+
StableDiffusionGLIGENPipeline,
|
| 648 |
+
StableDiffusionGLIGENTextImagePipeline,
|
| 649 |
+
StableDiffusionImageVariationPipeline,
|
| 650 |
+
StableDiffusionImg2ImgPipeline,
|
| 651 |
+
StableDiffusionInpaintPipeline,
|
| 652 |
+
StableDiffusionInpaintPipelineLegacy,
|
| 653 |
+
StableDiffusionInstructPix2PixPipeline,
|
| 654 |
+
StableDiffusionLatentUpscalePipeline,
|
| 655 |
+
StableDiffusionLDM3DPipeline,
|
| 656 |
+
StableDiffusionModelEditingPipeline,
|
| 657 |
+
StableDiffusionPanoramaPipeline,
|
| 658 |
+
StableDiffusionParadigmsPipeline,
|
| 659 |
+
StableDiffusionPipeline,
|
| 660 |
+
StableDiffusionPipelineSafe,
|
| 661 |
+
StableDiffusionPix2PixZeroPipeline,
|
| 662 |
+
StableDiffusionSAGPipeline,
|
| 663 |
+
StableDiffusionUpscalePipeline,
|
| 664 |
+
StableDiffusionXLAdapterPipeline,
|
| 665 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
| 666 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
| 667 |
+
StableDiffusionXLControlNetPipeline,
|
| 668 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 669 |
+
StableDiffusionXLInpaintPipeline,
|
| 670 |
+
StableDiffusionXLInstructPix2PixPipeline,
|
| 671 |
+
StableDiffusionXLPipeline,
|
| 672 |
+
StableUnCLIPImg2ImgPipeline,
|
| 673 |
+
StableUnCLIPPipeline,
|
| 674 |
+
StableVideoDiffusionPipeline,
|
| 675 |
+
TextToVideoSDPipeline,
|
| 676 |
+
TextToVideoZeroPipeline,
|
| 677 |
+
TextToVideoZeroSDXLPipeline,
|
| 678 |
+
UnCLIPImageVariationPipeline,
|
| 679 |
+
UnCLIPPipeline,
|
| 680 |
+
UniDiffuserModel,
|
| 681 |
+
UniDiffuserPipeline,
|
| 682 |
+
UniDiffuserTextDecoder,
|
| 683 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 684 |
+
VersatileDiffusionImageVariationPipeline,
|
| 685 |
+
VersatileDiffusionPipeline,
|
| 686 |
+
VersatileDiffusionTextToImagePipeline,
|
| 687 |
+
VideoToVideoSDPipeline,
|
| 688 |
+
VQDiffusionPipeline,
|
| 689 |
+
WuerstchenCombinedPipeline,
|
| 690 |
+
WuerstchenDecoderPipeline,
|
| 691 |
+
WuerstchenPriorPipeline,
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
try:
|
| 695 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 696 |
+
raise OptionalDependencyNotAvailable()
|
| 697 |
+
except OptionalDependencyNotAvailable:
|
| 698 |
+
from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
|
| 699 |
+
else:
|
| 700 |
+
from .pipelines import StableDiffusionKDiffusionPipeline, StableDiffusionXLKDiffusionPipeline
|
| 701 |
+
|
| 702 |
+
try:
|
| 703 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 704 |
+
raise OptionalDependencyNotAvailable()
|
| 705 |
+
except OptionalDependencyNotAvailable:
|
| 706 |
+
from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
|
| 707 |
+
else:
|
| 708 |
+
from .pipelines import (
|
| 709 |
+
OnnxStableDiffusionImg2ImgPipeline,
|
| 710 |
+
OnnxStableDiffusionInpaintPipeline,
|
| 711 |
+
OnnxStableDiffusionInpaintPipelineLegacy,
|
| 712 |
+
OnnxStableDiffusionPipeline,
|
| 713 |
+
OnnxStableDiffusionUpscalePipeline,
|
| 714 |
+
StableDiffusionOnnxPipeline,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
try:
|
| 718 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 719 |
+
raise OptionalDependencyNotAvailable()
|
| 720 |
+
except OptionalDependencyNotAvailable:
|
| 721 |
+
from .utils.dummy_torch_and_librosa_objects import * # noqa F403
|
| 722 |
+
else:
|
| 723 |
+
from .pipelines import AudioDiffusionPipeline, Mel
|
| 724 |
+
|
| 725 |
+
try:
|
| 726 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 727 |
+
raise OptionalDependencyNotAvailable()
|
| 728 |
+
except OptionalDependencyNotAvailable:
|
| 729 |
+
from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
|
| 730 |
+
else:
|
| 731 |
+
from .pipelines import SpectrogramDiffusionPipeline
|
| 732 |
+
|
| 733 |
+
try:
|
| 734 |
+
if not is_flax_available():
|
| 735 |
+
raise OptionalDependencyNotAvailable()
|
| 736 |
+
except OptionalDependencyNotAvailable:
|
| 737 |
+
from .utils.dummy_flax_objects import * # noqa F403
|
| 738 |
+
else:
|
| 739 |
+
from .models.controlnet_flax import FlaxControlNetModel
|
| 740 |
+
from .models.modeling_flax_utils import FlaxModelMixin
|
| 741 |
+
from .models.unets.unet_2d_condition_flax import FlaxUNet2DConditionModel
|
| 742 |
+
from .models.vae_flax import FlaxAutoencoderKL
|
| 743 |
+
from .pipelines import FlaxDiffusionPipeline
|
| 744 |
+
from .schedulers import (
|
| 745 |
+
FlaxDDIMScheduler,
|
| 746 |
+
FlaxDDPMScheduler,
|
| 747 |
+
FlaxDPMSolverMultistepScheduler,
|
| 748 |
+
FlaxEulerDiscreteScheduler,
|
| 749 |
+
FlaxKarrasVeScheduler,
|
| 750 |
+
FlaxLMSDiscreteScheduler,
|
| 751 |
+
FlaxPNDMScheduler,
|
| 752 |
+
FlaxSchedulerMixin,
|
| 753 |
+
FlaxScoreSdeVeScheduler,
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
try:
|
| 757 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 758 |
+
raise OptionalDependencyNotAvailable()
|
| 759 |
+
except OptionalDependencyNotAvailable:
|
| 760 |
+
from .utils.dummy_flax_and_transformers_objects import * # noqa F403
|
| 761 |
+
else:
|
| 762 |
+
from .pipelines import (
|
| 763 |
+
FlaxStableDiffusionControlNetPipeline,
|
| 764 |
+
FlaxStableDiffusionImg2ImgPipeline,
|
| 765 |
+
FlaxStableDiffusionInpaintPipeline,
|
| 766 |
+
FlaxStableDiffusionPipeline,
|
| 767 |
+
FlaxStableDiffusionXLPipeline,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
try:
|
| 771 |
+
if not (is_note_seq_available()):
|
| 772 |
+
raise OptionalDependencyNotAvailable()
|
| 773 |
+
except OptionalDependencyNotAvailable:
|
| 774 |
+
from .utils.dummy_note_seq_objects import * # noqa F403
|
| 775 |
+
else:
|
| 776 |
+
from .pipelines import MidiProcessor
|
| 777 |
+
|
| 778 |
+
else:
|
| 779 |
+
import sys
|
| 780 |
+
|
| 781 |
+
sys.modules[__name__] = _LazyModule(
|
| 782 |
+
__name__,
|
| 783 |
+
globals()["__file__"],
|
| 784 |
+
_import_structure,
|
| 785 |
+
module_spec=__spec__,
|
| 786 |
+
extra_objects={"__version__": __version__},
|
| 787 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/configuration_utils.py
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" ConfigMixin base class and utilities."""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import functools
|
| 19 |
+
import importlib
|
| 20 |
+
import inspect
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
from collections import OrderedDict
|
| 25 |
+
from pathlib import PosixPath
|
| 26 |
+
from typing import Any, Dict, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
from huggingface_hub import create_repo, hf_hub_download
|
| 30 |
+
from huggingface_hub.utils import (
|
| 31 |
+
EntryNotFoundError,
|
| 32 |
+
RepositoryNotFoundError,
|
| 33 |
+
RevisionNotFoundError,
|
| 34 |
+
validate_hf_hub_args,
|
| 35 |
+
)
|
| 36 |
+
from requests import HTTPError
|
| 37 |
+
|
| 38 |
+
from . import __version__
|
| 39 |
+
from .utils import (
|
| 40 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
| 41 |
+
DummyObject,
|
| 42 |
+
deprecate,
|
| 43 |
+
extract_commit_hash,
|
| 44 |
+
http_user_agent,
|
| 45 |
+
logging,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
_re_configuration_file = re.compile(r"config\.(.*)\.json")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class FrozenDict(OrderedDict):
|
| 55 |
+
def __init__(self, *args, **kwargs):
|
| 56 |
+
super().__init__(*args, **kwargs)
|
| 57 |
+
|
| 58 |
+
for key, value in self.items():
|
| 59 |
+
setattr(self, key, value)
|
| 60 |
+
|
| 61 |
+
self.__frozen = True
|
| 62 |
+
|
| 63 |
+
def __delitem__(self, *args, **kwargs):
|
| 64 |
+
raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
|
| 65 |
+
|
| 66 |
+
def setdefault(self, *args, **kwargs):
|
| 67 |
+
raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
|
| 68 |
+
|
| 69 |
+
def pop(self, *args, **kwargs):
|
| 70 |
+
raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
|
| 71 |
+
|
| 72 |
+
def update(self, *args, **kwargs):
|
| 73 |
+
raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
|
| 74 |
+
|
| 75 |
+
def __setattr__(self, name, value):
|
| 76 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
| 77 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
| 78 |
+
super().__setattr__(name, value)
|
| 79 |
+
|
| 80 |
+
def __setitem__(self, name, value):
|
| 81 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
| 82 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
| 83 |
+
super().__setitem__(name, value)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ConfigMixin:
|
| 87 |
+
r"""
|
| 88 |
+
Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
|
| 89 |
+
provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
|
| 90 |
+
saving classes that inherit from [`ConfigMixin`].
|
| 91 |
+
|
| 92 |
+
Class attributes:
|
| 93 |
+
- **config_name** (`str`) -- A filename under which the config should stored when calling
|
| 94 |
+
[`~ConfigMixin.save_config`] (should be overridden by parent class).
|
| 95 |
+
- **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
|
| 96 |
+
overridden by subclass).
|
| 97 |
+
- **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
|
| 98 |
+
- **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
|
| 99 |
+
should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
|
| 100 |
+
subclass).
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
config_name = None
|
| 104 |
+
ignore_for_config = []
|
| 105 |
+
has_compatibles = False
|
| 106 |
+
|
| 107 |
+
_deprecated_kwargs = []
|
| 108 |
+
|
| 109 |
+
def register_to_config(self, **kwargs):
|
| 110 |
+
if self.config_name is None:
|
| 111 |
+
raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
|
| 112 |
+
# Special case for `kwargs` used in deprecation warning added to schedulers
|
| 113 |
+
# TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
|
| 114 |
+
# or solve in a more general way.
|
| 115 |
+
kwargs.pop("kwargs", None)
|
| 116 |
+
|
| 117 |
+
if not hasattr(self, "_internal_dict"):
|
| 118 |
+
internal_dict = kwargs
|
| 119 |
+
else:
|
| 120 |
+
previous_dict = dict(self._internal_dict)
|
| 121 |
+
internal_dict = {**self._internal_dict, **kwargs}
|
| 122 |
+
logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
|
| 123 |
+
|
| 124 |
+
self._internal_dict = FrozenDict(internal_dict)
|
| 125 |
+
|
| 126 |
+
def __getattr__(self, name: str) -> Any:
|
| 127 |
+
"""The only reason we overwrite `getattr` here is to gracefully deprecate accessing
|
| 128 |
+
config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
|
| 129 |
+
|
| 130 |
+
This function is mostly copied from PyTorch's __getattr__ overwrite:
|
| 131 |
+
https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
|
| 135 |
+
is_attribute = name in self.__dict__
|
| 136 |
+
|
| 137 |
+
if is_in_config and not is_attribute:
|
| 138 |
+
deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'."
|
| 139 |
+
deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
|
| 140 |
+
return self._internal_dict[name]
|
| 141 |
+
|
| 142 |
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
|
| 143 |
+
|
| 144 |
+
def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
|
| 145 |
+
"""
|
| 146 |
+
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
|
| 147 |
+
[`~ConfigMixin.from_config`] class method.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
save_directory (`str` or `os.PathLike`):
|
| 151 |
+
Directory where the configuration JSON file is saved (will be created if it does not exist).
|
| 152 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 153 |
+
Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
|
| 154 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 155 |
+
namespace).
|
| 156 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 157 |
+
Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 158 |
+
"""
|
| 159 |
+
if os.path.isfile(save_directory):
|
| 160 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 161 |
+
|
| 162 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 163 |
+
|
| 164 |
+
# If we save using the predefined names, we can load using `from_config`
|
| 165 |
+
output_config_file = os.path.join(save_directory, self.config_name)
|
| 166 |
+
|
| 167 |
+
self.to_json_file(output_config_file)
|
| 168 |
+
logger.info(f"Configuration saved in {output_config_file}")
|
| 169 |
+
|
| 170 |
+
if push_to_hub:
|
| 171 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 172 |
+
private = kwargs.pop("private", False)
|
| 173 |
+
create_pr = kwargs.pop("create_pr", False)
|
| 174 |
+
token = kwargs.pop("token", None)
|
| 175 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 176 |
+
repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
|
| 177 |
+
|
| 178 |
+
self._upload_folder(
|
| 179 |
+
save_directory,
|
| 180 |
+
repo_id,
|
| 181 |
+
token=token,
|
| 182 |
+
commit_message=commit_message,
|
| 183 |
+
create_pr=create_pr,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
@classmethod
|
| 187 |
+
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
|
| 188 |
+
r"""
|
| 189 |
+
Instantiate a Python class from a config dictionary.
|
| 190 |
+
|
| 191 |
+
Parameters:
|
| 192 |
+
config (`Dict[str, Any]`):
|
| 193 |
+
A config dictionary from which the Python class is instantiated. Make sure to only load configuration
|
| 194 |
+
files of compatible classes.
|
| 195 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 196 |
+
Whether kwargs that are not consumed by the Python class should be returned or not.
|
| 197 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 198 |
+
Can be used to update the configuration object (after it is loaded) and initiate the Python class.
|
| 199 |
+
`**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
|
| 200 |
+
overwrite the same named arguments in `config`.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
[`ModelMixin`] or [`SchedulerMixin`]:
|
| 204 |
+
A model or scheduler object instantiated from a config dictionary.
|
| 205 |
+
|
| 206 |
+
Examples:
|
| 207 |
+
|
| 208 |
+
```python
|
| 209 |
+
>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
|
| 210 |
+
|
| 211 |
+
>>> # Download scheduler from huggingface.co and cache.
|
| 212 |
+
>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
|
| 213 |
+
|
| 214 |
+
>>> # Instantiate DDIM scheduler class with same config as DDPM
|
| 215 |
+
>>> scheduler = DDIMScheduler.from_config(scheduler.config)
|
| 216 |
+
|
| 217 |
+
>>> # Instantiate PNDM scheduler class with same config as DDPM
|
| 218 |
+
>>> scheduler = PNDMScheduler.from_config(scheduler.config)
|
| 219 |
+
```
|
| 220 |
+
"""
|
| 221 |
+
# <===== TO BE REMOVED WITH DEPRECATION
|
| 222 |
+
# TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
|
| 223 |
+
if "pretrained_model_name_or_path" in kwargs:
|
| 224 |
+
config = kwargs.pop("pretrained_model_name_or_path")
|
| 225 |
+
|
| 226 |
+
if config is None:
|
| 227 |
+
raise ValueError("Please make sure to provide a config as the first positional argument.")
|
| 228 |
+
# ======>
|
| 229 |
+
|
| 230 |
+
if not isinstance(config, dict):
|
| 231 |
+
deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
|
| 232 |
+
if "Scheduler" in cls.__name__:
|
| 233 |
+
deprecation_message += (
|
| 234 |
+
f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
|
| 235 |
+
" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
|
| 236 |
+
" be removed in v1.0.0."
|
| 237 |
+
)
|
| 238 |
+
elif "Model" in cls.__name__:
|
| 239 |
+
deprecation_message += (
|
| 240 |
+
f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
|
| 241 |
+
f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
|
| 242 |
+
" instead. This functionality will be removed in v1.0.0."
|
| 243 |
+
)
|
| 244 |
+
deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
|
| 245 |
+
config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
|
| 246 |
+
|
| 247 |
+
init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
|
| 248 |
+
|
| 249 |
+
# Allow dtype to be specified on initialization
|
| 250 |
+
if "dtype" in unused_kwargs:
|
| 251 |
+
init_dict["dtype"] = unused_kwargs.pop("dtype")
|
| 252 |
+
|
| 253 |
+
# add possible deprecated kwargs
|
| 254 |
+
for deprecated_kwarg in cls._deprecated_kwargs:
|
| 255 |
+
if deprecated_kwarg in unused_kwargs:
|
| 256 |
+
init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
|
| 257 |
+
|
| 258 |
+
# Return model and optionally state and/or unused_kwargs
|
| 259 |
+
model = cls(**init_dict)
|
| 260 |
+
|
| 261 |
+
# make sure to also save config parameters that might be used for compatible classes
|
| 262 |
+
# update _class_name
|
| 263 |
+
if "_class_name" in hidden_dict:
|
| 264 |
+
hidden_dict["_class_name"] = cls.__name__
|
| 265 |
+
|
| 266 |
+
model.register_to_config(**hidden_dict)
|
| 267 |
+
|
| 268 |
+
# add hidden kwargs of compatible classes to unused_kwargs
|
| 269 |
+
unused_kwargs = {**unused_kwargs, **hidden_dict}
|
| 270 |
+
|
| 271 |
+
if return_unused_kwargs:
|
| 272 |
+
return (model, unused_kwargs)
|
| 273 |
+
else:
|
| 274 |
+
return model
|
| 275 |
+
|
| 276 |
+
@classmethod
|
| 277 |
+
def get_config_dict(cls, *args, **kwargs):
|
| 278 |
+
deprecation_message = (
|
| 279 |
+
f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
|
| 280 |
+
" removed in version v1.0.0"
|
| 281 |
+
)
|
| 282 |
+
deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
|
| 283 |
+
return cls.load_config(*args, **kwargs)
|
| 284 |
+
|
| 285 |
+
@classmethod
|
| 286 |
+
@validate_hf_hub_args
|
| 287 |
+
def load_config(
|
| 288 |
+
cls,
|
| 289 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 290 |
+
return_unused_kwargs=False,
|
| 291 |
+
return_commit_hash=False,
|
| 292 |
+
**kwargs,
|
| 293 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
| 294 |
+
r"""
|
| 295 |
+
Load a model or scheduler configuration.
|
| 296 |
+
|
| 297 |
+
Parameters:
|
| 298 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
| 299 |
+
Can be either:
|
| 300 |
+
|
| 301 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
| 302 |
+
the Hub.
|
| 303 |
+
- A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
|
| 304 |
+
[`~ConfigMixin.save_config`].
|
| 305 |
+
|
| 306 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 307 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 308 |
+
is not used.
|
| 309 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 310 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 311 |
+
cached versions if they exist.
|
| 312 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 313 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 314 |
+
incompletely downloaded files are deleted.
|
| 315 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 316 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 317 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 318 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 319 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 320 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 321 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 322 |
+
won't be downloaded from the Hub.
|
| 323 |
+
token (`str` or *bool*, *optional*):
|
| 324 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 325 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 326 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 327 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 328 |
+
allowed by Git.
|
| 329 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 330 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 331 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False):
|
| 332 |
+
Whether unused keyword arguments of the config are returned.
|
| 333 |
+
return_commit_hash (`bool`, *optional*, defaults to `False):
|
| 334 |
+
Whether the `commit_hash` of the loaded configuration are returned.
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
`dict`:
|
| 338 |
+
A dictionary of all the parameters stored in a JSON configuration file.
|
| 339 |
+
|
| 340 |
+
"""
|
| 341 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 342 |
+
force_download = kwargs.pop("force_download", False)
|
| 343 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 344 |
+
proxies = kwargs.pop("proxies", None)
|
| 345 |
+
token = kwargs.pop("token", None)
|
| 346 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 347 |
+
revision = kwargs.pop("revision", None)
|
| 348 |
+
_ = kwargs.pop("mirror", None)
|
| 349 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 350 |
+
user_agent = kwargs.pop("user_agent", {})
|
| 351 |
+
|
| 352 |
+
user_agent = {**user_agent, "file_type": "config"}
|
| 353 |
+
user_agent = http_user_agent(user_agent)
|
| 354 |
+
|
| 355 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 356 |
+
|
| 357 |
+
if cls.config_name is None:
|
| 358 |
+
raise ValueError(
|
| 359 |
+
"`self.config_name` is not defined. Note that one should not load a config from "
|
| 360 |
+
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
| 364 |
+
config_file = pretrained_model_name_or_path
|
| 365 |
+
elif os.path.isdir(pretrained_model_name_or_path):
|
| 366 |
+
if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
|
| 367 |
+
# Load from a PyTorch checkpoint
|
| 368 |
+
config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
|
| 369 |
+
elif subfolder is not None and os.path.isfile(
|
| 370 |
+
os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
| 371 |
+
):
|
| 372 |
+
config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
| 373 |
+
else:
|
| 374 |
+
raise EnvironmentError(
|
| 375 |
+
f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
|
| 376 |
+
)
|
| 377 |
+
else:
|
| 378 |
+
try:
|
| 379 |
+
# Load from URL or cache if already cached
|
| 380 |
+
config_file = hf_hub_download(
|
| 381 |
+
pretrained_model_name_or_path,
|
| 382 |
+
filename=cls.config_name,
|
| 383 |
+
cache_dir=cache_dir,
|
| 384 |
+
force_download=force_download,
|
| 385 |
+
proxies=proxies,
|
| 386 |
+
resume_download=resume_download,
|
| 387 |
+
local_files_only=local_files_only,
|
| 388 |
+
token=token,
|
| 389 |
+
user_agent=user_agent,
|
| 390 |
+
subfolder=subfolder,
|
| 391 |
+
revision=revision,
|
| 392 |
+
)
|
| 393 |
+
except RepositoryNotFoundError:
|
| 394 |
+
raise EnvironmentError(
|
| 395 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
|
| 396 |
+
" listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
|
| 397 |
+
" token having permission to this repo with `token` or log in with `huggingface-cli login`."
|
| 398 |
+
)
|
| 399 |
+
except RevisionNotFoundError:
|
| 400 |
+
raise EnvironmentError(
|
| 401 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
|
| 402 |
+
" this model name. Check the model page at"
|
| 403 |
+
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
| 404 |
+
)
|
| 405 |
+
except EntryNotFoundError:
|
| 406 |
+
raise EnvironmentError(
|
| 407 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
|
| 408 |
+
)
|
| 409 |
+
except HTTPError as err:
|
| 410 |
+
raise EnvironmentError(
|
| 411 |
+
"There was a specific connection error when trying to load"
|
| 412 |
+
f" {pretrained_model_name_or_path}:\n{err}"
|
| 413 |
+
)
|
| 414 |
+
except ValueError:
|
| 415 |
+
raise EnvironmentError(
|
| 416 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
| 417 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
| 418 |
+
f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
|
| 419 |
+
" run the library in offline mode at"
|
| 420 |
+
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
|
| 421 |
+
)
|
| 422 |
+
except EnvironmentError:
|
| 423 |
+
raise EnvironmentError(
|
| 424 |
+
f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
| 425 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
| 426 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
| 427 |
+
f"containing a {cls.config_name} file"
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
try:
|
| 431 |
+
# Load config dict
|
| 432 |
+
config_dict = cls._dict_from_json_file(config_file)
|
| 433 |
+
|
| 434 |
+
commit_hash = extract_commit_hash(config_file)
|
| 435 |
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
| 436 |
+
raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
|
| 437 |
+
|
| 438 |
+
if not (return_unused_kwargs or return_commit_hash):
|
| 439 |
+
return config_dict
|
| 440 |
+
|
| 441 |
+
outputs = (config_dict,)
|
| 442 |
+
|
| 443 |
+
if return_unused_kwargs:
|
| 444 |
+
outputs += (kwargs,)
|
| 445 |
+
|
| 446 |
+
if return_commit_hash:
|
| 447 |
+
outputs += (commit_hash,)
|
| 448 |
+
|
| 449 |
+
return outputs
|
| 450 |
+
|
| 451 |
+
@staticmethod
|
| 452 |
+
def _get_init_keys(cls):
|
| 453 |
+
return set(dict(inspect.signature(cls.__init__).parameters).keys())
|
| 454 |
+
|
| 455 |
+
@classmethod
|
| 456 |
+
def extract_init_dict(cls, config_dict, **kwargs):
|
| 457 |
+
# Skip keys that were not present in the original config, so default __init__ values were used
|
| 458 |
+
used_defaults = config_dict.get("_use_default_values", [])
|
| 459 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
|
| 460 |
+
|
| 461 |
+
# 0. Copy origin config dict
|
| 462 |
+
original_dict = dict(config_dict.items())
|
| 463 |
+
|
| 464 |
+
# 1. Retrieve expected config attributes from __init__ signature
|
| 465 |
+
expected_keys = cls._get_init_keys(cls)
|
| 466 |
+
expected_keys.remove("self")
|
| 467 |
+
# remove general kwargs if present in dict
|
| 468 |
+
if "kwargs" in expected_keys:
|
| 469 |
+
expected_keys.remove("kwargs")
|
| 470 |
+
# remove flax internal keys
|
| 471 |
+
if hasattr(cls, "_flax_internal_args"):
|
| 472 |
+
for arg in cls._flax_internal_args:
|
| 473 |
+
expected_keys.remove(arg)
|
| 474 |
+
|
| 475 |
+
# 2. Remove attributes that cannot be expected from expected config attributes
|
| 476 |
+
# remove keys to be ignored
|
| 477 |
+
if len(cls.ignore_for_config) > 0:
|
| 478 |
+
expected_keys = expected_keys - set(cls.ignore_for_config)
|
| 479 |
+
|
| 480 |
+
# load diffusers library to import compatible and original scheduler
|
| 481 |
+
diffusers_library = importlib.import_module(__name__.split(".")[0])
|
| 482 |
+
|
| 483 |
+
if cls.has_compatibles:
|
| 484 |
+
compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
|
| 485 |
+
else:
|
| 486 |
+
compatible_classes = []
|
| 487 |
+
|
| 488 |
+
expected_keys_comp_cls = set()
|
| 489 |
+
for c in compatible_classes:
|
| 490 |
+
expected_keys_c = cls._get_init_keys(c)
|
| 491 |
+
expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
|
| 492 |
+
expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
|
| 493 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
|
| 494 |
+
|
| 495 |
+
# remove attributes from orig class that cannot be expected
|
| 496 |
+
orig_cls_name = config_dict.pop("_class_name", cls.__name__)
|
| 497 |
+
if (
|
| 498 |
+
isinstance(orig_cls_name, str)
|
| 499 |
+
and orig_cls_name != cls.__name__
|
| 500 |
+
and hasattr(diffusers_library, orig_cls_name)
|
| 501 |
+
):
|
| 502 |
+
orig_cls = getattr(diffusers_library, orig_cls_name)
|
| 503 |
+
unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
|
| 504 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
|
| 505 |
+
elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
|
| 506 |
+
raise ValueError(
|
| 507 |
+
"Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# remove private attributes
|
| 511 |
+
config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
|
| 512 |
+
|
| 513 |
+
# 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
|
| 514 |
+
init_dict = {}
|
| 515 |
+
for key in expected_keys:
|
| 516 |
+
# if config param is passed to kwarg and is present in config dict
|
| 517 |
+
# it should overwrite existing config dict key
|
| 518 |
+
if key in kwargs and key in config_dict:
|
| 519 |
+
config_dict[key] = kwargs.pop(key)
|
| 520 |
+
|
| 521 |
+
if key in kwargs:
|
| 522 |
+
# overwrite key
|
| 523 |
+
init_dict[key] = kwargs.pop(key)
|
| 524 |
+
elif key in config_dict:
|
| 525 |
+
# use value from config dict
|
| 526 |
+
init_dict[key] = config_dict.pop(key)
|
| 527 |
+
|
| 528 |
+
# 4. Give nice warning if unexpected values have been passed
|
| 529 |
+
if len(config_dict) > 0:
|
| 530 |
+
logger.warning(
|
| 531 |
+
f"The config attributes {config_dict} were passed to {cls.__name__}, "
|
| 532 |
+
"but are not expected and will be ignored. Please verify your "
|
| 533 |
+
f"{cls.config_name} configuration file."
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
# 5. Give nice info if config attributes are initialized to default because they have not been passed
|
| 537 |
+
passed_keys = set(init_dict.keys())
|
| 538 |
+
if len(expected_keys - passed_keys) > 0:
|
| 539 |
+
logger.info(
|
| 540 |
+
f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
# 6. Define unused keyword arguments
|
| 544 |
+
unused_kwargs = {**config_dict, **kwargs}
|
| 545 |
+
|
| 546 |
+
# 7. Define "hidden" config parameters that were saved for compatible classes
|
| 547 |
+
hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
|
| 548 |
+
|
| 549 |
+
return init_dict, unused_kwargs, hidden_config_dict
|
| 550 |
+
|
| 551 |
+
@classmethod
|
| 552 |
+
def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
|
| 553 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
| 554 |
+
text = reader.read()
|
| 555 |
+
return json.loads(text)
|
| 556 |
+
|
| 557 |
+
def __repr__(self):
|
| 558 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
| 559 |
+
|
| 560 |
+
@property
|
| 561 |
+
def config(self) -> Dict[str, Any]:
|
| 562 |
+
"""
|
| 563 |
+
Returns the config of the class as a frozen dictionary
|
| 564 |
+
|
| 565 |
+
Returns:
|
| 566 |
+
`Dict[str, Any]`: Config of the class.
|
| 567 |
+
"""
|
| 568 |
+
return self._internal_dict
|
| 569 |
+
|
| 570 |
+
def to_json_string(self) -> str:
|
| 571 |
+
"""
|
| 572 |
+
Serializes the configuration instance to a JSON string.
|
| 573 |
+
|
| 574 |
+
Returns:
|
| 575 |
+
`str`:
|
| 576 |
+
String containing all the attributes that make up the configuration instance in JSON format.
|
| 577 |
+
"""
|
| 578 |
+
config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
|
| 579 |
+
config_dict["_class_name"] = self.__class__.__name__
|
| 580 |
+
config_dict["_diffusers_version"] = __version__
|
| 581 |
+
|
| 582 |
+
def to_json_saveable(value):
|
| 583 |
+
if isinstance(value, np.ndarray):
|
| 584 |
+
value = value.tolist()
|
| 585 |
+
elif isinstance(value, PosixPath):
|
| 586 |
+
value = str(value)
|
| 587 |
+
return value
|
| 588 |
+
|
| 589 |
+
config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
|
| 590 |
+
# Don't save "_ignore_files" or "_use_default_values"
|
| 591 |
+
config_dict.pop("_ignore_files", None)
|
| 592 |
+
config_dict.pop("_use_default_values", None)
|
| 593 |
+
|
| 594 |
+
return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
| 595 |
+
|
| 596 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
| 597 |
+
"""
|
| 598 |
+
Save the configuration instance's parameters to a JSON file.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
json_file_path (`str` or `os.PathLike`):
|
| 602 |
+
Path to the JSON file to save a configuration instance's parameters.
|
| 603 |
+
"""
|
| 604 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 605 |
+
writer.write(self.to_json_string())
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def register_to_config(init):
|
| 609 |
+
r"""
|
| 610 |
+
Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
|
| 611 |
+
automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
|
| 612 |
+
shouldn't be registered in the config, use the `ignore_for_config` class variable
|
| 613 |
+
|
| 614 |
+
Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
|
| 615 |
+
"""
|
| 616 |
+
|
| 617 |
+
@functools.wraps(init)
|
| 618 |
+
def inner_init(self, *args, **kwargs):
|
| 619 |
+
# Ignore private kwargs in the init.
|
| 620 |
+
init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
|
| 621 |
+
config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
|
| 622 |
+
if not isinstance(self, ConfigMixin):
|
| 623 |
+
raise RuntimeError(
|
| 624 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
| 625 |
+
"not inherit from `ConfigMixin`."
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
ignore = getattr(self, "ignore_for_config", [])
|
| 629 |
+
# Get positional arguments aligned with kwargs
|
| 630 |
+
new_kwargs = {}
|
| 631 |
+
signature = inspect.signature(init)
|
| 632 |
+
parameters = {
|
| 633 |
+
name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
|
| 634 |
+
}
|
| 635 |
+
for arg, name in zip(args, parameters.keys()):
|
| 636 |
+
new_kwargs[name] = arg
|
| 637 |
+
|
| 638 |
+
# Then add all kwargs
|
| 639 |
+
new_kwargs.update(
|
| 640 |
+
{
|
| 641 |
+
k: init_kwargs.get(k, default)
|
| 642 |
+
for k, default in parameters.items()
|
| 643 |
+
if k not in ignore and k not in new_kwargs
|
| 644 |
+
}
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
# Take note of the parameters that were not present in the loaded config
|
| 648 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
| 649 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
| 650 |
+
|
| 651 |
+
new_kwargs = {**config_init_kwargs, **new_kwargs}
|
| 652 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
| 653 |
+
init(self, *args, **init_kwargs)
|
| 654 |
+
|
| 655 |
+
return inner_init
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def flax_register_to_config(cls):
|
| 659 |
+
original_init = cls.__init__
|
| 660 |
+
|
| 661 |
+
@functools.wraps(original_init)
|
| 662 |
+
def init(self, *args, **kwargs):
|
| 663 |
+
if not isinstance(self, ConfigMixin):
|
| 664 |
+
raise RuntimeError(
|
| 665 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
| 666 |
+
"not inherit from `ConfigMixin`."
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
# Ignore private kwargs in the init. Retrieve all passed attributes
|
| 670 |
+
init_kwargs = dict(kwargs.items())
|
| 671 |
+
|
| 672 |
+
# Retrieve default values
|
| 673 |
+
fields = dataclasses.fields(self)
|
| 674 |
+
default_kwargs = {}
|
| 675 |
+
for field in fields:
|
| 676 |
+
# ignore flax specific attributes
|
| 677 |
+
if field.name in self._flax_internal_args:
|
| 678 |
+
continue
|
| 679 |
+
if type(field.default) == dataclasses._MISSING_TYPE:
|
| 680 |
+
default_kwargs[field.name] = None
|
| 681 |
+
else:
|
| 682 |
+
default_kwargs[field.name] = getattr(self, field.name)
|
| 683 |
+
|
| 684 |
+
# Make sure init_kwargs override default kwargs
|
| 685 |
+
new_kwargs = {**default_kwargs, **init_kwargs}
|
| 686 |
+
# dtype should be part of `init_kwargs`, but not `new_kwargs`
|
| 687 |
+
if "dtype" in new_kwargs:
|
| 688 |
+
new_kwargs.pop("dtype")
|
| 689 |
+
|
| 690 |
+
# Get positional arguments aligned with kwargs
|
| 691 |
+
for i, arg in enumerate(args):
|
| 692 |
+
name = fields[i].name
|
| 693 |
+
new_kwargs[name] = arg
|
| 694 |
+
|
| 695 |
+
# Take note of the parameters that were not present in the loaded config
|
| 696 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
| 697 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
| 698 |
+
|
| 699 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
| 700 |
+
original_init(self, *args, **kwargs)
|
| 701 |
+
|
| 702 |
+
cls.__init__ = init
|
| 703 |
+
return cls
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/dependency_versions_check.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .dependency_versions_table import deps
|
| 16 |
+
from .utils.versions import require_version, require_version_core
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# define which module versions we always want to check at run time
|
| 20 |
+
# (usually the ones defined in `install_requires` in setup.py)
|
| 21 |
+
#
|
| 22 |
+
# order specific notes:
|
| 23 |
+
# - tqdm must be checked before tokenizers
|
| 24 |
+
|
| 25 |
+
pkgs_to_check_at_runtime = "python requests filelock numpy".split()
|
| 26 |
+
for pkg in pkgs_to_check_at_runtime:
|
| 27 |
+
if pkg in deps:
|
| 28 |
+
require_version_core(deps[pkg])
|
| 29 |
+
else:
|
| 30 |
+
raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def dep_version_check(pkg, hint=None):
|
| 34 |
+
require_version(deps[pkg], hint)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/dependency_versions_table.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# THIS FILE HAS BEEN AUTOGENERATED. To update:
|
| 2 |
+
# 1. modify the `_deps` dict in setup.py
|
| 3 |
+
# 2. run `make deps_table_update`
|
| 4 |
+
deps = {
|
| 5 |
+
"Pillow": "Pillow",
|
| 6 |
+
"accelerate": "accelerate>=0.11.0",
|
| 7 |
+
"compel": "compel==0.1.8",
|
| 8 |
+
"datasets": "datasets",
|
| 9 |
+
"filelock": "filelock",
|
| 10 |
+
"flax": "flax>=0.4.1",
|
| 11 |
+
"hf-doc-builder": "hf-doc-builder>=0.3.0",
|
| 12 |
+
"huggingface-hub": "huggingface-hub>=0.20.2",
|
| 13 |
+
"requests-mock": "requests-mock==1.10.0",
|
| 14 |
+
"importlib_metadata": "importlib_metadata",
|
| 15 |
+
"invisible-watermark": "invisible-watermark>=0.2.0",
|
| 16 |
+
"isort": "isort>=5.5.4",
|
| 17 |
+
"jax": "jax>=0.4.1",
|
| 18 |
+
"jaxlib": "jaxlib>=0.4.1",
|
| 19 |
+
"Jinja2": "Jinja2",
|
| 20 |
+
"k-diffusion": "k-diffusion>=0.0.12",
|
| 21 |
+
"torchsde": "torchsde",
|
| 22 |
+
"note_seq": "note_seq",
|
| 23 |
+
"librosa": "librosa",
|
| 24 |
+
"numpy": "numpy",
|
| 25 |
+
"parameterized": "parameterized",
|
| 26 |
+
"peft": "peft>=0.6.0",
|
| 27 |
+
"protobuf": "protobuf>=3.20.3,<4",
|
| 28 |
+
"pytest": "pytest",
|
| 29 |
+
"pytest-timeout": "pytest-timeout",
|
| 30 |
+
"pytest-xdist": "pytest-xdist",
|
| 31 |
+
"python": "python>=3.8.0",
|
| 32 |
+
"ruff": "ruff==0.1.5",
|
| 33 |
+
"safetensors": "safetensors>=0.3.1",
|
| 34 |
+
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
|
| 35 |
+
"GitPython": "GitPython<3.1.19",
|
| 36 |
+
"scipy": "scipy",
|
| 37 |
+
"onnx": "onnx",
|
| 38 |
+
"regex": "regex!=2019.12.17",
|
| 39 |
+
"requests": "requests",
|
| 40 |
+
"tensorboard": "tensorboard",
|
| 41 |
+
"torch": "torch>=1.4",
|
| 42 |
+
"torchvision": "torchvision",
|
| 43 |
+
"transformers": "transformers>=4.25.1",
|
| 44 |
+
"urllib3": "urllib3<=2.0.0",
|
| 45 |
+
}
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/image_processor.py
ADDED
|
@@ -0,0 +1,990 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
import warnings
|
| 17 |
+
from typing import List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import PIL.Image
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from PIL import Image, ImageFilter, ImageOps
|
| 24 |
+
|
| 25 |
+
from .configuration_utils import ConfigMixin, register_to_config
|
| 26 |
+
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
PipelineImageInput = Union[
|
| 30 |
+
PIL.Image.Image,
|
| 31 |
+
np.ndarray,
|
| 32 |
+
torch.FloatTensor,
|
| 33 |
+
List[PIL.Image.Image],
|
| 34 |
+
List[np.ndarray],
|
| 35 |
+
List[torch.FloatTensor],
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
PipelineDepthInput = PipelineImageInput
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class VaeImageProcessor(ConfigMixin):
|
| 42 |
+
"""
|
| 43 |
+
Image processor for VAE.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 47 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
|
| 48 |
+
`height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
|
| 49 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
| 50 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
| 51 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
| 52 |
+
Resampling filter to use when resizing the image.
|
| 53 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 54 |
+
Whether to normalize the image to [-1,1].
|
| 55 |
+
do_binarize (`bool`, *optional*, defaults to `False`):
|
| 56 |
+
Whether to binarize the image to 0/1.
|
| 57 |
+
do_convert_rgb (`bool`, *optional*, defaults to be `False`):
|
| 58 |
+
Whether to convert the images to RGB format.
|
| 59 |
+
do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
|
| 60 |
+
Whether to convert the images to grayscale format.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
config_name = CONFIG_NAME
|
| 64 |
+
|
| 65 |
+
@register_to_config
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
do_resize: bool = True,
|
| 69 |
+
vae_scale_factor: int = 8,
|
| 70 |
+
resample: str = "lanczos",
|
| 71 |
+
do_normalize: bool = True,
|
| 72 |
+
do_binarize: bool = False,
|
| 73 |
+
do_convert_rgb: bool = False,
|
| 74 |
+
do_convert_grayscale: bool = False,
|
| 75 |
+
):
|
| 76 |
+
super().__init__()
|
| 77 |
+
if do_convert_rgb and do_convert_grayscale:
|
| 78 |
+
raise ValueError(
|
| 79 |
+
"`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
|
| 80 |
+
" if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
|
| 81 |
+
" if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
|
| 82 |
+
)
|
| 83 |
+
self.config.do_convert_rgb = False
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
|
| 87 |
+
"""
|
| 88 |
+
Convert a numpy image or a batch of images to a PIL image.
|
| 89 |
+
"""
|
| 90 |
+
if images.ndim == 3:
|
| 91 |
+
images = images[None, ...]
|
| 92 |
+
images = (images * 255).round().astype("uint8")
|
| 93 |
+
if images.shape[-1] == 1:
|
| 94 |
+
# special case for grayscale (single channel) images
|
| 95 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 96 |
+
else:
|
| 97 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 98 |
+
|
| 99 |
+
return pil_images
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
| 103 |
+
"""
|
| 104 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
| 105 |
+
"""
|
| 106 |
+
if not isinstance(images, list):
|
| 107 |
+
images = [images]
|
| 108 |
+
images = [np.array(image).astype(np.float32) / 255.0 for image in images]
|
| 109 |
+
images = np.stack(images, axis=0)
|
| 110 |
+
|
| 111 |
+
return images
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
|
| 115 |
+
"""
|
| 116 |
+
Convert a NumPy image to a PyTorch tensor.
|
| 117 |
+
"""
|
| 118 |
+
if images.ndim == 3:
|
| 119 |
+
images = images[..., None]
|
| 120 |
+
|
| 121 |
+
images = torch.from_numpy(images.transpose(0, 3, 1, 2))
|
| 122 |
+
return images
|
| 123 |
+
|
| 124 |
+
@staticmethod
|
| 125 |
+
def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
|
| 126 |
+
"""
|
| 127 |
+
Convert a PyTorch tensor to a NumPy image.
|
| 128 |
+
"""
|
| 129 |
+
images = images.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 130 |
+
return images
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 134 |
+
"""
|
| 135 |
+
Normalize an image array to [-1,1].
|
| 136 |
+
"""
|
| 137 |
+
return 2.0 * images - 1.0
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 141 |
+
"""
|
| 142 |
+
Denormalize an image array to [0,1].
|
| 143 |
+
"""
|
| 144 |
+
return (images / 2 + 0.5).clamp(0, 1)
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
|
| 148 |
+
"""
|
| 149 |
+
Converts a PIL image to RGB format.
|
| 150 |
+
"""
|
| 151 |
+
image = image.convert("RGB")
|
| 152 |
+
|
| 153 |
+
return image
|
| 154 |
+
|
| 155 |
+
@staticmethod
|
| 156 |
+
def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
|
| 157 |
+
"""
|
| 158 |
+
Converts a PIL image to grayscale format.
|
| 159 |
+
"""
|
| 160 |
+
image = image.convert("L")
|
| 161 |
+
|
| 162 |
+
return image
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
|
| 166 |
+
"""
|
| 167 |
+
Applies Gaussian blur to an image.
|
| 168 |
+
"""
|
| 169 |
+
image = image.filter(ImageFilter.GaussianBlur(blur_factor))
|
| 170 |
+
|
| 171 |
+
return image
|
| 172 |
+
|
| 173 |
+
@staticmethod
|
| 174 |
+
def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
|
| 175 |
+
"""
|
| 176 |
+
Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect ratio of the original image;
|
| 177 |
+
for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
mask_image (PIL.Image.Image): Mask image.
|
| 181 |
+
width (int): Width of the image to be processed.
|
| 182 |
+
height (int): Height of the image to be processed.
|
| 183 |
+
pad (int, optional): Padding to be added to the crop region. Defaults to 0.
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and matches the original aspect ratio.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
mask_image = mask_image.convert("L")
|
| 190 |
+
mask = np.array(mask_image)
|
| 191 |
+
|
| 192 |
+
# 1. find a rectangular region that contains all masked ares in an image
|
| 193 |
+
h, w = mask.shape
|
| 194 |
+
crop_left = 0
|
| 195 |
+
for i in range(w):
|
| 196 |
+
if not (mask[:, i] == 0).all():
|
| 197 |
+
break
|
| 198 |
+
crop_left += 1
|
| 199 |
+
|
| 200 |
+
crop_right = 0
|
| 201 |
+
for i in reversed(range(w)):
|
| 202 |
+
if not (mask[:, i] == 0).all():
|
| 203 |
+
break
|
| 204 |
+
crop_right += 1
|
| 205 |
+
|
| 206 |
+
crop_top = 0
|
| 207 |
+
for i in range(h):
|
| 208 |
+
if not (mask[i] == 0).all():
|
| 209 |
+
break
|
| 210 |
+
crop_top += 1
|
| 211 |
+
|
| 212 |
+
crop_bottom = 0
|
| 213 |
+
for i in reversed(range(h)):
|
| 214 |
+
if not (mask[i] == 0).all():
|
| 215 |
+
break
|
| 216 |
+
crop_bottom += 1
|
| 217 |
+
|
| 218 |
+
# 2. add padding to the crop region
|
| 219 |
+
x1, y1, x2, y2 = (
|
| 220 |
+
int(max(crop_left - pad, 0)),
|
| 221 |
+
int(max(crop_top - pad, 0)),
|
| 222 |
+
int(min(w - crop_right + pad, w)),
|
| 223 |
+
int(min(h - crop_bottom + pad, h)),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# 3. expands crop region to match the aspect ratio of the image to be processed
|
| 227 |
+
ratio_crop_region = (x2 - x1) / (y2 - y1)
|
| 228 |
+
ratio_processing = width / height
|
| 229 |
+
|
| 230 |
+
if ratio_crop_region > ratio_processing:
|
| 231 |
+
desired_height = (x2 - x1) / ratio_processing
|
| 232 |
+
desired_height_diff = int(desired_height - (y2 - y1))
|
| 233 |
+
y1 -= desired_height_diff // 2
|
| 234 |
+
y2 += desired_height_diff - desired_height_diff // 2
|
| 235 |
+
if y2 >= mask_image.height:
|
| 236 |
+
diff = y2 - mask_image.height
|
| 237 |
+
y2 -= diff
|
| 238 |
+
y1 -= diff
|
| 239 |
+
if y1 < 0:
|
| 240 |
+
y2 -= y1
|
| 241 |
+
y1 -= y1
|
| 242 |
+
if y2 >= mask_image.height:
|
| 243 |
+
y2 = mask_image.height
|
| 244 |
+
else:
|
| 245 |
+
desired_width = (y2 - y1) * ratio_processing
|
| 246 |
+
desired_width_diff = int(desired_width - (x2 - x1))
|
| 247 |
+
x1 -= desired_width_diff // 2
|
| 248 |
+
x2 += desired_width_diff - desired_width_diff // 2
|
| 249 |
+
if x2 >= mask_image.width:
|
| 250 |
+
diff = x2 - mask_image.width
|
| 251 |
+
x2 -= diff
|
| 252 |
+
x1 -= diff
|
| 253 |
+
if x1 < 0:
|
| 254 |
+
x2 -= x1
|
| 255 |
+
x1 -= x1
|
| 256 |
+
if x2 >= mask_image.width:
|
| 257 |
+
x2 = mask_image.width
|
| 258 |
+
|
| 259 |
+
return x1, y1, x2, y2
|
| 260 |
+
|
| 261 |
+
def _resize_and_fill(
|
| 262 |
+
self,
|
| 263 |
+
image: PIL.Image.Image,
|
| 264 |
+
width: int,
|
| 265 |
+
height: int,
|
| 266 |
+
) -> PIL.Image.Image:
|
| 267 |
+
"""
|
| 268 |
+
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
image: The image to resize.
|
| 272 |
+
width: The width to resize the image to.
|
| 273 |
+
height: The height to resize the image to.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
ratio = width / height
|
| 277 |
+
src_ratio = image.width / image.height
|
| 278 |
+
|
| 279 |
+
src_w = width if ratio < src_ratio else image.width * height // image.height
|
| 280 |
+
src_h = height if ratio >= src_ratio else image.height * width // image.width
|
| 281 |
+
|
| 282 |
+
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
|
| 283 |
+
res = Image.new("RGB", (width, height))
|
| 284 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
| 285 |
+
|
| 286 |
+
if ratio < src_ratio:
|
| 287 |
+
fill_height = height // 2 - src_h // 2
|
| 288 |
+
if fill_height > 0:
|
| 289 |
+
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
|
| 290 |
+
res.paste(
|
| 291 |
+
resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
|
| 292 |
+
box=(0, fill_height + src_h),
|
| 293 |
+
)
|
| 294 |
+
elif ratio > src_ratio:
|
| 295 |
+
fill_width = width // 2 - src_w // 2
|
| 296 |
+
if fill_width > 0:
|
| 297 |
+
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
|
| 298 |
+
res.paste(
|
| 299 |
+
resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
|
| 300 |
+
box=(fill_width + src_w, 0),
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
return res
|
| 304 |
+
|
| 305 |
+
def _resize_and_crop(
|
| 306 |
+
self,
|
| 307 |
+
image: PIL.Image.Image,
|
| 308 |
+
width: int,
|
| 309 |
+
height: int,
|
| 310 |
+
) -> PIL.Image.Image:
|
| 311 |
+
"""
|
| 312 |
+
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
image: The image to resize.
|
| 316 |
+
width: The width to resize the image to.
|
| 317 |
+
height: The height to resize the image to.
|
| 318 |
+
"""
|
| 319 |
+
ratio = width / height
|
| 320 |
+
src_ratio = image.width / image.height
|
| 321 |
+
|
| 322 |
+
src_w = width if ratio > src_ratio else image.width * height // image.height
|
| 323 |
+
src_h = height if ratio <= src_ratio else image.height * width // image.width
|
| 324 |
+
|
| 325 |
+
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
|
| 326 |
+
res = Image.new("RGB", (width, height))
|
| 327 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
| 328 |
+
return res
|
| 329 |
+
|
| 330 |
+
def resize(
|
| 331 |
+
self,
|
| 332 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
| 333 |
+
height: int,
|
| 334 |
+
width: int,
|
| 335 |
+
resize_mode: str = "default", # "default", "fill", "crop"
|
| 336 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
|
| 337 |
+
"""
|
| 338 |
+
Resize image.
|
| 339 |
+
|
| 340 |
+
Args:
|
| 341 |
+
image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
| 342 |
+
The image input, can be a PIL image, numpy array or pytorch tensor.
|
| 343 |
+
height (`int`):
|
| 344 |
+
The height to resize to.
|
| 345 |
+
width (`int`):
|
| 346 |
+
The width to resize to.
|
| 347 |
+
resize_mode (`str`, *optional*, defaults to `default`):
|
| 348 |
+
The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
|
| 349 |
+
within the specified width and height, and it may not maintaining the original aspect ratio.
|
| 350 |
+
If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 351 |
+
within the dimensions, filling empty with data from image.
|
| 352 |
+
If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 353 |
+
within the dimensions, cropping the excess.
|
| 354 |
+
Note that resize_mode `fill` and `crop` are only supported for PIL image input.
|
| 355 |
+
|
| 356 |
+
Returns:
|
| 357 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
|
| 358 |
+
The resized image.
|
| 359 |
+
"""
|
| 360 |
+
if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
|
| 361 |
+
raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
|
| 362 |
+
if isinstance(image, PIL.Image.Image):
|
| 363 |
+
if resize_mode == "default":
|
| 364 |
+
image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
|
| 365 |
+
elif resize_mode == "fill":
|
| 366 |
+
image = self._resize_and_fill(image, width, height)
|
| 367 |
+
elif resize_mode == "crop":
|
| 368 |
+
image = self._resize_and_crop(image, width, height)
|
| 369 |
+
else:
|
| 370 |
+
raise ValueError(f"resize_mode {resize_mode} is not supported")
|
| 371 |
+
|
| 372 |
+
elif isinstance(image, torch.Tensor):
|
| 373 |
+
image = torch.nn.functional.interpolate(
|
| 374 |
+
image,
|
| 375 |
+
size=(height, width),
|
| 376 |
+
)
|
| 377 |
+
elif isinstance(image, np.ndarray):
|
| 378 |
+
image = self.numpy_to_pt(image)
|
| 379 |
+
image = torch.nn.functional.interpolate(
|
| 380 |
+
image,
|
| 381 |
+
size=(height, width),
|
| 382 |
+
)
|
| 383 |
+
image = self.pt_to_numpy(image)
|
| 384 |
+
return image
|
| 385 |
+
|
| 386 |
+
def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
|
| 387 |
+
"""
|
| 388 |
+
Create a mask.
|
| 389 |
+
|
| 390 |
+
Args:
|
| 391 |
+
image (`PIL.Image.Image`):
|
| 392 |
+
The image input, should be a PIL image.
|
| 393 |
+
|
| 394 |
+
Returns:
|
| 395 |
+
`PIL.Image.Image`:
|
| 396 |
+
The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
|
| 397 |
+
"""
|
| 398 |
+
image[image < 0.5] = 0
|
| 399 |
+
image[image >= 0.5] = 1
|
| 400 |
+
|
| 401 |
+
return image
|
| 402 |
+
|
| 403 |
+
def get_default_height_width(
|
| 404 |
+
self,
|
| 405 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
| 406 |
+
height: Optional[int] = None,
|
| 407 |
+
width: Optional[int] = None,
|
| 408 |
+
) -> Tuple[int, int]:
|
| 409 |
+
"""
|
| 410 |
+
This function return the height and width that are downscaled to the next integer multiple of
|
| 411 |
+
`vae_scale_factor`.
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
| 415 |
+
The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
|
| 416 |
+
shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
|
| 417 |
+
have shape `[batch, channel, height, width]`.
|
| 418 |
+
height (`int`, *optional*, defaults to `None`):
|
| 419 |
+
The height in preprocessed image. If `None`, will use the height of `image` input.
|
| 420 |
+
width (`int`, *optional*`, defaults to `None`):
|
| 421 |
+
The width in preprocessed. If `None`, will use the width of the `image` input.
|
| 422 |
+
"""
|
| 423 |
+
|
| 424 |
+
if height is None:
|
| 425 |
+
if isinstance(image, PIL.Image.Image):
|
| 426 |
+
height = image.height
|
| 427 |
+
elif isinstance(image, torch.Tensor):
|
| 428 |
+
height = image.shape[2]
|
| 429 |
+
else:
|
| 430 |
+
height = image.shape[1]
|
| 431 |
+
|
| 432 |
+
if width is None:
|
| 433 |
+
if isinstance(image, PIL.Image.Image):
|
| 434 |
+
width = image.width
|
| 435 |
+
elif isinstance(image, torch.Tensor):
|
| 436 |
+
width = image.shape[3]
|
| 437 |
+
else:
|
| 438 |
+
width = image.shape[2]
|
| 439 |
+
|
| 440 |
+
width, height = (
|
| 441 |
+
x - x % self.config.vae_scale_factor for x in (width, height)
|
| 442 |
+
) # resize to integer multiple of vae_scale_factor
|
| 443 |
+
|
| 444 |
+
return height, width
|
| 445 |
+
|
| 446 |
+
def preprocess(
|
| 447 |
+
self,
|
| 448 |
+
image: PipelineImageInput,
|
| 449 |
+
height: Optional[int] = None,
|
| 450 |
+
width: Optional[int] = None,
|
| 451 |
+
resize_mode: str = "default", # "default", "fill", "crop"
|
| 452 |
+
crops_coords: Optional[Tuple[int, int, int, int]] = None,
|
| 453 |
+
) -> torch.Tensor:
|
| 454 |
+
"""
|
| 455 |
+
Preprocess the image input.
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
image (`pipeline_image_input`):
|
| 459 |
+
The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of supported formats.
|
| 460 |
+
height (`int`, *optional*, defaults to `None`):
|
| 461 |
+
The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default height.
|
| 462 |
+
width (`int`, *optional*`, defaults to `None`):
|
| 463 |
+
The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
|
| 464 |
+
resize_mode (`str`, *optional*, defaults to `default`):
|
| 465 |
+
The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit
|
| 466 |
+
within the specified width and height, and it may not maintaining the original aspect ratio.
|
| 467 |
+
If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 468 |
+
within the dimensions, filling empty with data from image.
|
| 469 |
+
If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 470 |
+
within the dimensions, cropping the excess.
|
| 471 |
+
Note that resize_mode `fill` and `crop` are only supported for PIL image input.
|
| 472 |
+
crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
|
| 473 |
+
The crop coordinates for each image in the batch. If `None`, will not crop the image.
|
| 474 |
+
"""
|
| 475 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
| 476 |
+
|
| 477 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
| 478 |
+
if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
|
| 479 |
+
if isinstance(image, torch.Tensor):
|
| 480 |
+
# if image is a pytorch tensor could have 2 possible shapes:
|
| 481 |
+
# 1. batch x height x width: we should insert the channel dimension at position 1
|
| 482 |
+
# 2. channel x height x width: we should insert batch dimension at position 0,
|
| 483 |
+
# however, since both channel and batch dimension has same size 1, it is same to insert at position 1
|
| 484 |
+
# for simplicity, we insert a dimension of size 1 at position 1 for both cases
|
| 485 |
+
image = image.unsqueeze(1)
|
| 486 |
+
else:
|
| 487 |
+
# if it is a numpy array, it could have 2 possible shapes:
|
| 488 |
+
# 1. batch x height x width: insert channel dimension on last position
|
| 489 |
+
# 2. height x width x channel: insert batch dimension on first position
|
| 490 |
+
if image.shape[-1] == 1:
|
| 491 |
+
image = np.expand_dims(image, axis=0)
|
| 492 |
+
else:
|
| 493 |
+
image = np.expand_dims(image, axis=-1)
|
| 494 |
+
|
| 495 |
+
if isinstance(image, supported_formats):
|
| 496 |
+
image = [image]
|
| 497 |
+
elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
if isinstance(image[0], PIL.Image.Image):
|
| 503 |
+
if crops_coords is not None:
|
| 504 |
+
image = [i.crop(crops_coords) for i in image]
|
| 505 |
+
if self.config.do_resize:
|
| 506 |
+
height, width = self.get_default_height_width(image[0], height, width)
|
| 507 |
+
image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
|
| 508 |
+
if self.config.do_convert_rgb:
|
| 509 |
+
image = [self.convert_to_rgb(i) for i in image]
|
| 510 |
+
elif self.config.do_convert_grayscale:
|
| 511 |
+
image = [self.convert_to_grayscale(i) for i in image]
|
| 512 |
+
image = self.pil_to_numpy(image) # to np
|
| 513 |
+
image = self.numpy_to_pt(image) # to pt
|
| 514 |
+
|
| 515 |
+
elif isinstance(image[0], np.ndarray):
|
| 516 |
+
image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
|
| 517 |
+
|
| 518 |
+
image = self.numpy_to_pt(image)
|
| 519 |
+
|
| 520 |
+
height, width = self.get_default_height_width(image, height, width)
|
| 521 |
+
if self.config.do_resize:
|
| 522 |
+
image = self.resize(image, height, width)
|
| 523 |
+
|
| 524 |
+
elif isinstance(image[0], torch.Tensor):
|
| 525 |
+
image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
|
| 526 |
+
|
| 527 |
+
if self.config.do_convert_grayscale and image.ndim == 3:
|
| 528 |
+
image = image.unsqueeze(1)
|
| 529 |
+
|
| 530 |
+
channel = image.shape[1]
|
| 531 |
+
# don't need any preprocess if the image is latents
|
| 532 |
+
if channel == 4:
|
| 533 |
+
return image
|
| 534 |
+
|
| 535 |
+
height, width = self.get_default_height_width(image, height, width)
|
| 536 |
+
if self.config.do_resize:
|
| 537 |
+
image = self.resize(image, height, width)
|
| 538 |
+
|
| 539 |
+
# expected range [0,1], normalize to [-1,1]
|
| 540 |
+
do_normalize = self.config.do_normalize
|
| 541 |
+
if do_normalize and image.min() < 0:
|
| 542 |
+
warnings.warn(
|
| 543 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
| 544 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
|
| 545 |
+
FutureWarning,
|
| 546 |
+
)
|
| 547 |
+
do_normalize = False
|
| 548 |
+
|
| 549 |
+
if do_normalize:
|
| 550 |
+
image = self.normalize(image)
|
| 551 |
+
|
| 552 |
+
if self.config.do_binarize:
|
| 553 |
+
image = self.binarize(image)
|
| 554 |
+
|
| 555 |
+
return image
|
| 556 |
+
|
| 557 |
+
def postprocess(
|
| 558 |
+
self,
|
| 559 |
+
image: torch.FloatTensor,
|
| 560 |
+
output_type: str = "pil",
|
| 561 |
+
do_denormalize: Optional[List[bool]] = None,
|
| 562 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
| 563 |
+
"""
|
| 564 |
+
Postprocess the image output from tensor to `output_type`.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
image (`torch.FloatTensor`):
|
| 568 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
| 569 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
| 570 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
| 571 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
| 572 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
| 573 |
+
`VaeImageProcessor` config.
|
| 574 |
+
|
| 575 |
+
Returns:
|
| 576 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
| 577 |
+
The postprocessed image.
|
| 578 |
+
"""
|
| 579 |
+
if not isinstance(image, torch.Tensor):
|
| 580 |
+
raise ValueError(
|
| 581 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
| 582 |
+
)
|
| 583 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
| 584 |
+
deprecation_message = (
|
| 585 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
| 586 |
+
"`pil`, `np`, `pt`, `latent`"
|
| 587 |
+
)
|
| 588 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
| 589 |
+
output_type = "np"
|
| 590 |
+
|
| 591 |
+
if output_type == "latent":
|
| 592 |
+
return image
|
| 593 |
+
|
| 594 |
+
if do_denormalize is None:
|
| 595 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
| 596 |
+
|
| 597 |
+
image = torch.stack(
|
| 598 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
if output_type == "pt":
|
| 602 |
+
return image
|
| 603 |
+
|
| 604 |
+
image = self.pt_to_numpy(image)
|
| 605 |
+
|
| 606 |
+
if output_type == "np":
|
| 607 |
+
return image
|
| 608 |
+
|
| 609 |
+
if output_type == "pil":
|
| 610 |
+
return self.numpy_to_pil(image)
|
| 611 |
+
|
| 612 |
+
def apply_overlay(
|
| 613 |
+
self,
|
| 614 |
+
mask: PIL.Image.Image,
|
| 615 |
+
init_image: PIL.Image.Image,
|
| 616 |
+
image: PIL.Image.Image,
|
| 617 |
+
crop_coords: Optional[Tuple[int, int, int, int]] = None,
|
| 618 |
+
) -> PIL.Image.Image:
|
| 619 |
+
"""
|
| 620 |
+
overlay the inpaint output to the original image
|
| 621 |
+
"""
|
| 622 |
+
|
| 623 |
+
width, height = image.width, image.height
|
| 624 |
+
|
| 625 |
+
init_image = self.resize(init_image, width=width, height=height)
|
| 626 |
+
mask = self.resize(mask, width=width, height=height)
|
| 627 |
+
|
| 628 |
+
init_image_masked = PIL.Image.new("RGBa", (width, height))
|
| 629 |
+
init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
|
| 630 |
+
init_image_masked = init_image_masked.convert("RGBA")
|
| 631 |
+
|
| 632 |
+
if crop_coords is not None:
|
| 633 |
+
x, y, x2, y2 = crop_coords
|
| 634 |
+
w = x2 - x
|
| 635 |
+
h = y2 - y
|
| 636 |
+
base_image = PIL.Image.new("RGBA", (width, height))
|
| 637 |
+
image = self.resize(image, height=h, width=w, resize_mode="crop")
|
| 638 |
+
base_image.paste(image, (x, y))
|
| 639 |
+
image = base_image.convert("RGB")
|
| 640 |
+
|
| 641 |
+
image = image.convert("RGBA")
|
| 642 |
+
image.alpha_composite(init_image_masked)
|
| 643 |
+
image = image.convert("RGB")
|
| 644 |
+
|
| 645 |
+
return image
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class VaeImageProcessorLDM3D(VaeImageProcessor):
|
| 649 |
+
"""
|
| 650 |
+
Image processor for VAE LDM3D.
|
| 651 |
+
|
| 652 |
+
Args:
|
| 653 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 654 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
|
| 655 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
| 656 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
| 657 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
| 658 |
+
Resampling filter to use when resizing the image.
|
| 659 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 660 |
+
Whether to normalize the image to [-1,1].
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
config_name = CONFIG_NAME
|
| 664 |
+
|
| 665 |
+
@register_to_config
|
| 666 |
+
def __init__(
|
| 667 |
+
self,
|
| 668 |
+
do_resize: bool = True,
|
| 669 |
+
vae_scale_factor: int = 8,
|
| 670 |
+
resample: str = "lanczos",
|
| 671 |
+
do_normalize: bool = True,
|
| 672 |
+
):
|
| 673 |
+
super().__init__()
|
| 674 |
+
|
| 675 |
+
@staticmethod
|
| 676 |
+
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
|
| 677 |
+
"""
|
| 678 |
+
Convert a NumPy image or a batch of images to a PIL image.
|
| 679 |
+
"""
|
| 680 |
+
if images.ndim == 3:
|
| 681 |
+
images = images[None, ...]
|
| 682 |
+
images = (images * 255).round().astype("uint8")
|
| 683 |
+
if images.shape[-1] == 1:
|
| 684 |
+
# special case for grayscale (single channel) images
|
| 685 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 686 |
+
else:
|
| 687 |
+
pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
|
| 688 |
+
|
| 689 |
+
return pil_images
|
| 690 |
+
|
| 691 |
+
@staticmethod
|
| 692 |
+
def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
| 693 |
+
"""
|
| 694 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
| 695 |
+
"""
|
| 696 |
+
if not isinstance(images, list):
|
| 697 |
+
images = [images]
|
| 698 |
+
|
| 699 |
+
images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
|
| 700 |
+
images = np.stack(images, axis=0)
|
| 701 |
+
return images
|
| 702 |
+
|
| 703 |
+
@staticmethod
|
| 704 |
+
def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 705 |
+
"""
|
| 706 |
+
Args:
|
| 707 |
+
image: RGB-like depth image
|
| 708 |
+
|
| 709 |
+
Returns: depth map
|
| 710 |
+
|
| 711 |
+
"""
|
| 712 |
+
return image[:, :, 1] * 2**8 + image[:, :, 2]
|
| 713 |
+
|
| 714 |
+
def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
|
| 715 |
+
"""
|
| 716 |
+
Convert a NumPy depth image or a batch of images to a PIL image.
|
| 717 |
+
"""
|
| 718 |
+
if images.ndim == 3:
|
| 719 |
+
images = images[None, ...]
|
| 720 |
+
images_depth = images[:, :, :, 3:]
|
| 721 |
+
if images.shape[-1] == 6:
|
| 722 |
+
images_depth = (images_depth * 255).round().astype("uint8")
|
| 723 |
+
pil_images = [
|
| 724 |
+
Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
|
| 725 |
+
]
|
| 726 |
+
elif images.shape[-1] == 4:
|
| 727 |
+
images_depth = (images_depth * 65535.0).astype(np.uint16)
|
| 728 |
+
pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
|
| 729 |
+
else:
|
| 730 |
+
raise Exception("Not supported")
|
| 731 |
+
|
| 732 |
+
return pil_images
|
| 733 |
+
|
| 734 |
+
def postprocess(
|
| 735 |
+
self,
|
| 736 |
+
image: torch.FloatTensor,
|
| 737 |
+
output_type: str = "pil",
|
| 738 |
+
do_denormalize: Optional[List[bool]] = None,
|
| 739 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
| 740 |
+
"""
|
| 741 |
+
Postprocess the image output from tensor to `output_type`.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
image (`torch.FloatTensor`):
|
| 745 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
| 746 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
| 747 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
| 748 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
| 749 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
| 750 |
+
`VaeImageProcessor` config.
|
| 751 |
+
|
| 752 |
+
Returns:
|
| 753 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
| 754 |
+
The postprocessed image.
|
| 755 |
+
"""
|
| 756 |
+
if not isinstance(image, torch.Tensor):
|
| 757 |
+
raise ValueError(
|
| 758 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
| 759 |
+
)
|
| 760 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
| 761 |
+
deprecation_message = (
|
| 762 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
| 763 |
+
"`pil`, `np`, `pt`, `latent`"
|
| 764 |
+
)
|
| 765 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
| 766 |
+
output_type = "np"
|
| 767 |
+
|
| 768 |
+
if do_denormalize is None:
|
| 769 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
| 770 |
+
|
| 771 |
+
image = torch.stack(
|
| 772 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
image = self.pt_to_numpy(image)
|
| 776 |
+
|
| 777 |
+
if output_type == "np":
|
| 778 |
+
if image.shape[-1] == 6:
|
| 779 |
+
image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
|
| 780 |
+
else:
|
| 781 |
+
image_depth = image[:, :, :, 3:]
|
| 782 |
+
return image[:, :, :, :3], image_depth
|
| 783 |
+
|
| 784 |
+
if output_type == "pil":
|
| 785 |
+
return self.numpy_to_pil(image), self.numpy_to_depth(image)
|
| 786 |
+
else:
|
| 787 |
+
raise Exception(f"This type {output_type} is not supported")
|
| 788 |
+
|
| 789 |
+
def preprocess(
|
| 790 |
+
self,
|
| 791 |
+
rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
| 792 |
+
depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
| 793 |
+
height: Optional[int] = None,
|
| 794 |
+
width: Optional[int] = None,
|
| 795 |
+
target_res: Optional[int] = None,
|
| 796 |
+
) -> torch.Tensor:
|
| 797 |
+
"""
|
| 798 |
+
Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
|
| 799 |
+
"""
|
| 800 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
| 801 |
+
|
| 802 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
| 803 |
+
if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
|
| 804 |
+
raise Exception("This is not yet supported")
|
| 805 |
+
|
| 806 |
+
if isinstance(rgb, supported_formats):
|
| 807 |
+
rgb = [rgb]
|
| 808 |
+
depth = [depth]
|
| 809 |
+
elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
|
| 810 |
+
raise ValueError(
|
| 811 |
+
f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
if isinstance(rgb[0], PIL.Image.Image):
|
| 815 |
+
if self.config.do_convert_rgb:
|
| 816 |
+
raise Exception("This is not yet supported")
|
| 817 |
+
# rgb = [self.convert_to_rgb(i) for i in rgb]
|
| 818 |
+
# depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
|
| 819 |
+
if self.config.do_resize or target_res:
|
| 820 |
+
height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
|
| 821 |
+
rgb = [self.resize(i, height, width) for i in rgb]
|
| 822 |
+
depth = [self.resize(i, height, width) for i in depth]
|
| 823 |
+
rgb = self.pil_to_numpy(rgb) # to np
|
| 824 |
+
rgb = self.numpy_to_pt(rgb) # to pt
|
| 825 |
+
|
| 826 |
+
depth = self.depth_pil_to_numpy(depth) # to np
|
| 827 |
+
depth = self.numpy_to_pt(depth) # to pt
|
| 828 |
+
|
| 829 |
+
elif isinstance(rgb[0], np.ndarray):
|
| 830 |
+
rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
|
| 831 |
+
rgb = self.numpy_to_pt(rgb)
|
| 832 |
+
height, width = self.get_default_height_width(rgb, height, width)
|
| 833 |
+
if self.config.do_resize:
|
| 834 |
+
rgb = self.resize(rgb, height, width)
|
| 835 |
+
|
| 836 |
+
depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
|
| 837 |
+
depth = self.numpy_to_pt(depth)
|
| 838 |
+
height, width = self.get_default_height_width(depth, height, width)
|
| 839 |
+
if self.config.do_resize:
|
| 840 |
+
depth = self.resize(depth, height, width)
|
| 841 |
+
|
| 842 |
+
elif isinstance(rgb[0], torch.Tensor):
|
| 843 |
+
raise Exception("This is not yet supported")
|
| 844 |
+
# rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
|
| 845 |
+
|
| 846 |
+
# if self.config.do_convert_grayscale and rgb.ndim == 3:
|
| 847 |
+
# rgb = rgb.unsqueeze(1)
|
| 848 |
+
|
| 849 |
+
# channel = rgb.shape[1]
|
| 850 |
+
|
| 851 |
+
# height, width = self.get_default_height_width(rgb, height, width)
|
| 852 |
+
# if self.config.do_resize:
|
| 853 |
+
# rgb = self.resize(rgb, height, width)
|
| 854 |
+
|
| 855 |
+
# depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
|
| 856 |
+
|
| 857 |
+
# if self.config.do_convert_grayscale and depth.ndim == 3:
|
| 858 |
+
# depth = depth.unsqueeze(1)
|
| 859 |
+
|
| 860 |
+
# channel = depth.shape[1]
|
| 861 |
+
# # don't need any preprocess if the image is latents
|
| 862 |
+
# if depth == 4:
|
| 863 |
+
# return rgb, depth
|
| 864 |
+
|
| 865 |
+
# height, width = self.get_default_height_width(depth, height, width)
|
| 866 |
+
# if self.config.do_resize:
|
| 867 |
+
# depth = self.resize(depth, height, width)
|
| 868 |
+
# expected range [0,1], normalize to [-1,1]
|
| 869 |
+
do_normalize = self.config.do_normalize
|
| 870 |
+
if rgb.min() < 0 and do_normalize:
|
| 871 |
+
warnings.warn(
|
| 872 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
| 873 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
|
| 874 |
+
FutureWarning,
|
| 875 |
+
)
|
| 876 |
+
do_normalize = False
|
| 877 |
+
|
| 878 |
+
if do_normalize:
|
| 879 |
+
rgb = self.normalize(rgb)
|
| 880 |
+
depth = self.normalize(depth)
|
| 881 |
+
|
| 882 |
+
if self.config.do_binarize:
|
| 883 |
+
rgb = self.binarize(rgb)
|
| 884 |
+
depth = self.binarize(depth)
|
| 885 |
+
|
| 886 |
+
return rgb, depth
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
class IPAdapterMaskProcessor(VaeImageProcessor):
|
| 890 |
+
"""
|
| 891 |
+
Image processor for IP Adapter image masks.
|
| 892 |
+
|
| 893 |
+
Args:
|
| 894 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 895 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
|
| 896 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
| 897 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
| 898 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
| 899 |
+
Resampling filter to use when resizing the image.
|
| 900 |
+
do_normalize (`bool`, *optional*, defaults to `False`):
|
| 901 |
+
Whether to normalize the image to [-1,1].
|
| 902 |
+
do_binarize (`bool`, *optional*, defaults to `True`):
|
| 903 |
+
Whether to binarize the image to 0/1.
|
| 904 |
+
do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
|
| 905 |
+
Whether to convert the images to grayscale format.
|
| 906 |
+
|
| 907 |
+
"""
|
| 908 |
+
|
| 909 |
+
config_name = CONFIG_NAME
|
| 910 |
+
|
| 911 |
+
@register_to_config
|
| 912 |
+
def __init__(
|
| 913 |
+
self,
|
| 914 |
+
do_resize: bool = True,
|
| 915 |
+
vae_scale_factor: int = 8,
|
| 916 |
+
resample: str = "lanczos",
|
| 917 |
+
do_normalize: bool = False,
|
| 918 |
+
do_binarize: bool = True,
|
| 919 |
+
do_convert_grayscale: bool = True,
|
| 920 |
+
):
|
| 921 |
+
super().__init__(
|
| 922 |
+
do_resize=do_resize,
|
| 923 |
+
vae_scale_factor=vae_scale_factor,
|
| 924 |
+
resample=resample,
|
| 925 |
+
do_normalize=do_normalize,
|
| 926 |
+
do_binarize=do_binarize,
|
| 927 |
+
do_convert_grayscale=do_convert_grayscale,
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
@staticmethod
|
| 931 |
+
def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
|
| 932 |
+
"""
|
| 933 |
+
Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention.
|
| 934 |
+
If the aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
|
| 935 |
+
|
| 936 |
+
Args:
|
| 937 |
+
mask (`torch.FloatTensor`):
|
| 938 |
+
The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
|
| 939 |
+
batch_size (`int`):
|
| 940 |
+
The batch size.
|
| 941 |
+
num_queries (`int`):
|
| 942 |
+
The number of queries.
|
| 943 |
+
value_embed_dim (`int`):
|
| 944 |
+
The dimensionality of the value embeddings.
|
| 945 |
+
|
| 946 |
+
Returns:
|
| 947 |
+
`torch.FloatTensor`:
|
| 948 |
+
The downsampled mask tensor.
|
| 949 |
+
|
| 950 |
+
"""
|
| 951 |
+
o_h = mask.shape[1]
|
| 952 |
+
o_w = mask.shape[2]
|
| 953 |
+
ratio = o_w / o_h
|
| 954 |
+
mask_h = int(math.sqrt(num_queries / ratio))
|
| 955 |
+
mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
|
| 956 |
+
mask_w = num_queries // mask_h
|
| 957 |
+
|
| 958 |
+
mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
|
| 959 |
+
|
| 960 |
+
# Repeat batch_size times
|
| 961 |
+
if mask_downsample.shape[0] < batch_size:
|
| 962 |
+
mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
|
| 963 |
+
|
| 964 |
+
mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
|
| 965 |
+
|
| 966 |
+
downsampled_area = mask_h * mask_w
|
| 967 |
+
# If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
|
| 968 |
+
# Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
|
| 969 |
+
if downsampled_area < num_queries:
|
| 970 |
+
warnings.warn(
|
| 971 |
+
"The aspect ratio of the mask does not match the aspect ratio of the output image. "
|
| 972 |
+
"Please update your masks or adjust the output size for optimal performance.",
|
| 973 |
+
UserWarning,
|
| 974 |
+
)
|
| 975 |
+
mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
|
| 976 |
+
# Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
|
| 977 |
+
if downsampled_area > num_queries:
|
| 978 |
+
warnings.warn(
|
| 979 |
+
"The aspect ratio of the mask does not match the aspect ratio of the output image. "
|
| 980 |
+
"Please update your masks or adjust the output size for optimal performance.",
|
| 981 |
+
UserWarning,
|
| 982 |
+
)
|
| 983 |
+
mask_downsample = mask_downsample[:, :num_queries]
|
| 984 |
+
|
| 985 |
+
# Repeat last dimension to match SDPA output shape
|
| 986 |
+
mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
|
| 987 |
+
1, 1, value_embed_dim
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
return mask_downsample
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/optimization.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch optimization for diffusion models."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from enum import Enum
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
from torch.optim import Optimizer
|
| 22 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 23 |
+
|
| 24 |
+
from .utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SchedulerType(Enum):
|
| 31 |
+
LINEAR = "linear"
|
| 32 |
+
COSINE = "cosine"
|
| 33 |
+
COSINE_WITH_RESTARTS = "cosine_with_restarts"
|
| 34 |
+
POLYNOMIAL = "polynomial"
|
| 35 |
+
CONSTANT = "constant"
|
| 36 |
+
CONSTANT_WITH_WARMUP = "constant_with_warmup"
|
| 37 |
+
PIECEWISE_CONSTANT = "piecewise_constant"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1) -> LambdaLR:
|
| 41 |
+
"""
|
| 42 |
+
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 46 |
+
The optimizer for which to schedule the learning rate.
|
| 47 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 48 |
+
The index of the last epoch when resuming training.
|
| 49 |
+
|
| 50 |
+
Return:
|
| 51 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 52 |
+
"""
|
| 53 |
+
return LambdaLR(optimizer, lambda _: 1, last_epoch=last_epoch)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1) -> LambdaLR:
|
| 57 |
+
"""
|
| 58 |
+
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
|
| 59 |
+
increases linearly between 0 and the initial lr set in the optimizer.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 63 |
+
The optimizer for which to schedule the learning rate.
|
| 64 |
+
num_warmup_steps (`int`):
|
| 65 |
+
The number of steps for the warmup phase.
|
| 66 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 67 |
+
The index of the last epoch when resuming training.
|
| 68 |
+
|
| 69 |
+
Return:
|
| 70 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def lr_lambda(current_step: int):
|
| 74 |
+
if current_step < num_warmup_steps:
|
| 75 |
+
return float(current_step) / float(max(1.0, num_warmup_steps))
|
| 76 |
+
return 1.0
|
| 77 |
+
|
| 78 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_piecewise_constant_schedule(optimizer: Optimizer, step_rules: str, last_epoch: int = -1) -> LambdaLR:
|
| 82 |
+
"""
|
| 83 |
+
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 87 |
+
The optimizer for which to schedule the learning rate.
|
| 88 |
+
step_rules (`string`):
|
| 89 |
+
The rules for the learning rate. ex: rule_steps="1:10,0.1:20,0.01:30,0.005" it means that the learning rate
|
| 90 |
+
if multiple 1 for the first 10 steps, mutiple 0.1 for the next 20 steps, multiple 0.01 for the next 30
|
| 91 |
+
steps and multiple 0.005 for the other steps.
|
| 92 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 93 |
+
The index of the last epoch when resuming training.
|
| 94 |
+
|
| 95 |
+
Return:
|
| 96 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
rules_dict = {}
|
| 100 |
+
rule_list = step_rules.split(",")
|
| 101 |
+
for rule_str in rule_list[:-1]:
|
| 102 |
+
value_str, steps_str = rule_str.split(":")
|
| 103 |
+
steps = int(steps_str)
|
| 104 |
+
value = float(value_str)
|
| 105 |
+
rules_dict[steps] = value
|
| 106 |
+
last_lr_multiple = float(rule_list[-1])
|
| 107 |
+
|
| 108 |
+
def create_rules_function(rules_dict, last_lr_multiple):
|
| 109 |
+
def rule_func(steps: int) -> float:
|
| 110 |
+
sorted_steps = sorted(rules_dict.keys())
|
| 111 |
+
for i, sorted_step in enumerate(sorted_steps):
|
| 112 |
+
if steps < sorted_step:
|
| 113 |
+
return rules_dict[sorted_steps[i]]
|
| 114 |
+
return last_lr_multiple
|
| 115 |
+
|
| 116 |
+
return rule_func
|
| 117 |
+
|
| 118 |
+
rules_func = create_rules_function(rules_dict, last_lr_multiple)
|
| 119 |
+
|
| 120 |
+
return LambdaLR(optimizer, rules_func, last_epoch=last_epoch)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_linear_schedule_with_warmup(
|
| 124 |
+
optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, last_epoch: int = -1
|
| 125 |
+
) -> LambdaLR:
|
| 126 |
+
"""
|
| 127 |
+
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after
|
| 128 |
+
a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 132 |
+
The optimizer for which to schedule the learning rate.
|
| 133 |
+
num_warmup_steps (`int`):
|
| 134 |
+
The number of steps for the warmup phase.
|
| 135 |
+
num_training_steps (`int`):
|
| 136 |
+
The total number of training steps.
|
| 137 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 138 |
+
The index of the last epoch when resuming training.
|
| 139 |
+
|
| 140 |
+
Return:
|
| 141 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
def lr_lambda(current_step: int):
|
| 145 |
+
if current_step < num_warmup_steps:
|
| 146 |
+
return float(current_step) / float(max(1, num_warmup_steps))
|
| 147 |
+
return max(
|
| 148 |
+
0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps))
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_cosine_schedule_with_warmup(
|
| 155 |
+
optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1
|
| 156 |
+
) -> LambdaLR:
|
| 157 |
+
"""
|
| 158 |
+
Create a schedule with a learning rate that decreases following the values of the cosine function between the
|
| 159 |
+
initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the
|
| 160 |
+
initial lr set in the optimizer.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 164 |
+
The optimizer for which to schedule the learning rate.
|
| 165 |
+
num_warmup_steps (`int`):
|
| 166 |
+
The number of steps for the warmup phase.
|
| 167 |
+
num_training_steps (`int`):
|
| 168 |
+
The total number of training steps.
|
| 169 |
+
num_periods (`float`, *optional*, defaults to 0.5):
|
| 170 |
+
The number of periods of the cosine function in a schedule (the default is to just decrease from the max
|
| 171 |
+
value to 0 following a half-cosine).
|
| 172 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 173 |
+
The index of the last epoch when resuming training.
|
| 174 |
+
|
| 175 |
+
Return:
|
| 176 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def lr_lambda(current_step):
|
| 180 |
+
if current_step < num_warmup_steps:
|
| 181 |
+
return float(current_step) / float(max(1, num_warmup_steps))
|
| 182 |
+
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
|
| 183 |
+
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress)))
|
| 184 |
+
|
| 185 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_cosine_with_hard_restarts_schedule_with_warmup(
|
| 189 |
+
optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1
|
| 190 |
+
) -> LambdaLR:
|
| 191 |
+
"""
|
| 192 |
+
Create a schedule with a learning rate that decreases following the values of the cosine function between the
|
| 193 |
+
initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases
|
| 194 |
+
linearly between 0 and the initial lr set in the optimizer.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 198 |
+
The optimizer for which to schedule the learning rate.
|
| 199 |
+
num_warmup_steps (`int`):
|
| 200 |
+
The number of steps for the warmup phase.
|
| 201 |
+
num_training_steps (`int`):
|
| 202 |
+
The total number of training steps.
|
| 203 |
+
num_cycles (`int`, *optional*, defaults to 1):
|
| 204 |
+
The number of hard restarts to use.
|
| 205 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 206 |
+
The index of the last epoch when resuming training.
|
| 207 |
+
|
| 208 |
+
Return:
|
| 209 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def lr_lambda(current_step):
|
| 213 |
+
if current_step < num_warmup_steps:
|
| 214 |
+
return float(current_step) / float(max(1, num_warmup_steps))
|
| 215 |
+
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
|
| 216 |
+
if progress >= 1.0:
|
| 217 |
+
return 0.0
|
| 218 |
+
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0))))
|
| 219 |
+
|
| 220 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_polynomial_decay_schedule_with_warmup(
|
| 224 |
+
optimizer: Optimizer,
|
| 225 |
+
num_warmup_steps: int,
|
| 226 |
+
num_training_steps: int,
|
| 227 |
+
lr_end: float = 1e-7,
|
| 228 |
+
power: float = 1.0,
|
| 229 |
+
last_epoch: int = -1,
|
| 230 |
+
) -> LambdaLR:
|
| 231 |
+
"""
|
| 232 |
+
Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the
|
| 233 |
+
optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the
|
| 234 |
+
initial lr set in the optimizer.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
optimizer ([`~torch.optim.Optimizer`]):
|
| 238 |
+
The optimizer for which to schedule the learning rate.
|
| 239 |
+
num_warmup_steps (`int`):
|
| 240 |
+
The number of steps for the warmup phase.
|
| 241 |
+
num_training_steps (`int`):
|
| 242 |
+
The total number of training steps.
|
| 243 |
+
lr_end (`float`, *optional*, defaults to 1e-7):
|
| 244 |
+
The end LR.
|
| 245 |
+
power (`float`, *optional*, defaults to 1.0):
|
| 246 |
+
Power factor.
|
| 247 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 248 |
+
The index of the last epoch when resuming training.
|
| 249 |
+
|
| 250 |
+
Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT
|
| 251 |
+
implementation at
|
| 252 |
+
https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37
|
| 253 |
+
|
| 254 |
+
Return:
|
| 255 |
+
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
| 256 |
+
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
lr_init = optimizer.defaults["lr"]
|
| 260 |
+
if not (lr_init > lr_end):
|
| 261 |
+
raise ValueError(f"lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})")
|
| 262 |
+
|
| 263 |
+
def lr_lambda(current_step: int):
|
| 264 |
+
if current_step < num_warmup_steps:
|
| 265 |
+
return float(current_step) / float(max(1, num_warmup_steps))
|
| 266 |
+
elif current_step > num_training_steps:
|
| 267 |
+
return lr_end / lr_init # as LambdaLR multiplies by lr_init
|
| 268 |
+
else:
|
| 269 |
+
lr_range = lr_init - lr_end
|
| 270 |
+
decay_steps = num_training_steps - num_warmup_steps
|
| 271 |
+
pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps
|
| 272 |
+
decay = lr_range * pct_remaining**power + lr_end
|
| 273 |
+
return decay / lr_init # as LambdaLR multiplies by lr_init
|
| 274 |
+
|
| 275 |
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
TYPE_TO_SCHEDULER_FUNCTION = {
|
| 279 |
+
SchedulerType.LINEAR: get_linear_schedule_with_warmup,
|
| 280 |
+
SchedulerType.COSINE: get_cosine_schedule_with_warmup,
|
| 281 |
+
SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup,
|
| 282 |
+
SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup,
|
| 283 |
+
SchedulerType.CONSTANT: get_constant_schedule,
|
| 284 |
+
SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup,
|
| 285 |
+
SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule,
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def get_scheduler(
|
| 290 |
+
name: Union[str, SchedulerType],
|
| 291 |
+
optimizer: Optimizer,
|
| 292 |
+
step_rules: Optional[str] = None,
|
| 293 |
+
num_warmup_steps: Optional[int] = None,
|
| 294 |
+
num_training_steps: Optional[int] = None,
|
| 295 |
+
num_cycles: int = 1,
|
| 296 |
+
power: float = 1.0,
|
| 297 |
+
last_epoch: int = -1,
|
| 298 |
+
) -> LambdaLR:
|
| 299 |
+
"""
|
| 300 |
+
Unified API to get any scheduler from its name.
|
| 301 |
+
|
| 302 |
+
Args:
|
| 303 |
+
name (`str` or `SchedulerType`):
|
| 304 |
+
The name of the scheduler to use.
|
| 305 |
+
optimizer (`torch.optim.Optimizer`):
|
| 306 |
+
The optimizer that will be used during training.
|
| 307 |
+
step_rules (`str`, *optional*):
|
| 308 |
+
A string representing the step rules to use. This is only used by the `PIECEWISE_CONSTANT` scheduler.
|
| 309 |
+
num_warmup_steps (`int`, *optional*):
|
| 310 |
+
The number of warmup steps to do. This is not required by all schedulers (hence the argument being
|
| 311 |
+
optional), the function will raise an error if it's unset and the scheduler type requires it.
|
| 312 |
+
num_training_steps (`int``, *optional*):
|
| 313 |
+
The number of training steps to do. This is not required by all schedulers (hence the argument being
|
| 314 |
+
optional), the function will raise an error if it's unset and the scheduler type requires it.
|
| 315 |
+
num_cycles (`int`, *optional*):
|
| 316 |
+
The number of hard restarts used in `COSINE_WITH_RESTARTS` scheduler.
|
| 317 |
+
power (`float`, *optional*, defaults to 1.0):
|
| 318 |
+
Power factor. See `POLYNOMIAL` scheduler
|
| 319 |
+
last_epoch (`int`, *optional*, defaults to -1):
|
| 320 |
+
The index of the last epoch when resuming training.
|
| 321 |
+
"""
|
| 322 |
+
name = SchedulerType(name)
|
| 323 |
+
schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name]
|
| 324 |
+
if name == SchedulerType.CONSTANT:
|
| 325 |
+
return schedule_func(optimizer, last_epoch=last_epoch)
|
| 326 |
+
|
| 327 |
+
if name == SchedulerType.PIECEWISE_CONSTANT:
|
| 328 |
+
return schedule_func(optimizer, step_rules=step_rules, last_epoch=last_epoch)
|
| 329 |
+
|
| 330 |
+
# All other schedulers require `num_warmup_steps`
|
| 331 |
+
if num_warmup_steps is None:
|
| 332 |
+
raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.")
|
| 333 |
+
|
| 334 |
+
if name == SchedulerType.CONSTANT_WITH_WARMUP:
|
| 335 |
+
return schedule_func(optimizer, num_warmup_steps=num_warmup_steps, last_epoch=last_epoch)
|
| 336 |
+
|
| 337 |
+
# All other schedulers require `num_training_steps`
|
| 338 |
+
if num_training_steps is None:
|
| 339 |
+
raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.")
|
| 340 |
+
|
| 341 |
+
if name == SchedulerType.COSINE_WITH_RESTARTS:
|
| 342 |
+
return schedule_func(
|
| 343 |
+
optimizer,
|
| 344 |
+
num_warmup_steps=num_warmup_steps,
|
| 345 |
+
num_training_steps=num_training_steps,
|
| 346 |
+
num_cycles=num_cycles,
|
| 347 |
+
last_epoch=last_epoch,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
if name == SchedulerType.POLYNOMIAL:
|
| 351 |
+
return schedule_func(
|
| 352 |
+
optimizer,
|
| 353 |
+
num_warmup_steps=num_warmup_steps,
|
| 354 |
+
num_training_steps=num_training_steps,
|
| 355 |
+
power=power,
|
| 356 |
+
last_epoch=last_epoch,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
return schedule_func(
|
| 360 |
+
optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, last_epoch=last_epoch
|
| 361 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/__init__.py
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ..utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
get_objects_from_module,
|
| 8 |
+
is_flax_available,
|
| 9 |
+
is_k_diffusion_available,
|
| 10 |
+
is_librosa_available,
|
| 11 |
+
is_note_seq_available,
|
| 12 |
+
is_onnx_available,
|
| 13 |
+
is_torch_available,
|
| 14 |
+
is_torch_npu_available,
|
| 15 |
+
is_transformers_available,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# These modules contain pipelines from multiple libraries/frameworks
|
| 20 |
+
_dummy_objects = {}
|
| 21 |
+
_import_structure = {
|
| 22 |
+
"controlnet": [],
|
| 23 |
+
"controlnet_xs": [],
|
| 24 |
+
"deprecated": [],
|
| 25 |
+
"latent_diffusion": [],
|
| 26 |
+
"ledits_pp": [],
|
| 27 |
+
"stable_diffusion": [],
|
| 28 |
+
"stable_diffusion_xl": [],
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
if not is_torch_available():
|
| 33 |
+
raise OptionalDependencyNotAvailable()
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
from ..utils import dummy_pt_objects # noqa F403
|
| 36 |
+
|
| 37 |
+
_dummy_objects.update(get_objects_from_module(dummy_pt_objects))
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["auto_pipeline"] = [
|
| 40 |
+
"AutoPipelineForImage2Image",
|
| 41 |
+
"AutoPipelineForInpainting",
|
| 42 |
+
"AutoPipelineForText2Image",
|
| 43 |
+
]
|
| 44 |
+
_import_structure["consistency_models"] = ["ConsistencyModelPipeline"]
|
| 45 |
+
_import_structure["dance_diffusion"] = ["DanceDiffusionPipeline"]
|
| 46 |
+
_import_structure["ddim"] = ["DDIMPipeline"]
|
| 47 |
+
_import_structure["ddpm"] = ["DDPMPipeline"]
|
| 48 |
+
_import_structure["dit"] = ["DiTPipeline"]
|
| 49 |
+
_import_structure["latent_diffusion"].extend(["LDMSuperResolutionPipeline"])
|
| 50 |
+
_import_structure["pipeline_utils"] = [
|
| 51 |
+
"AudioPipelineOutput",
|
| 52 |
+
"DiffusionPipeline",
|
| 53 |
+
"StableDiffusionMixin",
|
| 54 |
+
"ImagePipelineOutput",
|
| 55 |
+
]
|
| 56 |
+
_import_structure["deprecated"].extend(
|
| 57 |
+
[
|
| 58 |
+
"PNDMPipeline",
|
| 59 |
+
"LDMPipeline",
|
| 60 |
+
"RePaintPipeline",
|
| 61 |
+
"ScoreSdeVePipeline",
|
| 62 |
+
"KarrasVePipeline",
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
try:
|
| 66 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 67 |
+
raise OptionalDependencyNotAvailable()
|
| 68 |
+
except OptionalDependencyNotAvailable:
|
| 69 |
+
from ..utils import dummy_torch_and_librosa_objects # noqa F403
|
| 70 |
+
|
| 71 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_librosa_objects))
|
| 72 |
+
else:
|
| 73 |
+
_import_structure["deprecated"].extend(["AudioDiffusionPipeline", "Mel"])
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 77 |
+
raise OptionalDependencyNotAvailable()
|
| 78 |
+
except OptionalDependencyNotAvailable:
|
| 79 |
+
from ..utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
|
| 80 |
+
|
| 81 |
+
_dummy_objects.update(get_objects_from_module(dummy_transformers_and_torch_and_note_seq_objects))
|
| 82 |
+
else:
|
| 83 |
+
_import_structure["deprecated"].extend(
|
| 84 |
+
[
|
| 85 |
+
"MidiProcessor",
|
| 86 |
+
"SpectrogramDiffusionPipeline",
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 92 |
+
raise OptionalDependencyNotAvailable()
|
| 93 |
+
except OptionalDependencyNotAvailable:
|
| 94 |
+
from ..utils import dummy_torch_and_transformers_objects # noqa F403
|
| 95 |
+
|
| 96 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 97 |
+
else:
|
| 98 |
+
_import_structure["deprecated"].extend(
|
| 99 |
+
[
|
| 100 |
+
"VQDiffusionPipeline",
|
| 101 |
+
"AltDiffusionPipeline",
|
| 102 |
+
"AltDiffusionImg2ImgPipeline",
|
| 103 |
+
"CycleDiffusionPipeline",
|
| 104 |
+
"StableDiffusionInpaintPipelineLegacy",
|
| 105 |
+
"StableDiffusionPix2PixZeroPipeline",
|
| 106 |
+
"StableDiffusionParadigmsPipeline",
|
| 107 |
+
"StableDiffusionModelEditingPipeline",
|
| 108 |
+
"VersatileDiffusionDualGuidedPipeline",
|
| 109 |
+
"VersatileDiffusionImageVariationPipeline",
|
| 110 |
+
"VersatileDiffusionPipeline",
|
| 111 |
+
"VersatileDiffusionTextToImagePipeline",
|
| 112 |
+
]
|
| 113 |
+
)
|
| 114 |
+
_import_structure["amused"] = ["AmusedImg2ImgPipeline", "AmusedInpaintPipeline", "AmusedPipeline"]
|
| 115 |
+
_import_structure["animatediff"] = [
|
| 116 |
+
"AnimateDiffPipeline",
|
| 117 |
+
"AnimateDiffVideoToVideoPipeline",
|
| 118 |
+
]
|
| 119 |
+
_import_structure["audioldm"] = ["AudioLDMPipeline"]
|
| 120 |
+
_import_structure["audioldm2"] = [
|
| 121 |
+
"AudioLDM2Pipeline",
|
| 122 |
+
"AudioLDM2ProjectionModel",
|
| 123 |
+
"AudioLDM2UNet2DConditionModel",
|
| 124 |
+
]
|
| 125 |
+
_import_structure["blip_diffusion"] = ["BlipDiffusionPipeline"]
|
| 126 |
+
_import_structure["controlnet"].extend(
|
| 127 |
+
[
|
| 128 |
+
"BlipDiffusionControlNetPipeline",
|
| 129 |
+
"StableDiffusionControlNetImg2ImgPipeline",
|
| 130 |
+
"StableDiffusionControlNetInpaintPipeline",
|
| 131 |
+
"StableDiffusionControlNetPipeline",
|
| 132 |
+
"StableDiffusionXLControlNetImg2ImgPipeline",
|
| 133 |
+
"StableDiffusionXLControlNetInpaintPipeline",
|
| 134 |
+
"StableDiffusionXLControlNetPipeline",
|
| 135 |
+
]
|
| 136 |
+
)
|
| 137 |
+
_import_structure["deepfloyd_if"] = [
|
| 138 |
+
"IFImg2ImgPipeline",
|
| 139 |
+
"IFImg2ImgSuperResolutionPipeline",
|
| 140 |
+
"IFInpaintingPipeline",
|
| 141 |
+
"IFInpaintingSuperResolutionPipeline",
|
| 142 |
+
"IFPipeline",
|
| 143 |
+
"IFSuperResolutionPipeline",
|
| 144 |
+
]
|
| 145 |
+
_import_structure["kandinsky"] = [
|
| 146 |
+
"KandinskyCombinedPipeline",
|
| 147 |
+
"KandinskyImg2ImgCombinedPipeline",
|
| 148 |
+
"KandinskyImg2ImgPipeline",
|
| 149 |
+
"KandinskyInpaintCombinedPipeline",
|
| 150 |
+
"KandinskyInpaintPipeline",
|
| 151 |
+
"KandinskyPipeline",
|
| 152 |
+
"KandinskyPriorPipeline",
|
| 153 |
+
]
|
| 154 |
+
_import_structure["kandinsky2_2"] = [
|
| 155 |
+
"KandinskyV22CombinedPipeline",
|
| 156 |
+
"KandinskyV22ControlnetImg2ImgPipeline",
|
| 157 |
+
"KandinskyV22ControlnetPipeline",
|
| 158 |
+
"KandinskyV22Img2ImgCombinedPipeline",
|
| 159 |
+
"KandinskyV22Img2ImgPipeline",
|
| 160 |
+
"KandinskyV22InpaintCombinedPipeline",
|
| 161 |
+
"KandinskyV22InpaintPipeline",
|
| 162 |
+
"KandinskyV22Pipeline",
|
| 163 |
+
"KandinskyV22PriorEmb2EmbPipeline",
|
| 164 |
+
"KandinskyV22PriorPipeline",
|
| 165 |
+
]
|
| 166 |
+
_import_structure["kandinsky3"] = [
|
| 167 |
+
"Kandinsky3Img2ImgPipeline",
|
| 168 |
+
"Kandinsky3Pipeline",
|
| 169 |
+
]
|
| 170 |
+
_import_structure["latent_consistency_models"] = [
|
| 171 |
+
"LatentConsistencyModelImg2ImgPipeline",
|
| 172 |
+
"LatentConsistencyModelPipeline",
|
| 173 |
+
]
|
| 174 |
+
_import_structure["latent_diffusion"].extend(["LDMTextToImagePipeline"])
|
| 175 |
+
_import_structure["ledits_pp"].extend(
|
| 176 |
+
[
|
| 177 |
+
"LEditsPPPipelineStableDiffusion",
|
| 178 |
+
"LEditsPPPipelineStableDiffusionXL",
|
| 179 |
+
]
|
| 180 |
+
)
|
| 181 |
+
_import_structure["musicldm"] = ["MusicLDMPipeline"]
|
| 182 |
+
_import_structure["paint_by_example"] = ["PaintByExamplePipeline"]
|
| 183 |
+
_import_structure["pia"] = ["PIAPipeline"]
|
| 184 |
+
_import_structure["pixart_alpha"] = ["PixArtAlphaPipeline"]
|
| 185 |
+
_import_structure["semantic_stable_diffusion"] = ["SemanticStableDiffusionPipeline"]
|
| 186 |
+
_import_structure["shap_e"] = ["ShapEImg2ImgPipeline", "ShapEPipeline"]
|
| 187 |
+
_import_structure["stable_cascade"] = [
|
| 188 |
+
"StableCascadeCombinedPipeline",
|
| 189 |
+
"StableCascadeDecoderPipeline",
|
| 190 |
+
"StableCascadePriorPipeline",
|
| 191 |
+
]
|
| 192 |
+
_import_structure["stable_diffusion"].extend(
|
| 193 |
+
[
|
| 194 |
+
"CLIPImageProjection",
|
| 195 |
+
"StableDiffusionDepth2ImgPipeline",
|
| 196 |
+
"StableDiffusionImageVariationPipeline",
|
| 197 |
+
"StableDiffusionImg2ImgPipeline",
|
| 198 |
+
"StableDiffusionInpaintPipeline",
|
| 199 |
+
"StableDiffusionInstructPix2PixPipeline",
|
| 200 |
+
"StableDiffusionLatentUpscalePipeline",
|
| 201 |
+
"StableDiffusionPipeline",
|
| 202 |
+
"StableDiffusionUpscalePipeline",
|
| 203 |
+
"StableUnCLIPImg2ImgPipeline",
|
| 204 |
+
"StableUnCLIPPipeline",
|
| 205 |
+
"StableDiffusionLDM3DPipeline",
|
| 206 |
+
]
|
| 207 |
+
)
|
| 208 |
+
_import_structure["stable_diffusion_attend_and_excite"] = ["StableDiffusionAttendAndExcitePipeline"]
|
| 209 |
+
_import_structure["stable_diffusion_safe"] = ["StableDiffusionPipelineSafe"]
|
| 210 |
+
_import_structure["stable_diffusion_sag"] = ["StableDiffusionSAGPipeline"]
|
| 211 |
+
_import_structure["stable_diffusion_gligen"] = [
|
| 212 |
+
"StableDiffusionGLIGENPipeline",
|
| 213 |
+
"StableDiffusionGLIGENTextImagePipeline",
|
| 214 |
+
]
|
| 215 |
+
_import_structure["stable_video_diffusion"] = ["StableVideoDiffusionPipeline"]
|
| 216 |
+
_import_structure["stable_diffusion_xl"].extend(
|
| 217 |
+
[
|
| 218 |
+
"StableDiffusionXLImg2ImgPipeline",
|
| 219 |
+
"StableDiffusionXLInpaintPipeline",
|
| 220 |
+
"StableDiffusionXLInstructPix2PixPipeline",
|
| 221 |
+
"StableDiffusionXLPipeline",
|
| 222 |
+
]
|
| 223 |
+
)
|
| 224 |
+
_import_structure["stable_diffusion_diffedit"] = ["StableDiffusionDiffEditPipeline"]
|
| 225 |
+
_import_structure["stable_diffusion_ldm3d"] = ["StableDiffusionLDM3DPipeline"]
|
| 226 |
+
_import_structure["stable_diffusion_panorama"] = ["StableDiffusionPanoramaPipeline"]
|
| 227 |
+
_import_structure["t2i_adapter"] = [
|
| 228 |
+
"StableDiffusionAdapterPipeline",
|
| 229 |
+
"StableDiffusionXLAdapterPipeline",
|
| 230 |
+
]
|
| 231 |
+
_import_structure["text_to_video_synthesis"] = [
|
| 232 |
+
"TextToVideoSDPipeline",
|
| 233 |
+
"TextToVideoZeroPipeline",
|
| 234 |
+
"TextToVideoZeroSDXLPipeline",
|
| 235 |
+
"VideoToVideoSDPipeline",
|
| 236 |
+
]
|
| 237 |
+
_import_structure["i2vgen_xl"] = ["I2VGenXLPipeline"]
|
| 238 |
+
_import_structure["unclip"] = ["UnCLIPImageVariationPipeline", "UnCLIPPipeline"]
|
| 239 |
+
_import_structure["unidiffuser"] = [
|
| 240 |
+
"ImageTextPipelineOutput",
|
| 241 |
+
"UniDiffuserModel",
|
| 242 |
+
"UniDiffuserPipeline",
|
| 243 |
+
"UniDiffuserTextDecoder",
|
| 244 |
+
]
|
| 245 |
+
_import_structure["wuerstchen"] = [
|
| 246 |
+
"WuerstchenCombinedPipeline",
|
| 247 |
+
"WuerstchenDecoderPipeline",
|
| 248 |
+
"WuerstchenPriorPipeline",
|
| 249 |
+
]
|
| 250 |
+
try:
|
| 251 |
+
if not is_onnx_available():
|
| 252 |
+
raise OptionalDependencyNotAvailable()
|
| 253 |
+
except OptionalDependencyNotAvailable:
|
| 254 |
+
from ..utils import dummy_onnx_objects # noqa F403
|
| 255 |
+
|
| 256 |
+
_dummy_objects.update(get_objects_from_module(dummy_onnx_objects))
|
| 257 |
+
else:
|
| 258 |
+
_import_structure["onnx_utils"] = ["OnnxRuntimeModel"]
|
| 259 |
+
try:
|
| 260 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 261 |
+
raise OptionalDependencyNotAvailable()
|
| 262 |
+
except OptionalDependencyNotAvailable:
|
| 263 |
+
from ..utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
|
| 264 |
+
|
| 265 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_and_onnx_objects))
|
| 266 |
+
else:
|
| 267 |
+
_import_structure["stable_diffusion"].extend(
|
| 268 |
+
[
|
| 269 |
+
"OnnxStableDiffusionImg2ImgPipeline",
|
| 270 |
+
"OnnxStableDiffusionInpaintPipeline",
|
| 271 |
+
"OnnxStableDiffusionPipeline",
|
| 272 |
+
"OnnxStableDiffusionUpscalePipeline",
|
| 273 |
+
"StableDiffusionOnnxPipeline",
|
| 274 |
+
]
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
try:
|
| 278 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 279 |
+
raise OptionalDependencyNotAvailable()
|
| 280 |
+
except OptionalDependencyNotAvailable:
|
| 281 |
+
from ..utils import (
|
| 282 |
+
dummy_torch_and_transformers_and_k_diffusion_objects,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_and_k_diffusion_objects))
|
| 286 |
+
else:
|
| 287 |
+
_import_structure["stable_diffusion_k_diffusion"] = [
|
| 288 |
+
"StableDiffusionKDiffusionPipeline",
|
| 289 |
+
"StableDiffusionXLKDiffusionPipeline",
|
| 290 |
+
]
|
| 291 |
+
try:
|
| 292 |
+
if not is_flax_available():
|
| 293 |
+
raise OptionalDependencyNotAvailable()
|
| 294 |
+
except OptionalDependencyNotAvailable:
|
| 295 |
+
from ..utils import dummy_flax_objects # noqa F403
|
| 296 |
+
|
| 297 |
+
_dummy_objects.update(get_objects_from_module(dummy_flax_objects))
|
| 298 |
+
else:
|
| 299 |
+
_import_structure["pipeline_flax_utils"] = ["FlaxDiffusionPipeline"]
|
| 300 |
+
try:
|
| 301 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 302 |
+
raise OptionalDependencyNotAvailable()
|
| 303 |
+
except OptionalDependencyNotAvailable:
|
| 304 |
+
from ..utils import dummy_flax_and_transformers_objects # noqa F403
|
| 305 |
+
|
| 306 |
+
_dummy_objects.update(get_objects_from_module(dummy_flax_and_transformers_objects))
|
| 307 |
+
else:
|
| 308 |
+
_import_structure["controlnet"].extend(["FlaxStableDiffusionControlNetPipeline"])
|
| 309 |
+
_import_structure["stable_diffusion"].extend(
|
| 310 |
+
[
|
| 311 |
+
"FlaxStableDiffusionImg2ImgPipeline",
|
| 312 |
+
"FlaxStableDiffusionInpaintPipeline",
|
| 313 |
+
"FlaxStableDiffusionPipeline",
|
| 314 |
+
]
|
| 315 |
+
)
|
| 316 |
+
_import_structure["stable_diffusion_xl"].extend(
|
| 317 |
+
[
|
| 318 |
+
"FlaxStableDiffusionXLPipeline",
|
| 319 |
+
]
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 323 |
+
try:
|
| 324 |
+
if not is_torch_available():
|
| 325 |
+
raise OptionalDependencyNotAvailable()
|
| 326 |
+
except OptionalDependencyNotAvailable:
|
| 327 |
+
from ..utils.dummy_pt_objects import * # noqa F403
|
| 328 |
+
|
| 329 |
+
else:
|
| 330 |
+
from .auto_pipeline import (
|
| 331 |
+
AutoPipelineForImage2Image,
|
| 332 |
+
AutoPipelineForInpainting,
|
| 333 |
+
AutoPipelineForText2Image,
|
| 334 |
+
)
|
| 335 |
+
from .consistency_models import ConsistencyModelPipeline
|
| 336 |
+
from .dance_diffusion import DanceDiffusionPipeline
|
| 337 |
+
from .ddim import DDIMPipeline
|
| 338 |
+
from .ddpm import DDPMPipeline
|
| 339 |
+
from .deprecated import KarrasVePipeline, LDMPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline
|
| 340 |
+
from .dit import DiTPipeline
|
| 341 |
+
from .latent_diffusion import LDMSuperResolutionPipeline
|
| 342 |
+
from .pipeline_utils import (
|
| 343 |
+
AudioPipelineOutput,
|
| 344 |
+
DiffusionPipeline,
|
| 345 |
+
ImagePipelineOutput,
|
| 346 |
+
StableDiffusionMixin,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
try:
|
| 350 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 351 |
+
raise OptionalDependencyNotAvailable()
|
| 352 |
+
except OptionalDependencyNotAvailable:
|
| 353 |
+
from ..utils.dummy_torch_and_librosa_objects import *
|
| 354 |
+
else:
|
| 355 |
+
from .deprecated import AudioDiffusionPipeline, Mel
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 359 |
+
raise OptionalDependencyNotAvailable()
|
| 360 |
+
except OptionalDependencyNotAvailable:
|
| 361 |
+
from ..utils.dummy_torch_and_transformers_objects import *
|
| 362 |
+
else:
|
| 363 |
+
from .amused import AmusedImg2ImgPipeline, AmusedInpaintPipeline, AmusedPipeline
|
| 364 |
+
from .animatediff import AnimateDiffPipeline, AnimateDiffVideoToVideoPipeline
|
| 365 |
+
from .audioldm import AudioLDMPipeline
|
| 366 |
+
from .audioldm2 import (
|
| 367 |
+
AudioLDM2Pipeline,
|
| 368 |
+
AudioLDM2ProjectionModel,
|
| 369 |
+
AudioLDM2UNet2DConditionModel,
|
| 370 |
+
)
|
| 371 |
+
from .blip_diffusion import BlipDiffusionPipeline
|
| 372 |
+
from .controlnet import (
|
| 373 |
+
BlipDiffusionControlNetPipeline,
|
| 374 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
| 375 |
+
StableDiffusionControlNetInpaintPipeline,
|
| 376 |
+
StableDiffusionControlNetPipeline,
|
| 377 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
| 378 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
| 379 |
+
StableDiffusionXLControlNetPipeline,
|
| 380 |
+
)
|
| 381 |
+
from .deepfloyd_if import (
|
| 382 |
+
IFImg2ImgPipeline,
|
| 383 |
+
IFImg2ImgSuperResolutionPipeline,
|
| 384 |
+
IFInpaintingPipeline,
|
| 385 |
+
IFInpaintingSuperResolutionPipeline,
|
| 386 |
+
IFPipeline,
|
| 387 |
+
IFSuperResolutionPipeline,
|
| 388 |
+
)
|
| 389 |
+
from .deprecated import (
|
| 390 |
+
AltDiffusionImg2ImgPipeline,
|
| 391 |
+
AltDiffusionPipeline,
|
| 392 |
+
CycleDiffusionPipeline,
|
| 393 |
+
StableDiffusionInpaintPipelineLegacy,
|
| 394 |
+
StableDiffusionModelEditingPipeline,
|
| 395 |
+
StableDiffusionParadigmsPipeline,
|
| 396 |
+
StableDiffusionPix2PixZeroPipeline,
|
| 397 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 398 |
+
VersatileDiffusionImageVariationPipeline,
|
| 399 |
+
VersatileDiffusionPipeline,
|
| 400 |
+
VersatileDiffusionTextToImagePipeline,
|
| 401 |
+
VQDiffusionPipeline,
|
| 402 |
+
)
|
| 403 |
+
from .i2vgen_xl import I2VGenXLPipeline
|
| 404 |
+
from .kandinsky import (
|
| 405 |
+
KandinskyCombinedPipeline,
|
| 406 |
+
KandinskyImg2ImgCombinedPipeline,
|
| 407 |
+
KandinskyImg2ImgPipeline,
|
| 408 |
+
KandinskyInpaintCombinedPipeline,
|
| 409 |
+
KandinskyInpaintPipeline,
|
| 410 |
+
KandinskyPipeline,
|
| 411 |
+
KandinskyPriorPipeline,
|
| 412 |
+
)
|
| 413 |
+
from .kandinsky2_2 import (
|
| 414 |
+
KandinskyV22CombinedPipeline,
|
| 415 |
+
KandinskyV22ControlnetImg2ImgPipeline,
|
| 416 |
+
KandinskyV22ControlnetPipeline,
|
| 417 |
+
KandinskyV22Img2ImgCombinedPipeline,
|
| 418 |
+
KandinskyV22Img2ImgPipeline,
|
| 419 |
+
KandinskyV22InpaintCombinedPipeline,
|
| 420 |
+
KandinskyV22InpaintPipeline,
|
| 421 |
+
KandinskyV22Pipeline,
|
| 422 |
+
KandinskyV22PriorEmb2EmbPipeline,
|
| 423 |
+
KandinskyV22PriorPipeline,
|
| 424 |
+
)
|
| 425 |
+
from .kandinsky3 import (
|
| 426 |
+
Kandinsky3Img2ImgPipeline,
|
| 427 |
+
Kandinsky3Pipeline,
|
| 428 |
+
)
|
| 429 |
+
from .latent_consistency_models import (
|
| 430 |
+
LatentConsistencyModelImg2ImgPipeline,
|
| 431 |
+
LatentConsistencyModelPipeline,
|
| 432 |
+
)
|
| 433 |
+
from .latent_diffusion import LDMTextToImagePipeline
|
| 434 |
+
from .ledits_pp import (
|
| 435 |
+
LEditsPPDiffusionPipelineOutput,
|
| 436 |
+
LEditsPPInversionPipelineOutput,
|
| 437 |
+
LEditsPPPipelineStableDiffusion,
|
| 438 |
+
LEditsPPPipelineStableDiffusionXL,
|
| 439 |
+
)
|
| 440 |
+
from .musicldm import MusicLDMPipeline
|
| 441 |
+
from .paint_by_example import PaintByExamplePipeline
|
| 442 |
+
from .pia import PIAPipeline
|
| 443 |
+
from .pixart_alpha import PixArtAlphaPipeline
|
| 444 |
+
from .semantic_stable_diffusion import SemanticStableDiffusionPipeline
|
| 445 |
+
from .shap_e import ShapEImg2ImgPipeline, ShapEPipeline
|
| 446 |
+
from .stable_cascade import (
|
| 447 |
+
StableCascadeCombinedPipeline,
|
| 448 |
+
StableCascadeDecoderPipeline,
|
| 449 |
+
StableCascadePriorPipeline,
|
| 450 |
+
)
|
| 451 |
+
from .stable_diffusion import (
|
| 452 |
+
CLIPImageProjection,
|
| 453 |
+
StableDiffusionDepth2ImgPipeline,
|
| 454 |
+
StableDiffusionImageVariationPipeline,
|
| 455 |
+
StableDiffusionImg2ImgPipeline,
|
| 456 |
+
StableDiffusionInpaintPipeline,
|
| 457 |
+
StableDiffusionInstructPix2PixPipeline,
|
| 458 |
+
StableDiffusionLatentUpscalePipeline,
|
| 459 |
+
StableDiffusionPipeline,
|
| 460 |
+
StableDiffusionUpscalePipeline,
|
| 461 |
+
StableUnCLIPImg2ImgPipeline,
|
| 462 |
+
StableUnCLIPPipeline,
|
| 463 |
+
)
|
| 464 |
+
from .stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline
|
| 465 |
+
from .stable_diffusion_diffedit import StableDiffusionDiffEditPipeline
|
| 466 |
+
from .stable_diffusion_gligen import StableDiffusionGLIGENPipeline, StableDiffusionGLIGENTextImagePipeline
|
| 467 |
+
from .stable_diffusion_ldm3d import StableDiffusionLDM3DPipeline
|
| 468 |
+
from .stable_diffusion_panorama import StableDiffusionPanoramaPipeline
|
| 469 |
+
from .stable_diffusion_safe import StableDiffusionPipelineSafe
|
| 470 |
+
from .stable_diffusion_sag import StableDiffusionSAGPipeline
|
| 471 |
+
from .stable_diffusion_xl import (
|
| 472 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 473 |
+
StableDiffusionXLInpaintPipeline,
|
| 474 |
+
StableDiffusionXLInstructPix2PixPipeline,
|
| 475 |
+
StableDiffusionXLPipeline,
|
| 476 |
+
)
|
| 477 |
+
from .stable_video_diffusion import StableVideoDiffusionPipeline
|
| 478 |
+
from .t2i_adapter import (
|
| 479 |
+
StableDiffusionAdapterPipeline,
|
| 480 |
+
StableDiffusionXLAdapterPipeline,
|
| 481 |
+
)
|
| 482 |
+
from .text_to_video_synthesis import (
|
| 483 |
+
TextToVideoSDPipeline,
|
| 484 |
+
TextToVideoZeroPipeline,
|
| 485 |
+
TextToVideoZeroSDXLPipeline,
|
| 486 |
+
VideoToVideoSDPipeline,
|
| 487 |
+
)
|
| 488 |
+
from .unclip import UnCLIPImageVariationPipeline, UnCLIPPipeline
|
| 489 |
+
from .unidiffuser import (
|
| 490 |
+
ImageTextPipelineOutput,
|
| 491 |
+
UniDiffuserModel,
|
| 492 |
+
UniDiffuserPipeline,
|
| 493 |
+
UniDiffuserTextDecoder,
|
| 494 |
+
)
|
| 495 |
+
from .wuerstchen import (
|
| 496 |
+
WuerstchenCombinedPipeline,
|
| 497 |
+
WuerstchenDecoderPipeline,
|
| 498 |
+
WuerstchenPriorPipeline,
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
try:
|
| 502 |
+
if not is_onnx_available():
|
| 503 |
+
raise OptionalDependencyNotAvailable()
|
| 504 |
+
except OptionalDependencyNotAvailable:
|
| 505 |
+
from ..utils.dummy_onnx_objects import * # noqa F403
|
| 506 |
+
|
| 507 |
+
else:
|
| 508 |
+
from .onnx_utils import OnnxRuntimeModel
|
| 509 |
+
|
| 510 |
+
try:
|
| 511 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 512 |
+
raise OptionalDependencyNotAvailable()
|
| 513 |
+
except OptionalDependencyNotAvailable:
|
| 514 |
+
from ..utils.dummy_torch_and_transformers_and_onnx_objects import *
|
| 515 |
+
else:
|
| 516 |
+
from .stable_diffusion import (
|
| 517 |
+
OnnxStableDiffusionImg2ImgPipeline,
|
| 518 |
+
OnnxStableDiffusionInpaintPipeline,
|
| 519 |
+
OnnxStableDiffusionPipeline,
|
| 520 |
+
OnnxStableDiffusionUpscalePipeline,
|
| 521 |
+
StableDiffusionOnnxPipeline,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
try:
|
| 525 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 526 |
+
raise OptionalDependencyNotAvailable()
|
| 527 |
+
except OptionalDependencyNotAvailable:
|
| 528 |
+
from ..utils.dummy_torch_and_transformers_and_k_diffusion_objects import *
|
| 529 |
+
else:
|
| 530 |
+
from .stable_diffusion_k_diffusion import (
|
| 531 |
+
StableDiffusionKDiffusionPipeline,
|
| 532 |
+
StableDiffusionXLKDiffusionPipeline,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
try:
|
| 536 |
+
if not is_flax_available():
|
| 537 |
+
raise OptionalDependencyNotAvailable()
|
| 538 |
+
except OptionalDependencyNotAvailable:
|
| 539 |
+
from ..utils.dummy_flax_objects import * # noqa F403
|
| 540 |
+
else:
|
| 541 |
+
from .pipeline_flax_utils import FlaxDiffusionPipeline
|
| 542 |
+
|
| 543 |
+
try:
|
| 544 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 545 |
+
raise OptionalDependencyNotAvailable()
|
| 546 |
+
except OptionalDependencyNotAvailable:
|
| 547 |
+
from ..utils.dummy_flax_and_transformers_objects import *
|
| 548 |
+
else:
|
| 549 |
+
from .controlnet import FlaxStableDiffusionControlNetPipeline
|
| 550 |
+
from .stable_diffusion import (
|
| 551 |
+
FlaxStableDiffusionImg2ImgPipeline,
|
| 552 |
+
FlaxStableDiffusionInpaintPipeline,
|
| 553 |
+
FlaxStableDiffusionPipeline,
|
| 554 |
+
)
|
| 555 |
+
from .stable_diffusion_xl import (
|
| 556 |
+
FlaxStableDiffusionXLPipeline,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
try:
|
| 560 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 561 |
+
raise OptionalDependencyNotAvailable()
|
| 562 |
+
except OptionalDependencyNotAvailable:
|
| 563 |
+
from ..utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
|
| 564 |
+
|
| 565 |
+
else:
|
| 566 |
+
from .deprecated import (
|
| 567 |
+
MidiProcessor,
|
| 568 |
+
SpectrogramDiffusionPipeline,
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
else:
|
| 572 |
+
import sys
|
| 573 |
+
|
| 574 |
+
sys.modules[__name__] = _LazyModule(
|
| 575 |
+
__name__,
|
| 576 |
+
globals()["__file__"],
|
| 577 |
+
_import_structure,
|
| 578 |
+
module_spec=__spec__,
|
| 579 |
+
)
|
| 580 |
+
for name, value in _dummy_objects.items():
|
| 581 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/auto_pipeline.py
ADDED
|
@@ -0,0 +1,987 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.utils import validate_hf_hub_args
|
| 19 |
+
|
| 20 |
+
from ..configuration_utils import ConfigMixin
|
| 21 |
+
from .controlnet import (
|
| 22 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
| 23 |
+
StableDiffusionControlNetInpaintPipeline,
|
| 24 |
+
StableDiffusionControlNetPipeline,
|
| 25 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
| 26 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
| 27 |
+
StableDiffusionXLControlNetPipeline,
|
| 28 |
+
)
|
| 29 |
+
from .deepfloyd_if import IFImg2ImgPipeline, IFInpaintingPipeline, IFPipeline
|
| 30 |
+
from .kandinsky import (
|
| 31 |
+
KandinskyCombinedPipeline,
|
| 32 |
+
KandinskyImg2ImgCombinedPipeline,
|
| 33 |
+
KandinskyImg2ImgPipeline,
|
| 34 |
+
KandinskyInpaintCombinedPipeline,
|
| 35 |
+
KandinskyInpaintPipeline,
|
| 36 |
+
KandinskyPipeline,
|
| 37 |
+
)
|
| 38 |
+
from .kandinsky2_2 import (
|
| 39 |
+
KandinskyV22CombinedPipeline,
|
| 40 |
+
KandinskyV22Img2ImgCombinedPipeline,
|
| 41 |
+
KandinskyV22Img2ImgPipeline,
|
| 42 |
+
KandinskyV22InpaintCombinedPipeline,
|
| 43 |
+
KandinskyV22InpaintPipeline,
|
| 44 |
+
KandinskyV22Pipeline,
|
| 45 |
+
)
|
| 46 |
+
from .kandinsky3 import Kandinsky3Img2ImgPipeline, Kandinsky3Pipeline
|
| 47 |
+
from .latent_consistency_models import LatentConsistencyModelImg2ImgPipeline, LatentConsistencyModelPipeline
|
| 48 |
+
from .pixart_alpha import PixArtAlphaPipeline
|
| 49 |
+
from .stable_diffusion import (
|
| 50 |
+
StableDiffusionImg2ImgPipeline,
|
| 51 |
+
StableDiffusionInpaintPipeline,
|
| 52 |
+
StableDiffusionPipeline,
|
| 53 |
+
)
|
| 54 |
+
from .stable_diffusion_xl import (
|
| 55 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 56 |
+
StableDiffusionXLInpaintPipeline,
|
| 57 |
+
StableDiffusionXLPipeline,
|
| 58 |
+
)
|
| 59 |
+
from .wuerstchen import WuerstchenCombinedPipeline, WuerstchenDecoderPipeline
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
AUTO_TEXT2IMAGE_PIPELINES_MAPPING = OrderedDict(
|
| 63 |
+
[
|
| 64 |
+
("stable-diffusion", StableDiffusionPipeline),
|
| 65 |
+
("stable-diffusion-xl", StableDiffusionXLPipeline),
|
| 66 |
+
("if", IFPipeline),
|
| 67 |
+
("kandinsky", KandinskyCombinedPipeline),
|
| 68 |
+
("kandinsky22", KandinskyV22CombinedPipeline),
|
| 69 |
+
("kandinsky3", Kandinsky3Pipeline),
|
| 70 |
+
("stable-diffusion-controlnet", StableDiffusionControlNetPipeline),
|
| 71 |
+
("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetPipeline),
|
| 72 |
+
("wuerstchen", WuerstchenCombinedPipeline),
|
| 73 |
+
("lcm", LatentConsistencyModelPipeline),
|
| 74 |
+
("pixart", PixArtAlphaPipeline),
|
| 75 |
+
]
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING = OrderedDict(
|
| 79 |
+
[
|
| 80 |
+
("stable-diffusion", StableDiffusionImg2ImgPipeline),
|
| 81 |
+
("stable-diffusion-xl", StableDiffusionXLImg2ImgPipeline),
|
| 82 |
+
("if", IFImg2ImgPipeline),
|
| 83 |
+
("kandinsky", KandinskyImg2ImgCombinedPipeline),
|
| 84 |
+
("kandinsky22", KandinskyV22Img2ImgCombinedPipeline),
|
| 85 |
+
("kandinsky3", Kandinsky3Img2ImgPipeline),
|
| 86 |
+
("stable-diffusion-controlnet", StableDiffusionControlNetImg2ImgPipeline),
|
| 87 |
+
("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetImg2ImgPipeline),
|
| 88 |
+
("lcm", LatentConsistencyModelImg2ImgPipeline),
|
| 89 |
+
]
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
AUTO_INPAINT_PIPELINES_MAPPING = OrderedDict(
|
| 93 |
+
[
|
| 94 |
+
("stable-diffusion", StableDiffusionInpaintPipeline),
|
| 95 |
+
("stable-diffusion-xl", StableDiffusionXLInpaintPipeline),
|
| 96 |
+
("if", IFInpaintingPipeline),
|
| 97 |
+
("kandinsky", KandinskyInpaintCombinedPipeline),
|
| 98 |
+
("kandinsky22", KandinskyV22InpaintCombinedPipeline),
|
| 99 |
+
("stable-diffusion-controlnet", StableDiffusionControlNetInpaintPipeline),
|
| 100 |
+
("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetInpaintPipeline),
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
_AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING = OrderedDict(
|
| 105 |
+
[
|
| 106 |
+
("kandinsky", KandinskyPipeline),
|
| 107 |
+
("kandinsky22", KandinskyV22Pipeline),
|
| 108 |
+
("wuerstchen", WuerstchenDecoderPipeline),
|
| 109 |
+
]
|
| 110 |
+
)
|
| 111 |
+
_AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING = OrderedDict(
|
| 112 |
+
[
|
| 113 |
+
("kandinsky", KandinskyImg2ImgPipeline),
|
| 114 |
+
("kandinsky22", KandinskyV22Img2ImgPipeline),
|
| 115 |
+
]
|
| 116 |
+
)
|
| 117 |
+
_AUTO_INPAINT_DECODER_PIPELINES_MAPPING = OrderedDict(
|
| 118 |
+
[
|
| 119 |
+
("kandinsky", KandinskyInpaintPipeline),
|
| 120 |
+
("kandinsky22", KandinskyV22InpaintPipeline),
|
| 121 |
+
]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
SUPPORTED_TASKS_MAPPINGS = [
|
| 125 |
+
AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
|
| 126 |
+
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
|
| 127 |
+
AUTO_INPAINT_PIPELINES_MAPPING,
|
| 128 |
+
_AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING,
|
| 129 |
+
_AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING,
|
| 130 |
+
_AUTO_INPAINT_DECODER_PIPELINES_MAPPING,
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _get_connected_pipeline(pipeline_cls):
|
| 135 |
+
# for now connected pipelines can only be loaded from decoder pipelines, such as kandinsky-community/kandinsky-2-2-decoder
|
| 136 |
+
if pipeline_cls in _AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING.values():
|
| 137 |
+
return _get_task_class(
|
| 138 |
+
AUTO_TEXT2IMAGE_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False
|
| 139 |
+
)
|
| 140 |
+
if pipeline_cls in _AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING.values():
|
| 141 |
+
return _get_task_class(
|
| 142 |
+
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False
|
| 143 |
+
)
|
| 144 |
+
if pipeline_cls in _AUTO_INPAINT_DECODER_PIPELINES_MAPPING.values():
|
| 145 |
+
return _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _get_task_class(mapping, pipeline_class_name, throw_error_if_not_exist: bool = True):
|
| 149 |
+
def get_model(pipeline_class_name):
|
| 150 |
+
for task_mapping in SUPPORTED_TASKS_MAPPINGS:
|
| 151 |
+
for model_name, pipeline in task_mapping.items():
|
| 152 |
+
if pipeline.__name__ == pipeline_class_name:
|
| 153 |
+
return model_name
|
| 154 |
+
|
| 155 |
+
model_name = get_model(pipeline_class_name)
|
| 156 |
+
|
| 157 |
+
if model_name is not None:
|
| 158 |
+
task_class = mapping.get(model_name, None)
|
| 159 |
+
if task_class is not None:
|
| 160 |
+
return task_class
|
| 161 |
+
|
| 162 |
+
if throw_error_if_not_exist:
|
| 163 |
+
raise ValueError(f"AutoPipeline can't find a pipeline linked to {pipeline_class_name} for {model_name}")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class AutoPipelineForText2Image(ConfigMixin):
|
| 167 |
+
r"""
|
| 168 |
+
|
| 169 |
+
[`AutoPipelineForText2Image`] is a generic pipeline class that instantiates a text-to-image pipeline class. The
|
| 170 |
+
specific underlying pipeline class is automatically selected from either the
|
| 171 |
+
[`~AutoPipelineForText2Image.from_pretrained`] or [`~AutoPipelineForText2Image.from_pipe`] methods.
|
| 172 |
+
|
| 173 |
+
This class cannot be instantiated using `__init__()` (throws an error).
|
| 174 |
+
|
| 175 |
+
Class attributes:
|
| 176 |
+
|
| 177 |
+
- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
|
| 178 |
+
diffusion pipeline's components.
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
config_name = "model_index.json"
|
| 183 |
+
|
| 184 |
+
def __init__(self, *args, **kwargs):
|
| 185 |
+
raise EnvironmentError(
|
| 186 |
+
f"{self.__class__.__name__} is designed to be instantiated "
|
| 187 |
+
f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
|
| 188 |
+
f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
@validate_hf_hub_args
|
| 193 |
+
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
|
| 194 |
+
r"""
|
| 195 |
+
Instantiates a text-to-image Pytorch diffusion pipeline from pretrained pipeline weight.
|
| 196 |
+
|
| 197 |
+
The from_pretrained() method takes care of returning the correct pipeline class instance by:
|
| 198 |
+
1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
|
| 199 |
+
config object
|
| 200 |
+
2. Find the text-to-image pipeline linked to the pipeline class using pattern matching on pipeline class
|
| 201 |
+
name.
|
| 202 |
+
|
| 203 |
+
If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetPipeline`] object.
|
| 204 |
+
|
| 205 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 206 |
+
|
| 207 |
+
If you get the error message below, you need to finetune the weights for your downstream task:
|
| 208 |
+
|
| 209 |
+
```
|
| 210 |
+
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
|
| 211 |
+
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
|
| 212 |
+
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
Parameters:
|
| 216 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
| 217 |
+
Can be either:
|
| 218 |
+
|
| 219 |
+
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
|
| 220 |
+
hosted on the Hub.
|
| 221 |
+
- A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
|
| 222 |
+
saved using
|
| 223 |
+
[`~DiffusionPipeline.save_pretrained`].
|
| 224 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 225 |
+
Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the
|
| 226 |
+
dtype is automatically derived from the model's weights.
|
| 227 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 228 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 229 |
+
cached versions if they exist.
|
| 230 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 231 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 232 |
+
is not used.
|
| 233 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 234 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 235 |
+
incompletely downloaded files are deleted.
|
| 236 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 237 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 238 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 239 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 240 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 241 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 242 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 243 |
+
won't be downloaded from the Hub.
|
| 244 |
+
token (`str` or *bool*, *optional*):
|
| 245 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 246 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 247 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 248 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 249 |
+
allowed by Git.
|
| 250 |
+
custom_revision (`str`, *optional*, defaults to `"main"`):
|
| 251 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
|
| 252 |
+
`revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
|
| 253 |
+
custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
|
| 254 |
+
mirror (`str`, *optional*):
|
| 255 |
+
Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
|
| 256 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 257 |
+
information.
|
| 258 |
+
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
| 259 |
+
A map that specifies where each submodule should go. It doesn’t need to be defined for each
|
| 260 |
+
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
|
| 261 |
+
same device.
|
| 262 |
+
|
| 263 |
+
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
|
| 264 |
+
more information about each option see [designing a device
|
| 265 |
+
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
|
| 266 |
+
max_memory (`Dict`, *optional*):
|
| 267 |
+
A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
|
| 268 |
+
each GPU and the available CPU RAM if unset.
|
| 269 |
+
offload_folder (`str` or `os.PathLike`, *optional*):
|
| 270 |
+
The path to offload weights if device_map contains the value `"disk"`.
|
| 271 |
+
offload_state_dict (`bool`, *optional*):
|
| 272 |
+
If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
|
| 273 |
+
the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
|
| 274 |
+
when there is some disk offload.
|
| 275 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 276 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 277 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 278 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 279 |
+
argument to `True` will raise an error.
|
| 280 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 281 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 282 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 283 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 284 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 285 |
+
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
|
| 286 |
+
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
|
| 287 |
+
below for more information.
|
| 288 |
+
variant (`str`, *optional*):
|
| 289 |
+
Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
|
| 290 |
+
loading `from_flax`.
|
| 291 |
+
|
| 292 |
+
<Tip>
|
| 293 |
+
|
| 294 |
+
To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
|
| 295 |
+
`huggingface-cli login`.
|
| 296 |
+
|
| 297 |
+
</Tip>
|
| 298 |
+
|
| 299 |
+
Examples:
|
| 300 |
+
|
| 301 |
+
```py
|
| 302 |
+
>>> from diffusers import AutoPipelineForText2Image
|
| 303 |
+
|
| 304 |
+
>>> pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
|
| 305 |
+
>>> image = pipeline(prompt).images[0]
|
| 306 |
+
```
|
| 307 |
+
"""
|
| 308 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 309 |
+
force_download = kwargs.pop("force_download", False)
|
| 310 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 311 |
+
proxies = kwargs.pop("proxies", None)
|
| 312 |
+
token = kwargs.pop("token", None)
|
| 313 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 314 |
+
revision = kwargs.pop("revision", None)
|
| 315 |
+
|
| 316 |
+
load_config_kwargs = {
|
| 317 |
+
"cache_dir": cache_dir,
|
| 318 |
+
"force_download": force_download,
|
| 319 |
+
"resume_download": resume_download,
|
| 320 |
+
"proxies": proxies,
|
| 321 |
+
"token": token,
|
| 322 |
+
"local_files_only": local_files_only,
|
| 323 |
+
"revision": revision,
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
|
| 327 |
+
orig_class_name = config["_class_name"]
|
| 328 |
+
|
| 329 |
+
if "controlnet" in kwargs:
|
| 330 |
+
orig_class_name = config["_class_name"].replace("Pipeline", "ControlNetPipeline")
|
| 331 |
+
|
| 332 |
+
text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, orig_class_name)
|
| 333 |
+
|
| 334 |
+
kwargs = {**load_config_kwargs, **kwargs}
|
| 335 |
+
return text_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)
|
| 336 |
+
|
| 337 |
+
@classmethod
|
| 338 |
+
def from_pipe(cls, pipeline, **kwargs):
|
| 339 |
+
r"""
|
| 340 |
+
Instantiates a text-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
|
| 341 |
+
|
| 342 |
+
The from_pipe() method takes care of returning the correct pipeline class instance by finding the text-to-image
|
| 343 |
+
pipeline linked to the pipeline class using pattern matching on pipeline class name.
|
| 344 |
+
|
| 345 |
+
All the modules the pipeline contains will be used to initialize the new pipeline without reallocating
|
| 346 |
+
additional memory.
|
| 347 |
+
|
| 348 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 349 |
+
|
| 350 |
+
Parameters:
|
| 351 |
+
pipeline (`DiffusionPipeline`):
|
| 352 |
+
an instantiated `DiffusionPipeline` object
|
| 353 |
+
|
| 354 |
+
```py
|
| 355 |
+
>>> from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
|
| 356 |
+
|
| 357 |
+
>>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
|
| 358 |
+
... "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
|
| 359 |
+
... )
|
| 360 |
+
|
| 361 |
+
>>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i)
|
| 362 |
+
>>> image = pipe_t2i(prompt).images[0]
|
| 363 |
+
```
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
original_config = dict(pipeline.config)
|
| 367 |
+
original_cls_name = pipeline.__class__.__name__
|
| 368 |
+
|
| 369 |
+
# derive the pipeline class to instantiate
|
| 370 |
+
text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, original_cls_name)
|
| 371 |
+
|
| 372 |
+
if "controlnet" in kwargs:
|
| 373 |
+
if kwargs["controlnet"] is not None:
|
| 374 |
+
text_2_image_cls = _get_task_class(
|
| 375 |
+
AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
|
| 376 |
+
text_2_image_cls.__name__.replace("ControlNet", "").replace("Pipeline", "ControlNetPipeline"),
|
| 377 |
+
)
|
| 378 |
+
else:
|
| 379 |
+
text_2_image_cls = _get_task_class(
|
| 380 |
+
AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
|
| 381 |
+
text_2_image_cls.__name__.replace("ControlNetPipeline", "Pipeline"),
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# define expected module and optional kwargs given the pipeline signature
|
| 385 |
+
expected_modules, optional_kwargs = text_2_image_cls._get_signature_keys(text_2_image_cls)
|
| 386 |
+
|
| 387 |
+
pretrained_model_name_or_path = original_config.pop("_name_or_path", None)
|
| 388 |
+
|
| 389 |
+
# allow users pass modules in `kwargs` to override the original pipeline's components
|
| 390 |
+
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
|
| 391 |
+
original_class_obj = {
|
| 392 |
+
k: pipeline.components[k]
|
| 393 |
+
for k, v in pipeline.components.items()
|
| 394 |
+
if k in expected_modules and k not in passed_class_obj
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
# allow users pass optional kwargs to override the original pipelines config attribute
|
| 398 |
+
passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
|
| 399 |
+
original_pipe_kwargs = {
|
| 400 |
+
k: original_config[k]
|
| 401 |
+
for k, v in original_config.items()
|
| 402 |
+
if k in optional_kwargs and k not in passed_pipe_kwargs
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
# config that were not expected by original pipeline is stored as private attribute
|
| 406 |
+
# we will pass them as optional arguments if they can be accepted by the pipeline
|
| 407 |
+
additional_pipe_kwargs = [
|
| 408 |
+
k[1:]
|
| 409 |
+
for k in original_config.keys()
|
| 410 |
+
if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
|
| 411 |
+
]
|
| 412 |
+
for k in additional_pipe_kwargs:
|
| 413 |
+
original_pipe_kwargs[k] = original_config.pop(f"_{k}")
|
| 414 |
+
|
| 415 |
+
text_2_image_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}
|
| 416 |
+
|
| 417 |
+
# store unused config as private attribute
|
| 418 |
+
unused_original_config = {
|
| 419 |
+
f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
|
| 420 |
+
for k, v in original_config.items()
|
| 421 |
+
if k not in text_2_image_kwargs
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(text_2_image_kwargs.keys())
|
| 425 |
+
|
| 426 |
+
if len(missing_modules) > 0:
|
| 427 |
+
raise ValueError(
|
| 428 |
+
f"Pipeline {text_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
model = text_2_image_cls(**text_2_image_kwargs)
|
| 432 |
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
|
| 433 |
+
model.register_to_config(**unused_original_config)
|
| 434 |
+
|
| 435 |
+
return model
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class AutoPipelineForImage2Image(ConfigMixin):
|
| 439 |
+
r"""
|
| 440 |
+
|
| 441 |
+
[`AutoPipelineForImage2Image`] is a generic pipeline class that instantiates an image-to-image pipeline class. The
|
| 442 |
+
specific underlying pipeline class is automatically selected from either the
|
| 443 |
+
[`~AutoPipelineForImage2Image.from_pretrained`] or [`~AutoPipelineForImage2Image.from_pipe`] methods.
|
| 444 |
+
|
| 445 |
+
This class cannot be instantiated using `__init__()` (throws an error).
|
| 446 |
+
|
| 447 |
+
Class attributes:
|
| 448 |
+
|
| 449 |
+
- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
|
| 450 |
+
diffusion pipeline's components.
|
| 451 |
+
|
| 452 |
+
"""
|
| 453 |
+
|
| 454 |
+
config_name = "model_index.json"
|
| 455 |
+
|
| 456 |
+
def __init__(self, *args, **kwargs):
|
| 457 |
+
raise EnvironmentError(
|
| 458 |
+
f"{self.__class__.__name__} is designed to be instantiated "
|
| 459 |
+
f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
|
| 460 |
+
f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
@classmethod
|
| 464 |
+
@validate_hf_hub_args
|
| 465 |
+
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
|
| 466 |
+
r"""
|
| 467 |
+
Instantiates a image-to-image Pytorch diffusion pipeline from pretrained pipeline weight.
|
| 468 |
+
|
| 469 |
+
The from_pretrained() method takes care of returning the correct pipeline class instance by:
|
| 470 |
+
1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
|
| 471 |
+
config object
|
| 472 |
+
2. Find the image-to-image pipeline linked to the pipeline class using pattern matching on pipeline class
|
| 473 |
+
name.
|
| 474 |
+
|
| 475 |
+
If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetImg2ImgPipeline`]
|
| 476 |
+
object.
|
| 477 |
+
|
| 478 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 479 |
+
|
| 480 |
+
If you get the error message below, you need to finetune the weights for your downstream task:
|
| 481 |
+
|
| 482 |
+
```
|
| 483 |
+
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
|
| 484 |
+
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
|
| 485 |
+
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
|
| 486 |
+
```
|
| 487 |
+
|
| 488 |
+
Parameters:
|
| 489 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
| 490 |
+
Can be either:
|
| 491 |
+
|
| 492 |
+
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
|
| 493 |
+
hosted on the Hub.
|
| 494 |
+
- A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
|
| 495 |
+
saved using
|
| 496 |
+
[`~DiffusionPipeline.save_pretrained`].
|
| 497 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 498 |
+
Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the
|
| 499 |
+
dtype is automatically derived from the model's weights.
|
| 500 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 501 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 502 |
+
cached versions if they exist.
|
| 503 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 504 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 505 |
+
is not used.
|
| 506 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 507 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 508 |
+
incompletely downloaded files are deleted.
|
| 509 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 510 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 511 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 512 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 513 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 514 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 515 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 516 |
+
won't be downloaded from the Hub.
|
| 517 |
+
token (`str` or *bool*, *optional*):
|
| 518 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 519 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 520 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 521 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 522 |
+
allowed by Git.
|
| 523 |
+
custom_revision (`str`, *optional*, defaults to `"main"`):
|
| 524 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
|
| 525 |
+
`revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
|
| 526 |
+
custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
|
| 527 |
+
mirror (`str`, *optional*):
|
| 528 |
+
Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
|
| 529 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 530 |
+
information.
|
| 531 |
+
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
| 532 |
+
A map that specifies where each submodule should go. It doesn’t need to be defined for each
|
| 533 |
+
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
|
| 534 |
+
same device.
|
| 535 |
+
|
| 536 |
+
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
|
| 537 |
+
more information about each option see [designing a device
|
| 538 |
+
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
|
| 539 |
+
max_memory (`Dict`, *optional*):
|
| 540 |
+
A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
|
| 541 |
+
each GPU and the available CPU RAM if unset.
|
| 542 |
+
offload_folder (`str` or `os.PathLike`, *optional*):
|
| 543 |
+
The path to offload weights if device_map contains the value `"disk"`.
|
| 544 |
+
offload_state_dict (`bool`, *optional*):
|
| 545 |
+
If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
|
| 546 |
+
the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
|
| 547 |
+
when there is some disk offload.
|
| 548 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 549 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 550 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 551 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 552 |
+
argument to `True` will raise an error.
|
| 553 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 554 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 555 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 556 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 557 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 558 |
+
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
|
| 559 |
+
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
|
| 560 |
+
below for more information.
|
| 561 |
+
variant (`str`, *optional*):
|
| 562 |
+
Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
|
| 563 |
+
loading `from_flax`.
|
| 564 |
+
|
| 565 |
+
<Tip>
|
| 566 |
+
|
| 567 |
+
To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
|
| 568 |
+
`huggingface-cli login`.
|
| 569 |
+
|
| 570 |
+
</Tip>
|
| 571 |
+
|
| 572 |
+
Examples:
|
| 573 |
+
|
| 574 |
+
```py
|
| 575 |
+
>>> from diffusers import AutoPipelineForImage2Image
|
| 576 |
+
|
| 577 |
+
>>> pipeline = AutoPipelineForImage2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
|
| 578 |
+
>>> image = pipeline(prompt, image).images[0]
|
| 579 |
+
```
|
| 580 |
+
"""
|
| 581 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 582 |
+
force_download = kwargs.pop("force_download", False)
|
| 583 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 584 |
+
proxies = kwargs.pop("proxies", None)
|
| 585 |
+
token = kwargs.pop("token", None)
|
| 586 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 587 |
+
revision = kwargs.pop("revision", None)
|
| 588 |
+
|
| 589 |
+
load_config_kwargs = {
|
| 590 |
+
"cache_dir": cache_dir,
|
| 591 |
+
"force_download": force_download,
|
| 592 |
+
"resume_download": resume_download,
|
| 593 |
+
"proxies": proxies,
|
| 594 |
+
"token": token,
|
| 595 |
+
"local_files_only": local_files_only,
|
| 596 |
+
"revision": revision,
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
|
| 600 |
+
orig_class_name = config["_class_name"]
|
| 601 |
+
|
| 602 |
+
if "controlnet" in kwargs:
|
| 603 |
+
orig_class_name = config["_class_name"].replace("Pipeline", "ControlNetPipeline")
|
| 604 |
+
|
| 605 |
+
image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, orig_class_name)
|
| 606 |
+
|
| 607 |
+
kwargs = {**load_config_kwargs, **kwargs}
|
| 608 |
+
return image_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)
|
| 609 |
+
|
| 610 |
+
@classmethod
|
| 611 |
+
def from_pipe(cls, pipeline, **kwargs):
|
| 612 |
+
r"""
|
| 613 |
+
Instantiates a image-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
|
| 614 |
+
|
| 615 |
+
The from_pipe() method takes care of returning the correct pipeline class instance by finding the
|
| 616 |
+
image-to-image pipeline linked to the pipeline class using pattern matching on pipeline class name.
|
| 617 |
+
|
| 618 |
+
All the modules the pipeline contains will be used to initialize the new pipeline without reallocating
|
| 619 |
+
additional memory.
|
| 620 |
+
|
| 621 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 622 |
+
|
| 623 |
+
Parameters:
|
| 624 |
+
pipeline (`DiffusionPipeline`):
|
| 625 |
+
an instantiated `DiffusionPipeline` object
|
| 626 |
+
|
| 627 |
+
Examples:
|
| 628 |
+
|
| 629 |
+
```py
|
| 630 |
+
>>> from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
|
| 631 |
+
|
| 632 |
+
>>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
|
| 633 |
+
... "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
|
| 634 |
+
... )
|
| 635 |
+
|
| 636 |
+
>>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
|
| 637 |
+
>>> image = pipe_i2i(prompt, image).images[0]
|
| 638 |
+
```
|
| 639 |
+
"""
|
| 640 |
+
|
| 641 |
+
original_config = dict(pipeline.config)
|
| 642 |
+
original_cls_name = pipeline.__class__.__name__
|
| 643 |
+
|
| 644 |
+
# derive the pipeline class to instantiate
|
| 645 |
+
image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, original_cls_name)
|
| 646 |
+
|
| 647 |
+
if "controlnet" in kwargs:
|
| 648 |
+
if kwargs["controlnet"] is not None:
|
| 649 |
+
image_2_image_cls = _get_task_class(
|
| 650 |
+
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
|
| 651 |
+
image_2_image_cls.__name__.replace("ControlNet", "").replace(
|
| 652 |
+
"Img2ImgPipeline", "ControlNetImg2ImgPipeline"
|
| 653 |
+
),
|
| 654 |
+
)
|
| 655 |
+
else:
|
| 656 |
+
image_2_image_cls = _get_task_class(
|
| 657 |
+
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
|
| 658 |
+
image_2_image_cls.__name__.replace("ControlNetImg2ImgPipeline", "Img2ImgPipeline"),
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# define expected module and optional kwargs given the pipeline signature
|
| 662 |
+
expected_modules, optional_kwargs = image_2_image_cls._get_signature_keys(image_2_image_cls)
|
| 663 |
+
|
| 664 |
+
pretrained_model_name_or_path = original_config.pop("_name_or_path", None)
|
| 665 |
+
|
| 666 |
+
# allow users pass modules in `kwargs` to override the original pipeline's components
|
| 667 |
+
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
|
| 668 |
+
original_class_obj = {
|
| 669 |
+
k: pipeline.components[k]
|
| 670 |
+
for k, v in pipeline.components.items()
|
| 671 |
+
if k in expected_modules and k not in passed_class_obj
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
# allow users pass optional kwargs to override the original pipelines config attribute
|
| 675 |
+
passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
|
| 676 |
+
original_pipe_kwargs = {
|
| 677 |
+
k: original_config[k]
|
| 678 |
+
for k, v in original_config.items()
|
| 679 |
+
if k in optional_kwargs and k not in passed_pipe_kwargs
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
# config attribute that were not expected by original pipeline is stored as its private attribute
|
| 683 |
+
# we will pass them as optional arguments if they can be accepted by the pipeline
|
| 684 |
+
additional_pipe_kwargs = [
|
| 685 |
+
k[1:]
|
| 686 |
+
for k in original_config.keys()
|
| 687 |
+
if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
|
| 688 |
+
]
|
| 689 |
+
for k in additional_pipe_kwargs:
|
| 690 |
+
original_pipe_kwargs[k] = original_config.pop(f"_{k}")
|
| 691 |
+
|
| 692 |
+
image_2_image_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}
|
| 693 |
+
|
| 694 |
+
# store unused config as private attribute
|
| 695 |
+
unused_original_config = {
|
| 696 |
+
f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
|
| 697 |
+
for k, v in original_config.items()
|
| 698 |
+
if k not in image_2_image_kwargs
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(image_2_image_kwargs.keys())
|
| 702 |
+
|
| 703 |
+
if len(missing_modules) > 0:
|
| 704 |
+
raise ValueError(
|
| 705 |
+
f"Pipeline {image_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
model = image_2_image_cls(**image_2_image_kwargs)
|
| 709 |
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
|
| 710 |
+
model.register_to_config(**unused_original_config)
|
| 711 |
+
|
| 712 |
+
return model
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
class AutoPipelineForInpainting(ConfigMixin):
|
| 716 |
+
r"""
|
| 717 |
+
|
| 718 |
+
[`AutoPipelineForInpainting`] is a generic pipeline class that instantiates an inpainting pipeline class. The
|
| 719 |
+
specific underlying pipeline class is automatically selected from either the
|
| 720 |
+
[`~AutoPipelineForInpainting.from_pretrained`] or [`~AutoPipelineForInpainting.from_pipe`] methods.
|
| 721 |
+
|
| 722 |
+
This class cannot be instantiated using `__init__()` (throws an error).
|
| 723 |
+
|
| 724 |
+
Class attributes:
|
| 725 |
+
|
| 726 |
+
- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
|
| 727 |
+
diffusion pipeline's components.
|
| 728 |
+
|
| 729 |
+
"""
|
| 730 |
+
|
| 731 |
+
config_name = "model_index.json"
|
| 732 |
+
|
| 733 |
+
def __init__(self, *args, **kwargs):
|
| 734 |
+
raise EnvironmentError(
|
| 735 |
+
f"{self.__class__.__name__} is designed to be instantiated "
|
| 736 |
+
f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
|
| 737 |
+
f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
@classmethod
|
| 741 |
+
@validate_hf_hub_args
|
| 742 |
+
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
|
| 743 |
+
r"""
|
| 744 |
+
Instantiates a inpainting Pytorch diffusion pipeline from pretrained pipeline weight.
|
| 745 |
+
|
| 746 |
+
The from_pretrained() method takes care of returning the correct pipeline class instance by:
|
| 747 |
+
1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
|
| 748 |
+
config object
|
| 749 |
+
2. Find the inpainting pipeline linked to the pipeline class using pattern matching on pipeline class name.
|
| 750 |
+
|
| 751 |
+
If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetInpaintPipeline`]
|
| 752 |
+
object.
|
| 753 |
+
|
| 754 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 755 |
+
|
| 756 |
+
If you get the error message below, you need to finetune the weights for your downstream task:
|
| 757 |
+
|
| 758 |
+
```
|
| 759 |
+
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
|
| 760 |
+
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
|
| 761 |
+
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
|
| 762 |
+
```
|
| 763 |
+
|
| 764 |
+
Parameters:
|
| 765 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
| 766 |
+
Can be either:
|
| 767 |
+
|
| 768 |
+
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
|
| 769 |
+
hosted on the Hub.
|
| 770 |
+
- A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
|
| 771 |
+
saved using
|
| 772 |
+
[`~DiffusionPipeline.save_pretrained`].
|
| 773 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 774 |
+
Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the
|
| 775 |
+
dtype is automatically derived from the model's weights.
|
| 776 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 777 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 778 |
+
cached versions if they exist.
|
| 779 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 780 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 781 |
+
is not used.
|
| 782 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 783 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 784 |
+
incompletely downloaded files are deleted.
|
| 785 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 786 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 787 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 788 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 789 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 790 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 791 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 792 |
+
won't be downloaded from the Hub.
|
| 793 |
+
token (`str` or *bool*, *optional*):
|
| 794 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 795 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 796 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 797 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 798 |
+
allowed by Git.
|
| 799 |
+
custom_revision (`str`, *optional*, defaults to `"main"`):
|
| 800 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
|
| 801 |
+
`revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
|
| 802 |
+
custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
|
| 803 |
+
mirror (`str`, *optional*):
|
| 804 |
+
Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
|
| 805 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 806 |
+
information.
|
| 807 |
+
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
| 808 |
+
A map that specifies where each submodule should go. It doesn’t need to be defined for each
|
| 809 |
+
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
|
| 810 |
+
same device.
|
| 811 |
+
|
| 812 |
+
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
|
| 813 |
+
more information about each option see [designing a device
|
| 814 |
+
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
|
| 815 |
+
max_memory (`Dict`, *optional*):
|
| 816 |
+
A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
|
| 817 |
+
each GPU and the available CPU RAM if unset.
|
| 818 |
+
offload_folder (`str` or `os.PathLike`, *optional*):
|
| 819 |
+
The path to offload weights if device_map contains the value `"disk"`.
|
| 820 |
+
offload_state_dict (`bool`, *optional*):
|
| 821 |
+
If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
|
| 822 |
+
the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
|
| 823 |
+
when there is some disk offload.
|
| 824 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 825 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 826 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 827 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 828 |
+
argument to `True` will raise an error.
|
| 829 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 830 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 831 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 832 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 833 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 834 |
+
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
|
| 835 |
+
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
|
| 836 |
+
below for more information.
|
| 837 |
+
variant (`str`, *optional*):
|
| 838 |
+
Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
|
| 839 |
+
loading `from_flax`.
|
| 840 |
+
|
| 841 |
+
<Tip>
|
| 842 |
+
|
| 843 |
+
To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
|
| 844 |
+
`huggingface-cli login`.
|
| 845 |
+
|
| 846 |
+
</Tip>
|
| 847 |
+
|
| 848 |
+
Examples:
|
| 849 |
+
|
| 850 |
+
```py
|
| 851 |
+
>>> from diffusers import AutoPipelineForInpainting
|
| 852 |
+
|
| 853 |
+
>>> pipeline = AutoPipelineForInpainting.from_pretrained("runwayml/stable-diffusion-v1-5")
|
| 854 |
+
>>> image = pipeline(prompt, image=init_image, mask_image=mask_image).images[0]
|
| 855 |
+
```
|
| 856 |
+
"""
|
| 857 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 858 |
+
force_download = kwargs.pop("force_download", False)
|
| 859 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 860 |
+
proxies = kwargs.pop("proxies", None)
|
| 861 |
+
token = kwargs.pop("token", None)
|
| 862 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 863 |
+
revision = kwargs.pop("revision", None)
|
| 864 |
+
|
| 865 |
+
load_config_kwargs = {
|
| 866 |
+
"cache_dir": cache_dir,
|
| 867 |
+
"force_download": force_download,
|
| 868 |
+
"resume_download": resume_download,
|
| 869 |
+
"proxies": proxies,
|
| 870 |
+
"token": token,
|
| 871 |
+
"local_files_only": local_files_only,
|
| 872 |
+
"revision": revision,
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
|
| 876 |
+
orig_class_name = config["_class_name"]
|
| 877 |
+
|
| 878 |
+
if "controlnet" in kwargs:
|
| 879 |
+
orig_class_name = config["_class_name"].replace("Pipeline", "ControlNetPipeline")
|
| 880 |
+
|
| 881 |
+
inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, orig_class_name)
|
| 882 |
+
|
| 883 |
+
kwargs = {**load_config_kwargs, **kwargs}
|
| 884 |
+
return inpainting_cls.from_pretrained(pretrained_model_or_path, **kwargs)
|
| 885 |
+
|
| 886 |
+
@classmethod
|
| 887 |
+
def from_pipe(cls, pipeline, **kwargs):
|
| 888 |
+
r"""
|
| 889 |
+
Instantiates a inpainting Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
|
| 890 |
+
|
| 891 |
+
The from_pipe() method takes care of returning the correct pipeline class instance by finding the inpainting
|
| 892 |
+
pipeline linked to the pipeline class using pattern matching on pipeline class name.
|
| 893 |
+
|
| 894 |
+
All the modules the pipeline class contain will be used to initialize the new pipeline without reallocating
|
| 895 |
+
additional memory.
|
| 896 |
+
|
| 897 |
+
The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 898 |
+
|
| 899 |
+
Parameters:
|
| 900 |
+
pipeline (`DiffusionPipeline`):
|
| 901 |
+
an instantiated `DiffusionPipeline` object
|
| 902 |
+
|
| 903 |
+
Examples:
|
| 904 |
+
|
| 905 |
+
```py
|
| 906 |
+
>>> from diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting
|
| 907 |
+
|
| 908 |
+
>>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
|
| 909 |
+
... "DeepFloyd/IF-I-XL-v1.0", requires_safety_checker=False
|
| 910 |
+
... )
|
| 911 |
+
|
| 912 |
+
>>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
|
| 913 |
+
>>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image).images[0]
|
| 914 |
+
```
|
| 915 |
+
"""
|
| 916 |
+
original_config = dict(pipeline.config)
|
| 917 |
+
original_cls_name = pipeline.__class__.__name__
|
| 918 |
+
|
| 919 |
+
# derive the pipeline class to instantiate
|
| 920 |
+
inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, original_cls_name)
|
| 921 |
+
|
| 922 |
+
if "controlnet" in kwargs:
|
| 923 |
+
if kwargs["controlnet"] is not None:
|
| 924 |
+
inpainting_cls = _get_task_class(
|
| 925 |
+
AUTO_INPAINT_PIPELINES_MAPPING,
|
| 926 |
+
inpainting_cls.__name__.replace("ControlNet", "").replace(
|
| 927 |
+
"InpaintPipeline", "ControlNetInpaintPipeline"
|
| 928 |
+
),
|
| 929 |
+
)
|
| 930 |
+
else:
|
| 931 |
+
inpainting_cls = _get_task_class(
|
| 932 |
+
AUTO_INPAINT_PIPELINES_MAPPING,
|
| 933 |
+
inpainting_cls.__name__.replace("ControlNetInpaintPipeline", "InpaintPipeline"),
|
| 934 |
+
)
|
| 935 |
+
|
| 936 |
+
# define expected module and optional kwargs given the pipeline signature
|
| 937 |
+
expected_modules, optional_kwargs = inpainting_cls._get_signature_keys(inpainting_cls)
|
| 938 |
+
|
| 939 |
+
pretrained_model_name_or_path = original_config.pop("_name_or_path", None)
|
| 940 |
+
|
| 941 |
+
# allow users pass modules in `kwargs` to override the original pipeline's components
|
| 942 |
+
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
|
| 943 |
+
original_class_obj = {
|
| 944 |
+
k: pipeline.components[k]
|
| 945 |
+
for k, v in pipeline.components.items()
|
| 946 |
+
if k in expected_modules and k not in passed_class_obj
|
| 947 |
+
}
|
| 948 |
+
|
| 949 |
+
# allow users pass optional kwargs to override the original pipelines config attribute
|
| 950 |
+
passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
|
| 951 |
+
original_pipe_kwargs = {
|
| 952 |
+
k: original_config[k]
|
| 953 |
+
for k, v in original_config.items()
|
| 954 |
+
if k in optional_kwargs and k not in passed_pipe_kwargs
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
# config that were not expected by original pipeline is stored as private attribute
|
| 958 |
+
# we will pass them as optional arguments if they can be accepted by the pipeline
|
| 959 |
+
additional_pipe_kwargs = [
|
| 960 |
+
k[1:]
|
| 961 |
+
for k in original_config.keys()
|
| 962 |
+
if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
|
| 963 |
+
]
|
| 964 |
+
for k in additional_pipe_kwargs:
|
| 965 |
+
original_pipe_kwargs[k] = original_config.pop(f"_{k}")
|
| 966 |
+
|
| 967 |
+
inpainting_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}
|
| 968 |
+
|
| 969 |
+
# store unused config as private attribute
|
| 970 |
+
unused_original_config = {
|
| 971 |
+
f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
|
| 972 |
+
for k, v in original_config.items()
|
| 973 |
+
if k not in inpainting_kwargs
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(inpainting_kwargs.keys())
|
| 977 |
+
|
| 978 |
+
if len(missing_modules) > 0:
|
| 979 |
+
raise ValueError(
|
| 980 |
+
f"Pipeline {inpainting_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
model = inpainting_cls(**inpainting_kwargs)
|
| 984 |
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
|
| 985 |
+
model.register_to_config(**unused_original_config)
|
| 986 |
+
|
| 987 |
+
return model
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/__init__.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ...utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
get_objects_from_module,
|
| 8 |
+
is_librosa_available,
|
| 9 |
+
is_note_seq_available,
|
| 10 |
+
is_torch_available,
|
| 11 |
+
is_transformers_available,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_dummy_objects = {}
|
| 16 |
+
_import_structure = {}
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
if not is_torch_available():
|
| 20 |
+
raise OptionalDependencyNotAvailable()
|
| 21 |
+
except OptionalDependencyNotAvailable:
|
| 22 |
+
from ...utils import dummy_pt_objects
|
| 23 |
+
|
| 24 |
+
_dummy_objects.update(get_objects_from_module(dummy_pt_objects))
|
| 25 |
+
else:
|
| 26 |
+
_import_structure["latent_diffusion_uncond"] = ["LDMPipeline"]
|
| 27 |
+
_import_structure["pndm"] = ["PNDMPipeline"]
|
| 28 |
+
_import_structure["repaint"] = ["RePaintPipeline"]
|
| 29 |
+
_import_structure["score_sde_ve"] = ["ScoreSdeVePipeline"]
|
| 30 |
+
_import_structure["stochastic_karras_ve"] = ["KarrasVePipeline"]
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 34 |
+
raise OptionalDependencyNotAvailable()
|
| 35 |
+
except OptionalDependencyNotAvailable:
|
| 36 |
+
from ...utils import dummy_torch_and_transformers_objects
|
| 37 |
+
|
| 38 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 39 |
+
else:
|
| 40 |
+
_import_structure["alt_diffusion"] = [
|
| 41 |
+
"AltDiffusionImg2ImgPipeline",
|
| 42 |
+
"AltDiffusionPipeline",
|
| 43 |
+
"AltDiffusionPipelineOutput",
|
| 44 |
+
]
|
| 45 |
+
_import_structure["versatile_diffusion"] = [
|
| 46 |
+
"VersatileDiffusionDualGuidedPipeline",
|
| 47 |
+
"VersatileDiffusionImageVariationPipeline",
|
| 48 |
+
"VersatileDiffusionPipeline",
|
| 49 |
+
"VersatileDiffusionTextToImagePipeline",
|
| 50 |
+
]
|
| 51 |
+
_import_structure["vq_diffusion"] = ["VQDiffusionPipeline"]
|
| 52 |
+
_import_structure["stable_diffusion_variants"] = [
|
| 53 |
+
"CycleDiffusionPipeline",
|
| 54 |
+
"StableDiffusionInpaintPipelineLegacy",
|
| 55 |
+
"StableDiffusionPix2PixZeroPipeline",
|
| 56 |
+
"StableDiffusionParadigmsPipeline",
|
| 57 |
+
"StableDiffusionModelEditingPipeline",
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 62 |
+
raise OptionalDependencyNotAvailable()
|
| 63 |
+
except OptionalDependencyNotAvailable:
|
| 64 |
+
from ...utils import dummy_torch_and_librosa_objects # noqa F403
|
| 65 |
+
|
| 66 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_librosa_objects))
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
_import_structure["audio_diffusion"] = ["AudioDiffusionPipeline", "Mel"]
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 73 |
+
raise OptionalDependencyNotAvailable()
|
| 74 |
+
except OptionalDependencyNotAvailable:
|
| 75 |
+
from ...utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
|
| 76 |
+
|
| 77 |
+
_dummy_objects.update(get_objects_from_module(dummy_transformers_and_torch_and_note_seq_objects))
|
| 78 |
+
|
| 79 |
+
else:
|
| 80 |
+
_import_structure["spectrogram_diffusion"] = ["MidiProcessor", "SpectrogramDiffusionPipeline"]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 84 |
+
try:
|
| 85 |
+
if not is_torch_available():
|
| 86 |
+
raise OptionalDependencyNotAvailable()
|
| 87 |
+
except OptionalDependencyNotAvailable:
|
| 88 |
+
from ...utils.dummy_pt_objects import *
|
| 89 |
+
|
| 90 |
+
else:
|
| 91 |
+
from .latent_diffusion_uncond import LDMPipeline
|
| 92 |
+
from .pndm import PNDMPipeline
|
| 93 |
+
from .repaint import RePaintPipeline
|
| 94 |
+
from .score_sde_ve import ScoreSdeVePipeline
|
| 95 |
+
from .stochastic_karras_ve import KarrasVePipeline
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 99 |
+
raise OptionalDependencyNotAvailable()
|
| 100 |
+
except OptionalDependencyNotAvailable:
|
| 101 |
+
from ...utils.dummy_torch_and_transformers_objects import *
|
| 102 |
+
|
| 103 |
+
else:
|
| 104 |
+
from .alt_diffusion import AltDiffusionImg2ImgPipeline, AltDiffusionPipeline, AltDiffusionPipelineOutput
|
| 105 |
+
from .audio_diffusion import AudioDiffusionPipeline, Mel
|
| 106 |
+
from .spectrogram_diffusion import SpectrogramDiffusionPipeline
|
| 107 |
+
from .stable_diffusion_variants import (
|
| 108 |
+
CycleDiffusionPipeline,
|
| 109 |
+
StableDiffusionInpaintPipelineLegacy,
|
| 110 |
+
StableDiffusionModelEditingPipeline,
|
| 111 |
+
StableDiffusionParadigmsPipeline,
|
| 112 |
+
StableDiffusionPix2PixZeroPipeline,
|
| 113 |
+
)
|
| 114 |
+
from .stochastic_karras_ve import KarrasVePipeline
|
| 115 |
+
from .versatile_diffusion import (
|
| 116 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 117 |
+
VersatileDiffusionImageVariationPipeline,
|
| 118 |
+
VersatileDiffusionPipeline,
|
| 119 |
+
VersatileDiffusionTextToImagePipeline,
|
| 120 |
+
)
|
| 121 |
+
from .vq_diffusion import VQDiffusionPipeline
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 125 |
+
raise OptionalDependencyNotAvailable()
|
| 126 |
+
except OptionalDependencyNotAvailable:
|
| 127 |
+
from ...utils.dummy_torch_and_librosa_objects import *
|
| 128 |
+
else:
|
| 129 |
+
from .audio_diffusion import AudioDiffusionPipeline, Mel
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 133 |
+
raise OptionalDependencyNotAvailable()
|
| 134 |
+
except OptionalDependencyNotAvailable:
|
| 135 |
+
from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
|
| 136 |
+
else:
|
| 137 |
+
from .spectrogram_diffusion import (
|
| 138 |
+
MidiProcessor,
|
| 139 |
+
SpectrogramDiffusionPipeline,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
else:
|
| 144 |
+
import sys
|
| 145 |
+
|
| 146 |
+
sys.modules[__name__] = _LazyModule(
|
| 147 |
+
__name__,
|
| 148 |
+
globals()["__file__"],
|
| 149 |
+
_import_structure,
|
| 150 |
+
module_spec=__spec__,
|
| 151 |
+
)
|
| 152 |
+
for name, value in _dummy_objects.items():
|
| 153 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ....utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
get_objects_from_module,
|
| 8 |
+
is_torch_available,
|
| 9 |
+
is_transformers_available,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_dummy_objects = {}
|
| 14 |
+
_import_structure = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 18 |
+
raise OptionalDependencyNotAvailable()
|
| 19 |
+
except OptionalDependencyNotAvailable:
|
| 20 |
+
from ....utils import dummy_torch_and_transformers_objects
|
| 21 |
+
|
| 22 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 23 |
+
else:
|
| 24 |
+
_import_structure["modeling_roberta_series"] = ["RobertaSeriesModelWithTransformation"]
|
| 25 |
+
_import_structure["pipeline_alt_diffusion"] = ["AltDiffusionPipeline"]
|
| 26 |
+
_import_structure["pipeline_alt_diffusion_img2img"] = ["AltDiffusionImg2ImgPipeline"]
|
| 27 |
+
|
| 28 |
+
_import_structure["pipeline_output"] = ["AltDiffusionPipelineOutput"]
|
| 29 |
+
|
| 30 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 31 |
+
try:
|
| 32 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 33 |
+
raise OptionalDependencyNotAvailable()
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
from ....utils.dummy_torch_and_transformers_objects import *
|
| 36 |
+
|
| 37 |
+
else:
|
| 38 |
+
from .modeling_roberta_series import RobertaSeriesModelWithTransformation
|
| 39 |
+
from .pipeline_alt_diffusion import AltDiffusionPipeline
|
| 40 |
+
from .pipeline_alt_diffusion_img2img import AltDiffusionImg2ImgPipeline
|
| 41 |
+
from .pipeline_output import AltDiffusionPipelineOutput
|
| 42 |
+
|
| 43 |
+
else:
|
| 44 |
+
import sys
|
| 45 |
+
|
| 46 |
+
sys.modules[__name__] = _LazyModule(
|
| 47 |
+
__name__,
|
| 48 |
+
globals()["__file__"],
|
| 49 |
+
_import_structure,
|
| 50 |
+
module_spec=__spec__,
|
| 51 |
+
)
|
| 52 |
+
for name, value in _dummy_objects.items():
|
| 53 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_alt_diffusion.cpython-310.pyc
ADDED
|
Binary file (32.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_alt_diffusion_img2img.cpython-310.pyc
ADDED
|
Binary file (35.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/__pycache__/pipeline_output.cpython-310.pyc
ADDED
|
Binary file (1.25 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
|
| 7 |
+
from transformers.utils import ModelOutput
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class TransformationModelOutput(ModelOutput):
|
| 12 |
+
"""
|
| 13 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 17 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 18 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 19 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 20 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 21 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 22 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 23 |
+
|
| 24 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 25 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 26 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 27 |
+
sequence_length)`.
|
| 28 |
+
|
| 29 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 30 |
+
heads.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
projection_state: Optional[torch.FloatTensor] = None
|
| 34 |
+
last_hidden_state: torch.FloatTensor = None
|
| 35 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 36 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class RobertaSeriesConfig(XLMRobertaConfig):
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
pad_token_id=1,
|
| 43 |
+
bos_token_id=0,
|
| 44 |
+
eos_token_id=2,
|
| 45 |
+
project_dim=512,
|
| 46 |
+
pooler_fn="cls",
|
| 47 |
+
learn_encoder=False,
|
| 48 |
+
use_attention_mask=True,
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 52 |
+
self.project_dim = project_dim
|
| 53 |
+
self.pooler_fn = pooler_fn
|
| 54 |
+
self.learn_encoder = learn_encoder
|
| 55 |
+
self.use_attention_mask = use_attention_mask
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class RobertaSeriesModelWithTransformation(RobertaPreTrainedModel):
|
| 59 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"logit_scale"]
|
| 60 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
| 61 |
+
base_model_prefix = "roberta"
|
| 62 |
+
config_class = RobertaSeriesConfig
|
| 63 |
+
|
| 64 |
+
def __init__(self, config):
|
| 65 |
+
super().__init__(config)
|
| 66 |
+
self.roberta = XLMRobertaModel(config)
|
| 67 |
+
self.transformation = nn.Linear(config.hidden_size, config.project_dim)
|
| 68 |
+
self.has_pre_transformation = getattr(config, "has_pre_transformation", False)
|
| 69 |
+
if self.has_pre_transformation:
|
| 70 |
+
self.transformation_pre = nn.Linear(config.hidden_size, config.project_dim)
|
| 71 |
+
self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 72 |
+
self.post_init()
|
| 73 |
+
|
| 74 |
+
def forward(
|
| 75 |
+
self,
|
| 76 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 77 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 78 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 79 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 80 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 81 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 82 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 83 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 84 |
+
output_attentions: Optional[bool] = None,
|
| 85 |
+
return_dict: Optional[bool] = None,
|
| 86 |
+
output_hidden_states: Optional[bool] = None,
|
| 87 |
+
):
|
| 88 |
+
r""" """
|
| 89 |
+
|
| 90 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 91 |
+
|
| 92 |
+
outputs = self.base_model(
|
| 93 |
+
input_ids=input_ids,
|
| 94 |
+
attention_mask=attention_mask,
|
| 95 |
+
token_type_ids=token_type_ids,
|
| 96 |
+
position_ids=position_ids,
|
| 97 |
+
head_mask=head_mask,
|
| 98 |
+
inputs_embeds=inputs_embeds,
|
| 99 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 100 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 101 |
+
output_attentions=output_attentions,
|
| 102 |
+
output_hidden_states=True if self.has_pre_transformation else output_hidden_states,
|
| 103 |
+
return_dict=return_dict,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
if self.has_pre_transformation:
|
| 107 |
+
sequence_output2 = outputs["hidden_states"][-2]
|
| 108 |
+
sequence_output2 = self.pre_LN(sequence_output2)
|
| 109 |
+
projection_state2 = self.transformation_pre(sequence_output2)
|
| 110 |
+
|
| 111 |
+
return TransformationModelOutput(
|
| 112 |
+
projection_state=projection_state2,
|
| 113 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 114 |
+
hidden_states=outputs.hidden_states,
|
| 115 |
+
attentions=outputs.attentions,
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
projection_state = self.transformation(outputs.last_hidden_state)
|
| 119 |
+
return TransformationModelOutput(
|
| 120 |
+
projection_state=projection_state,
|
| 121 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 122 |
+
hidden_states=outputs.hidden_states,
|
| 123 |
+
attentions=outputs.attentions,
|
| 124 |
+
)
|
evalkit_tf437/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from packaging import version
|
| 20 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, XLMRobertaTokenizer
|
| 21 |
+
|
| 22 |
+
from ....configuration_utils import FrozenDict
|
| 23 |
+
from ....image_processor import PipelineImageInput, VaeImageProcessor
|
| 24 |
+
from ....loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 25 |
+
from ....models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
| 26 |
+
from ....models.lora import adjust_lora_scale_text_encoder
|
| 27 |
+
from ....schedulers import KarrasDiffusionSchedulers
|
| 28 |
+
from ....utils import (
|
| 29 |
+
USE_PEFT_BACKEND,
|
| 30 |
+
deprecate,
|
| 31 |
+
logging,
|
| 32 |
+
replace_example_docstring,
|
| 33 |
+
scale_lora_layers,
|
| 34 |
+
unscale_lora_layers,
|
| 35 |
+
)
|
| 36 |
+
from ....utils.torch_utils import randn_tensor
|
| 37 |
+
from ...pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 38 |
+
from ...stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 39 |
+
from .modeling_roberta_series import RobertaSeriesModelWithTransformation
|
| 40 |
+
from .pipeline_output import AltDiffusionPipelineOutput
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 44 |
+
|
| 45 |
+
EXAMPLE_DOC_STRING = """
|
| 46 |
+
Examples:
|
| 47 |
+
```py
|
| 48 |
+
>>> import torch
|
| 49 |
+
>>> from diffusers import AltDiffusionPipeline
|
| 50 |
+
|
| 51 |
+
>>> pipe = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion-m9", torch_dtype=torch.float16)
|
| 52 |
+
>>> pipe = pipe.to("cuda")
|
| 53 |
+
|
| 54 |
+
>>> # "dark elf princess, highly detailed, d & d, fantasy, highly detailed, digital painting, trending on artstation, concept art, sharp focus, illustration, art by artgerm and greg rutkowski and fuji choko and viktoria gavrilenko and hoang lap"
|
| 55 |
+
>>> prompt = "黑暗精灵公主,非常详细,幻想,非常详细,数字绘画,概念艺术,敏锐的焦点,插图"
|
| 56 |
+
>>> image = pipe(prompt).images[0]
|
| 57 |
+
```
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
| 62 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 63 |
+
"""
|
| 64 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 65 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 66 |
+
"""
|
| 67 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 68 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 69 |
+
# rescale the results from guidance (fixes overexposure)
|
| 70 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 71 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 72 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 73 |
+
return noise_cfg
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 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 |
+
**kwargs,
|
| 83 |
+
):
|
| 84 |
+
"""
|
| 85 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 86 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
scheduler (`SchedulerMixin`):
|
| 90 |
+
The scheduler to get timesteps from.
|
| 91 |
+
num_inference_steps (`int`):
|
| 92 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
| 93 |
+
`timesteps` must be `None`.
|
| 94 |
+
device (`str` or `torch.device`, *optional*):
|
| 95 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 96 |
+
timesteps (`List[int]`, *optional*):
|
| 97 |
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
| 98 |
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
| 99 |
+
must be `None`.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 103 |
+
second element is the number of inference steps.
|
| 104 |
+
"""
|
| 105 |
+
if timesteps is not None:
|
| 106 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 107 |
+
if not accepts_timesteps:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 110 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 111 |
+
)
|
| 112 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 113 |
+
timesteps = scheduler.timesteps
|
| 114 |
+
num_inference_steps = len(timesteps)
|
| 115 |
+
else:
|
| 116 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 117 |
+
timesteps = scheduler.timesteps
|
| 118 |
+
return timesteps, num_inference_steps
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class AltDiffusionPipeline(
|
| 122 |
+
DiffusionPipeline,
|
| 123 |
+
StableDiffusionMixin,
|
| 124 |
+
TextualInversionLoaderMixin,
|
| 125 |
+
LoraLoaderMixin,
|
| 126 |
+
IPAdapterMixin,
|
| 127 |
+
FromSingleFileMixin,
|
| 128 |
+
):
|
| 129 |
+
r"""
|
| 130 |
+
Pipeline for text-to-image generation using Alt Diffusion.
|
| 131 |
+
|
| 132 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 133 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 134 |
+
|
| 135 |
+
The pipeline also inherits the following loading methods:
|
| 136 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 137 |
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 138 |
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 139 |
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
| 140 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
vae ([`AutoencoderKL`]):
|
| 144 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 145 |
+
text_encoder ([`~transformers.RobertaSeriesModelWithTransformation`]):
|
| 146 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 147 |
+
tokenizer ([`~transformers.XLMRobertaTokenizer`]):
|
| 148 |
+
A `XLMRobertaTokenizer` to tokenize text.
|
| 149 |
+
unet ([`UNet2DConditionModel`]):
|
| 150 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 151 |
+
scheduler ([`SchedulerMixin`]):
|
| 152 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 153 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 154 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 155 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 156 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 157 |
+
about a model's potential harms.
|
| 158 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 159 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
| 163 |
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
| 164 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 165 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
vae: AutoencoderKL,
|
| 170 |
+
text_encoder: RobertaSeriesModelWithTransformation,
|
| 171 |
+
tokenizer: XLMRobertaTokenizer,
|
| 172 |
+
unet: UNet2DConditionModel,
|
| 173 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 174 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 175 |
+
feature_extractor: CLIPImageProcessor,
|
| 176 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 177 |
+
requires_safety_checker: bool = True,
|
| 178 |
+
):
|
| 179 |
+
super().__init__()
|
| 180 |
+
|
| 181 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 182 |
+
deprecation_message = (
|
| 183 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 184 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 185 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 186 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 187 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 188 |
+
" file"
|
| 189 |
+
)
|
| 190 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 191 |
+
new_config = dict(scheduler.config)
|
| 192 |
+
new_config["steps_offset"] = 1
|
| 193 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 194 |
+
|
| 195 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 196 |
+
deprecation_message = (
|
| 197 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 198 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 199 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 200 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 201 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 202 |
+
)
|
| 203 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 204 |
+
new_config = dict(scheduler.config)
|
| 205 |
+
new_config["clip_sample"] = False
|
| 206 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 207 |
+
|
| 208 |
+
if safety_checker is None and requires_safety_checker:
|
| 209 |
+
logger.warning(
|
| 210 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 211 |
+
" that you abide to the conditions of the Alt Diffusion license and do not expose unfiltered"
|
| 212 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 213 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 214 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 215 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
if safety_checker is not None and feature_extractor is None:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 221 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 225 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 226 |
+
) < version.parse("0.9.0.dev0")
|
| 227 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 228 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 229 |
+
deprecation_message = (
|
| 230 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 231 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 232 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 233 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 234 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 235 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 236 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 237 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 238 |
+
" the `unet/config.json` file"
|
| 239 |
+
)
|
| 240 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 241 |
+
new_config = dict(unet.config)
|
| 242 |
+
new_config["sample_size"] = 64
|
| 243 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 244 |
+
|
| 245 |
+
self.register_modules(
|
| 246 |
+
vae=vae,
|
| 247 |
+
text_encoder=text_encoder,
|
| 248 |
+
tokenizer=tokenizer,
|
| 249 |
+
unet=unet,
|
| 250 |
+
scheduler=scheduler,
|
| 251 |
+
safety_checker=safety_checker,
|
| 252 |
+
feature_extractor=feature_extractor,
|
| 253 |
+
image_encoder=image_encoder,
|
| 254 |
+
)
|
| 255 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 256 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 257 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 258 |
+
|
| 259 |
+
def _encode_prompt(
|
| 260 |
+
self,
|
| 261 |
+
prompt,
|
| 262 |
+
device,
|
| 263 |
+
num_images_per_prompt,
|
| 264 |
+
do_classifier_free_guidance,
|
| 265 |
+
negative_prompt=None,
|
| 266 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 267 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 268 |
+
lora_scale: Optional[float] = None,
|
| 269 |
+
**kwargs,
|
| 270 |
+
):
|
| 271 |
+
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."
|
| 272 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 273 |
+
|
| 274 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 275 |
+
prompt=prompt,
|
| 276 |
+
device=device,
|
| 277 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 278 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 279 |
+
negative_prompt=negative_prompt,
|
| 280 |
+
prompt_embeds=prompt_embeds,
|
| 281 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 282 |
+
lora_scale=lora_scale,
|
| 283 |
+
**kwargs,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# concatenate for backwards comp
|
| 287 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 288 |
+
|
| 289 |
+
return prompt_embeds
|
| 290 |
+
|
| 291 |
+
def encode_prompt(
|
| 292 |
+
self,
|
| 293 |
+
prompt,
|
| 294 |
+
device,
|
| 295 |
+
num_images_per_prompt,
|
| 296 |
+
do_classifier_free_guidance,
|
| 297 |
+
negative_prompt=None,
|
| 298 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 299 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 300 |
+
lora_scale: Optional[float] = None,
|
| 301 |
+
clip_skip: Optional[int] = None,
|
| 302 |
+
):
|
| 303 |
+
r"""
|
| 304 |
+
Encodes the prompt into text encoder hidden states.
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 308 |
+
prompt to be encoded
|
| 309 |
+
device: (`torch.device`):
|
| 310 |
+
torch device
|
| 311 |
+
num_images_per_prompt (`int`):
|
| 312 |
+
number of images that should be generated per prompt
|
| 313 |
+
do_classifier_free_guidance (`bool`):
|
| 314 |
+
whether to use classifier free guidance or not
|
| 315 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 316 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 317 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 318 |
+
less than `1`).
|
| 319 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 320 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 321 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 322 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 323 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 324 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 325 |
+
argument.
|
| 326 |
+
lora_scale (`float`, *optional*):
|
| 327 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 328 |
+
clip_skip (`int`, *optional*):
|
| 329 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 330 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 331 |
+
"""
|
| 332 |
+
# set lora scale so that monkey patched LoRA
|
| 333 |
+
# function of text encoder can correctly access it
|
| 334 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 335 |
+
self._lora_scale = lora_scale
|
| 336 |
+
|
| 337 |
+
# dynamically adjust the LoRA scale
|
| 338 |
+
if not USE_PEFT_BACKEND:
|
| 339 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 340 |
+
else:
|
| 341 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 342 |
+
|
| 343 |
+
if prompt is not None and isinstance(prompt, str):
|
| 344 |
+
batch_size = 1
|
| 345 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 346 |
+
batch_size = len(prompt)
|
| 347 |
+
else:
|
| 348 |
+
batch_size = prompt_embeds.shape[0]
|
| 349 |
+
|
| 350 |
+
if prompt_embeds is None:
|
| 351 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 352 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 353 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 354 |
+
|
| 355 |
+
text_inputs = self.tokenizer(
|
| 356 |
+
prompt,
|
| 357 |
+
padding="max_length",
|
| 358 |
+
max_length=self.tokenizer.model_max_length,
|
| 359 |
+
truncation=True,
|
| 360 |
+
return_tensors="pt",
|
| 361 |
+
)
|
| 362 |
+
text_input_ids = text_inputs.input_ids
|
| 363 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 364 |
+
|
| 365 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 366 |
+
text_input_ids, untruncated_ids
|
| 367 |
+
):
|
| 368 |
+
removed_text = self.tokenizer.batch_decode(
|
| 369 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 370 |
+
)
|
| 371 |
+
logger.warning(
|
| 372 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 373 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 377 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 378 |
+
else:
|
| 379 |
+
attention_mask = None
|
| 380 |
+
|
| 381 |
+
if clip_skip is None:
|
| 382 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 383 |
+
prompt_embeds = prompt_embeds[0]
|
| 384 |
+
else:
|
| 385 |
+
prompt_embeds = self.text_encoder(
|
| 386 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 387 |
+
)
|
| 388 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 389 |
+
# all the hidden states from the encoder layers. Then index into
|
| 390 |
+
# the tuple to access the hidden states from the desired layer.
|
| 391 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 392 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 393 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 394 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 395 |
+
# layer.
|
| 396 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 397 |
+
|
| 398 |
+
if self.text_encoder is not None:
|
| 399 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 400 |
+
elif self.unet is not None:
|
| 401 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 402 |
+
else:
|
| 403 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 404 |
+
|
| 405 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 406 |
+
|
| 407 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 408 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 409 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 410 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 411 |
+
|
| 412 |
+
# get unconditional embeddings for classifier free guidance
|
| 413 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 414 |
+
uncond_tokens: List[str]
|
| 415 |
+
if negative_prompt is None:
|
| 416 |
+
uncond_tokens = [""] * batch_size
|
| 417 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 418 |
+
raise TypeError(
|
| 419 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 420 |
+
f" {type(prompt)}."
|
| 421 |
+
)
|
| 422 |
+
elif isinstance(negative_prompt, str):
|
| 423 |
+
uncond_tokens = [negative_prompt]
|
| 424 |
+
elif batch_size != len(negative_prompt):
|
| 425 |
+
raise ValueError(
|
| 426 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 427 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 428 |
+
" the batch size of `prompt`."
|
| 429 |
+
)
|
| 430 |
+
else:
|
| 431 |
+
uncond_tokens = negative_prompt
|
| 432 |
+
|
| 433 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 434 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 435 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 436 |
+
|
| 437 |
+
max_length = prompt_embeds.shape[1]
|
| 438 |
+
uncond_input = self.tokenizer(
|
| 439 |
+
uncond_tokens,
|
| 440 |
+
padding="max_length",
|
| 441 |
+
max_length=max_length,
|
| 442 |
+
truncation=True,
|
| 443 |
+
return_tensors="pt",
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 447 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 448 |
+
else:
|
| 449 |
+
attention_mask = None
|
| 450 |
+
|
| 451 |
+
negative_prompt_embeds = self.text_encoder(
|
| 452 |
+
uncond_input.input_ids.to(device),
|
| 453 |
+
attention_mask=attention_mask,
|
| 454 |
+
)
|
| 455 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 456 |
+
|
| 457 |
+
if do_classifier_free_guidance:
|
| 458 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 459 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 460 |
+
|
| 461 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 462 |
+
|
| 463 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 464 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 465 |
+
|
| 466 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 467 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 468 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 469 |
+
|
| 470 |
+
return prompt_embeds, negative_prompt_embeds
|
| 471 |
+
|
| 472 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
| 473 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 474 |
+
|
| 475 |
+
if not isinstance(image, torch.Tensor):
|
| 476 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 477 |
+
|
| 478 |
+
image = image.to(device=device, dtype=dtype)
|
| 479 |
+
if output_hidden_states:
|
| 480 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
| 481 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
| 482 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
| 483 |
+
torch.zeros_like(image), output_hidden_states=True
|
| 484 |
+
).hidden_states[-2]
|
| 485 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
| 486 |
+
num_images_per_prompt, dim=0
|
| 487 |
+
)
|
| 488 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
| 489 |
+
else:
|
| 490 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 491 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 492 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
| 493 |
+
|
| 494 |
+
return image_embeds, uncond_image_embeds
|
| 495 |
+
|
| 496 |
+
def run_safety_checker(self, image, device, dtype):
|
| 497 |
+
if self.safety_checker is None:
|
| 498 |
+
has_nsfw_concept = None
|
| 499 |
+
else:
|
| 500 |
+
if torch.is_tensor(image):
|
| 501 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 502 |
+
else:
|
| 503 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 504 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 505 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 506 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 507 |
+
)
|
| 508 |
+
return image, has_nsfw_concept
|
| 509 |
+
|
| 510 |
+
def decode_latents(self, latents):
|
| 511 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 512 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 513 |
+
|
| 514 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 515 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 516 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 517 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 518 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 519 |
+
return image
|
| 520 |
+
|
| 521 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 522 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 523 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 524 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 525 |
+
# and should be between [0, 1]
|
| 526 |
+
|
| 527 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 528 |
+
extra_step_kwargs = {}
|
| 529 |
+
if accepts_eta:
|
| 530 |
+
extra_step_kwargs["eta"] = eta
|
| 531 |
+
|
| 532 |
+
# check if the scheduler accepts generator
|
| 533 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 534 |
+
if accepts_generator:
|
| 535 |
+
extra_step_kwargs["generator"] = generator
|
| 536 |
+
return extra_step_kwargs
|
| 537 |
+
|
| 538 |
+
def check_inputs(
|
| 539 |
+
self,
|
| 540 |
+
prompt,
|
| 541 |
+
height,
|
| 542 |
+
width,
|
| 543 |
+
callback_steps,
|
| 544 |
+
negative_prompt=None,
|
| 545 |
+
prompt_embeds=None,
|
| 546 |
+
negative_prompt_embeds=None,
|
| 547 |
+
callback_on_step_end_tensor_inputs=None,
|
| 548 |
+
):
|
| 549 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 550 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 551 |
+
|
| 552 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 553 |
+
raise ValueError(
|
| 554 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 555 |
+
f" {type(callback_steps)}."
|
| 556 |
+
)
|
| 557 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 558 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 559 |
+
):
|
| 560 |
+
raise ValueError(
|
| 561 |
+
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]}"
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
if prompt is not None and prompt_embeds is not None:
|
| 565 |
+
raise ValueError(
|
| 566 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 567 |
+
" only forward one of the two."
|
| 568 |
+
)
|
| 569 |
+
elif prompt is None and prompt_embeds is None:
|
| 570 |
+
raise ValueError(
|
| 571 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 572 |
+
)
|
| 573 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 574 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 575 |
+
|
| 576 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 577 |
+
raise ValueError(
|
| 578 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 579 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 583 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 584 |
+
raise ValueError(
|
| 585 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 586 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 587 |
+
f" {negative_prompt_embeds.shape}."
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 591 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 592 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 593 |
+
raise ValueError(
|
| 594 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 595 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
if latents is None:
|
| 599 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 600 |
+
else:
|
| 601 |
+
latents = latents.to(device)
|
| 602 |
+
|
| 603 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 604 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 605 |
+
return latents
|
| 606 |
+
|
| 607 |
+
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
| 608 |
+
"""
|
| 609 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
timesteps (`torch.Tensor`):
|
| 613 |
+
generate embedding vectors at these timesteps
|
| 614 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
| 615 |
+
dimension of the embeddings to generate
|
| 616 |
+
dtype:
|
| 617 |
+
data type of the generated embeddings
|
| 618 |
+
|
| 619 |
+
Returns:
|
| 620 |
+
`torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
|
| 621 |
+
"""
|
| 622 |
+
assert len(w.shape) == 1
|
| 623 |
+
w = w * 1000.0
|
| 624 |
+
|
| 625 |
+
half_dim = embedding_dim // 2
|
| 626 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
| 627 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
| 628 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
| 629 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 630 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 631 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
| 632 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
| 633 |
+
return emb
|
| 634 |
+
|
| 635 |
+
@property
|
| 636 |
+
def guidance_scale(self):
|
| 637 |
+
return self._guidance_scale
|
| 638 |
+
|
| 639 |
+
@property
|
| 640 |
+
def guidance_rescale(self):
|
| 641 |
+
return self._guidance_rescale
|
| 642 |
+
|
| 643 |
+
@property
|
| 644 |
+
def clip_skip(self):
|
| 645 |
+
return self._clip_skip
|
| 646 |
+
|
| 647 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 648 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 649 |
+
# corresponds to doing no classifier free guidance.
|
| 650 |
+
@property
|
| 651 |
+
def do_classifier_free_guidance(self):
|
| 652 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
| 653 |
+
|
| 654 |
+
@property
|
| 655 |
+
def cross_attention_kwargs(self):
|
| 656 |
+
return self._cross_attention_kwargs
|
| 657 |
+
|
| 658 |
+
@property
|
| 659 |
+
def num_timesteps(self):
|
| 660 |
+
return self._num_timesteps
|
| 661 |
+
|
| 662 |
+
@torch.no_grad()
|
| 663 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 664 |
+
def __call__(
|
| 665 |
+
self,
|
| 666 |
+
prompt: Union[str, List[str]] = None,
|
| 667 |
+
height: Optional[int] = None,
|
| 668 |
+
width: Optional[int] = None,
|
| 669 |
+
num_inference_steps: int = 50,
|
| 670 |
+
timesteps: List[int] = None,
|
| 671 |
+
guidance_scale: float = 7.5,
|
| 672 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 673 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 674 |
+
eta: float = 0.0,
|
| 675 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 676 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 677 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 678 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 679 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 680 |
+
output_type: Optional[str] = "pil",
|
| 681 |
+
return_dict: bool = True,
|
| 682 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 683 |
+
guidance_rescale: float = 0.0,
|
| 684 |
+
clip_skip: Optional[int] = None,
|
| 685 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 686 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 687 |
+
**kwargs,
|
| 688 |
+
):
|
| 689 |
+
r"""
|
| 690 |
+
The call function to the pipeline for generation.
|
| 691 |
+
|
| 692 |
+
Args:
|
| 693 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 694 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 695 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 696 |
+
The height in pixels of the generated image.
|
| 697 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 698 |
+
The width in pixels of the generated image.
|
| 699 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 700 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 701 |
+
expense of slower inference.
|
| 702 |
+
timesteps (`List[int]`, *optional*):
|
| 703 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
| 704 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
| 705 |
+
passed will be used. Must be in descending order.
|
| 706 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 707 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 708 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 709 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 710 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 711 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 712 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 713 |
+
The number of images to generate per prompt.
|
| 714 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 715 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 716 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 717 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 718 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 719 |
+
generation deterministic.
|
| 720 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 721 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 722 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 723 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 724 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 725 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 726 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 727 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 728 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 729 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 730 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
| 731 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 732 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 733 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 734 |
+
Whether or not to return a [`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] instead of a
|
| 735 |
+
plain tuple.
|
| 736 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 737 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 738 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 739 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
| 740 |
+
Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
|
| 741 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
|
| 742 |
+
using zero terminal SNR.
|
| 743 |
+
clip_skip (`int`, *optional*):
|
| 744 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 745 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 746 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 747 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 748 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 749 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 750 |
+
`callback_on_step_end_tensor_inputs`.
|
| 751 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 752 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 753 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 754 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 755 |
+
|
| 756 |
+
Examples:
|
| 757 |
+
|
| 758 |
+
Returns:
|
| 759 |
+
[`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] or `tuple`:
|
| 760 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] is returned,
|
| 761 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 762 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 763 |
+
"not-safe-for-work" (nsfw) content.
|
| 764 |
+
"""
|
| 765 |
+
|
| 766 |
+
callback = kwargs.pop("callback", None)
|
| 767 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 768 |
+
|
| 769 |
+
if callback is not None:
|
| 770 |
+
deprecate(
|
| 771 |
+
"callback",
|
| 772 |
+
"1.0.0",
|
| 773 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 774 |
+
)
|
| 775 |
+
if callback_steps is not None:
|
| 776 |
+
deprecate(
|
| 777 |
+
"callback_steps",
|
| 778 |
+
"1.0.0",
|
| 779 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
# 0. Default height and width to unet
|
| 783 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 784 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 785 |
+
# to deal with lora scaling and other possible forward hooks
|
| 786 |
+
|
| 787 |
+
# 1. Check inputs. Raise error if not correct
|
| 788 |
+
self.check_inputs(
|
| 789 |
+
prompt,
|
| 790 |
+
height,
|
| 791 |
+
width,
|
| 792 |
+
callback_steps,
|
| 793 |
+
negative_prompt,
|
| 794 |
+
prompt_embeds,
|
| 795 |
+
negative_prompt_embeds,
|
| 796 |
+
callback_on_step_end_tensor_inputs,
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
self._guidance_scale = guidance_scale
|
| 800 |
+
self._guidance_rescale = guidance_rescale
|
| 801 |
+
self._clip_skip = clip_skip
|
| 802 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 803 |
+
|
| 804 |
+
# 2. Define call parameters
|
| 805 |
+
if prompt is not None and isinstance(prompt, str):
|
| 806 |
+
batch_size = 1
|
| 807 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 808 |
+
batch_size = len(prompt)
|
| 809 |
+
else:
|
| 810 |
+
batch_size = prompt_embeds.shape[0]
|
| 811 |
+
|
| 812 |
+
device = self._execution_device
|
| 813 |
+
|
| 814 |
+
# 3. Encode input prompt
|
| 815 |
+
lora_scale = (
|
| 816 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 820 |
+
prompt,
|
| 821 |
+
device,
|
| 822 |
+
num_images_per_prompt,
|
| 823 |
+
self.do_classifier_free_guidance,
|
| 824 |
+
negative_prompt,
|
| 825 |
+
prompt_embeds=prompt_embeds,
|
| 826 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 827 |
+
lora_scale=lora_scale,
|
| 828 |
+
clip_skip=self.clip_skip,
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 832 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 833 |
+
# to avoid doing two forward passes
|
| 834 |
+
if self.do_classifier_free_guidance:
|
| 835 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 836 |
+
|
| 837 |
+
if ip_adapter_image is not None:
|
| 838 |
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
| 839 |
+
image_embeds, negative_image_embeds = self.encode_image(
|
| 840 |
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
| 841 |
+
)
|
| 842 |
+
if self.do_classifier_free_guidance:
|
| 843 |
+
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
| 844 |
+
|
| 845 |
+
# 4. Prepare timesteps
|
| 846 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
| 847 |
+
|
| 848 |
+
# 5. Prepare latent variables
|
| 849 |
+
num_channels_latents = self.unet.config.in_channels
|
| 850 |
+
latents = self.prepare_latents(
|
| 851 |
+
batch_size * num_images_per_prompt,
|
| 852 |
+
num_channels_latents,
|
| 853 |
+
height,
|
| 854 |
+
width,
|
| 855 |
+
prompt_embeds.dtype,
|
| 856 |
+
device,
|
| 857 |
+
generator,
|
| 858 |
+
latents,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 862 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 863 |
+
|
| 864 |
+
# 6.1 Add image embeds for IP-Adapter
|
| 865 |
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
| 866 |
+
|
| 867 |
+
# 6.2 Optionally get Guidance Scale Embedding
|
| 868 |
+
timestep_cond = None
|
| 869 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
| 870 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
| 871 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
| 872 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
| 873 |
+
).to(device=device, dtype=latents.dtype)
|
| 874 |
+
|
| 875 |
+
# 7. Denoising loop
|
| 876 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 877 |
+
self._num_timesteps = len(timesteps)
|
| 878 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 879 |
+
for i, t in enumerate(timesteps):
|
| 880 |
+
# expand the latents if we are doing classifier free guidance
|
| 881 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 882 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 883 |
+
|
| 884 |
+
# predict the noise residual
|
| 885 |
+
noise_pred = self.unet(
|
| 886 |
+
latent_model_input,
|
| 887 |
+
t,
|
| 888 |
+
encoder_hidden_states=prompt_embeds,
|
| 889 |
+
timestep_cond=timestep_cond,
|
| 890 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 891 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 892 |
+
return_dict=False,
|
| 893 |
+
)[0]
|
| 894 |
+
|
| 895 |
+
# perform guidance
|
| 896 |
+
if self.do_classifier_free_guidance:
|
| 897 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 898 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 899 |
+
|
| 900 |
+
if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
|
| 901 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 902 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
|
| 903 |
+
|
| 904 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 905 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 906 |
+
|
| 907 |
+
if callback_on_step_end is not None:
|
| 908 |
+
callback_kwargs = {}
|
| 909 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 910 |
+
callback_kwargs[k] = locals()[k]
|
| 911 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 912 |
+
|
| 913 |
+
latents = callback_outputs.pop("latents", latents)
|
| 914 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 915 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 916 |
+
|
| 917 |
+
# call the callback, if provided
|
| 918 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 919 |
+
progress_bar.update()
|
| 920 |
+
if callback is not None and i % callback_steps == 0:
|
| 921 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 922 |
+
callback(step_idx, t, latents)
|
| 923 |
+
|
| 924 |
+
if not output_type == "latent":
|
| 925 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
| 926 |
+
0
|
| 927 |
+
]
|
| 928 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 929 |
+
else:
|
| 930 |
+
image = latents
|
| 931 |
+
has_nsfw_concept = None
|
| 932 |
+
|
| 933 |
+
if has_nsfw_concept is None:
|
| 934 |
+
do_denormalize = [True] * image.shape[0]
|
| 935 |
+
else:
|
| 936 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 937 |
+
|
| 938 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 939 |
+
|
| 940 |
+
# Offload all models
|
| 941 |
+
self.maybe_free_model_hooks()
|
| 942 |
+
|
| 943 |
+
if not return_dict:
|
| 944 |
+
return (image, has_nsfw_concept)
|
| 945 |
+
|
| 946 |
+
return AltDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py
ADDED
|
@@ -0,0 +1,1018 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import PIL.Image
|
| 20 |
+
import torch
|
| 21 |
+
from packaging import version
|
| 22 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, XLMRobertaTokenizer
|
| 23 |
+
|
| 24 |
+
from ....configuration_utils import FrozenDict
|
| 25 |
+
from ....image_processor import PipelineImageInput, VaeImageProcessor
|
| 26 |
+
from ....loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 27 |
+
from ....models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
| 28 |
+
from ....models.lora import adjust_lora_scale_text_encoder
|
| 29 |
+
from ....schedulers import KarrasDiffusionSchedulers
|
| 30 |
+
from ....utils import (
|
| 31 |
+
PIL_INTERPOLATION,
|
| 32 |
+
USE_PEFT_BACKEND,
|
| 33 |
+
deprecate,
|
| 34 |
+
logging,
|
| 35 |
+
replace_example_docstring,
|
| 36 |
+
scale_lora_layers,
|
| 37 |
+
unscale_lora_layers,
|
| 38 |
+
)
|
| 39 |
+
from ....utils.torch_utils import randn_tensor
|
| 40 |
+
from ...pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 41 |
+
from ...stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 42 |
+
from .modeling_roberta_series import RobertaSeriesModelWithTransformation
|
| 43 |
+
from .pipeline_output import AltDiffusionPipelineOutput
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 47 |
+
|
| 48 |
+
EXAMPLE_DOC_STRING = """
|
| 49 |
+
Examples:
|
| 50 |
+
```py
|
| 51 |
+
>>> import requests
|
| 52 |
+
>>> import torch
|
| 53 |
+
>>> from PIL import Image
|
| 54 |
+
>>> from io import BytesIO
|
| 55 |
+
|
| 56 |
+
>>> from diffusers import AltDiffusionImg2ImgPipeline
|
| 57 |
+
|
| 58 |
+
>>> device = "cuda"
|
| 59 |
+
>>> model_id_or_path = "BAAI/AltDiffusion-m9"
|
| 60 |
+
>>> pipe = AltDiffusionImg2ImgPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
|
| 61 |
+
>>> pipe = pipe.to(device)
|
| 62 |
+
|
| 63 |
+
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
|
| 64 |
+
|
| 65 |
+
>>> response = requests.get(url)
|
| 66 |
+
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 67 |
+
>>> init_image = init_image.resize((768, 512))
|
| 68 |
+
|
| 69 |
+
>>> # "A fantasy landscape, trending on artstation"
|
| 70 |
+
>>> prompt = "幻想风景, artstation"
|
| 71 |
+
|
| 72 |
+
>>> images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
|
| 73 |
+
>>> images[0].save("幻想风景.png")
|
| 74 |
+
```
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
| 79 |
+
def retrieve_latents(
|
| 80 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 81 |
+
):
|
| 82 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 83 |
+
return encoder_output.latent_dist.sample(generator)
|
| 84 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 85 |
+
return encoder_output.latent_dist.mode()
|
| 86 |
+
elif hasattr(encoder_output, "latents"):
|
| 87 |
+
return encoder_output.latents
|
| 88 |
+
else:
|
| 89 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.preprocess
|
| 93 |
+
def preprocess(image):
|
| 94 |
+
deprecation_message = "The preprocess method is deprecated and will be removed in diffusers 1.0.0. Please use VaeImageProcessor.preprocess(...) instead"
|
| 95 |
+
deprecate("preprocess", "1.0.0", deprecation_message, standard_warn=False)
|
| 96 |
+
if isinstance(image, torch.Tensor):
|
| 97 |
+
return image
|
| 98 |
+
elif isinstance(image, PIL.Image.Image):
|
| 99 |
+
image = [image]
|
| 100 |
+
|
| 101 |
+
if isinstance(image[0], PIL.Image.Image):
|
| 102 |
+
w, h = image[0].size
|
| 103 |
+
w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
|
| 104 |
+
|
| 105 |
+
image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
|
| 106 |
+
image = np.concatenate(image, axis=0)
|
| 107 |
+
image = np.array(image).astype(np.float32) / 255.0
|
| 108 |
+
image = image.transpose(0, 3, 1, 2)
|
| 109 |
+
image = 2.0 * image - 1.0
|
| 110 |
+
image = torch.from_numpy(image)
|
| 111 |
+
elif isinstance(image[0], torch.Tensor):
|
| 112 |
+
image = torch.cat(image, dim=0)
|
| 113 |
+
return image
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 117 |
+
def retrieve_timesteps(
|
| 118 |
+
scheduler,
|
| 119 |
+
num_inference_steps: Optional[int] = None,
|
| 120 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 121 |
+
timesteps: Optional[List[int]] = None,
|
| 122 |
+
**kwargs,
|
| 123 |
+
):
|
| 124 |
+
"""
|
| 125 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 126 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
scheduler (`SchedulerMixin`):
|
| 130 |
+
The scheduler to get timesteps from.
|
| 131 |
+
num_inference_steps (`int`):
|
| 132 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
| 133 |
+
`timesteps` must be `None`.
|
| 134 |
+
device (`str` or `torch.device`, *optional*):
|
| 135 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 136 |
+
timesteps (`List[int]`, *optional*):
|
| 137 |
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
| 138 |
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
| 139 |
+
must be `None`.
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 143 |
+
second element is the number of inference steps.
|
| 144 |
+
"""
|
| 145 |
+
if timesteps is not None:
|
| 146 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 147 |
+
if not accepts_timesteps:
|
| 148 |
+
raise ValueError(
|
| 149 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 150 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 151 |
+
)
|
| 152 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 153 |
+
timesteps = scheduler.timesteps
|
| 154 |
+
num_inference_steps = len(timesteps)
|
| 155 |
+
else:
|
| 156 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 157 |
+
timesteps = scheduler.timesteps
|
| 158 |
+
return timesteps, num_inference_steps
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class AltDiffusionImg2ImgPipeline(
|
| 162 |
+
DiffusionPipeline,
|
| 163 |
+
StableDiffusionMixin,
|
| 164 |
+
TextualInversionLoaderMixin,
|
| 165 |
+
IPAdapterMixin,
|
| 166 |
+
LoraLoaderMixin,
|
| 167 |
+
FromSingleFileMixin,
|
| 168 |
+
):
|
| 169 |
+
r"""
|
| 170 |
+
Pipeline for text-guided image-to-image generation using Alt Diffusion.
|
| 171 |
+
|
| 172 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 173 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 174 |
+
|
| 175 |
+
The pipeline also inherits the following loading methods:
|
| 176 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 177 |
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 178 |
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 179 |
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
| 180 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
vae ([`AutoencoderKL`]):
|
| 184 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 185 |
+
text_encoder ([`~transformers.RobertaSeriesModelWithTransformation`]):
|
| 186 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 187 |
+
tokenizer ([`~transformers.XLMRobertaTokenizer`]):
|
| 188 |
+
A `XLMRobertaTokenizer` to tokenize text.
|
| 189 |
+
unet ([`UNet2DConditionModel`]):
|
| 190 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 191 |
+
scheduler ([`SchedulerMixin`]):
|
| 192 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 193 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 194 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 195 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 196 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 197 |
+
about a model's potential harms.
|
| 198 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 199 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
| 203 |
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
| 204 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 205 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 206 |
+
|
| 207 |
+
def __init__(
|
| 208 |
+
self,
|
| 209 |
+
vae: AutoencoderKL,
|
| 210 |
+
text_encoder: RobertaSeriesModelWithTransformation,
|
| 211 |
+
tokenizer: XLMRobertaTokenizer,
|
| 212 |
+
unet: UNet2DConditionModel,
|
| 213 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 214 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 215 |
+
feature_extractor: CLIPImageProcessor,
|
| 216 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 217 |
+
requires_safety_checker: bool = True,
|
| 218 |
+
):
|
| 219 |
+
super().__init__()
|
| 220 |
+
|
| 221 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 222 |
+
deprecation_message = (
|
| 223 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 224 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 225 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 226 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 227 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 228 |
+
" file"
|
| 229 |
+
)
|
| 230 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 231 |
+
new_config = dict(scheduler.config)
|
| 232 |
+
new_config["steps_offset"] = 1
|
| 233 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 234 |
+
|
| 235 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 236 |
+
deprecation_message = (
|
| 237 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 238 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 239 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 240 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 241 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 242 |
+
)
|
| 243 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 244 |
+
new_config = dict(scheduler.config)
|
| 245 |
+
new_config["clip_sample"] = False
|
| 246 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 247 |
+
|
| 248 |
+
if safety_checker is None and requires_safety_checker:
|
| 249 |
+
logger.warning(
|
| 250 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 251 |
+
" that you abide to the conditions of the Alt Diffusion license and do not expose unfiltered"
|
| 252 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 253 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 254 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 255 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
if safety_checker is not None and feature_extractor is None:
|
| 259 |
+
raise ValueError(
|
| 260 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 261 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 265 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 266 |
+
) < version.parse("0.9.0.dev0")
|
| 267 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 268 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 269 |
+
deprecation_message = (
|
| 270 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 271 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 272 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 273 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 274 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 275 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 276 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 277 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 278 |
+
" the `unet/config.json` file"
|
| 279 |
+
)
|
| 280 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 281 |
+
new_config = dict(unet.config)
|
| 282 |
+
new_config["sample_size"] = 64
|
| 283 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 284 |
+
|
| 285 |
+
self.register_modules(
|
| 286 |
+
vae=vae,
|
| 287 |
+
text_encoder=text_encoder,
|
| 288 |
+
tokenizer=tokenizer,
|
| 289 |
+
unet=unet,
|
| 290 |
+
scheduler=scheduler,
|
| 291 |
+
safety_checker=safety_checker,
|
| 292 |
+
feature_extractor=feature_extractor,
|
| 293 |
+
image_encoder=image_encoder,
|
| 294 |
+
)
|
| 295 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 296 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 297 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 298 |
+
|
| 299 |
+
def _encode_prompt(
|
| 300 |
+
self,
|
| 301 |
+
prompt,
|
| 302 |
+
device,
|
| 303 |
+
num_images_per_prompt,
|
| 304 |
+
do_classifier_free_guidance,
|
| 305 |
+
negative_prompt=None,
|
| 306 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 307 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 308 |
+
lora_scale: Optional[float] = None,
|
| 309 |
+
**kwargs,
|
| 310 |
+
):
|
| 311 |
+
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."
|
| 312 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 313 |
+
|
| 314 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 315 |
+
prompt=prompt,
|
| 316 |
+
device=device,
|
| 317 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 318 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 319 |
+
negative_prompt=negative_prompt,
|
| 320 |
+
prompt_embeds=prompt_embeds,
|
| 321 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 322 |
+
lora_scale=lora_scale,
|
| 323 |
+
**kwargs,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# concatenate for backwards comp
|
| 327 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 328 |
+
|
| 329 |
+
return prompt_embeds
|
| 330 |
+
|
| 331 |
+
def encode_prompt(
|
| 332 |
+
self,
|
| 333 |
+
prompt,
|
| 334 |
+
device,
|
| 335 |
+
num_images_per_prompt,
|
| 336 |
+
do_classifier_free_guidance,
|
| 337 |
+
negative_prompt=None,
|
| 338 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 339 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 340 |
+
lora_scale: Optional[float] = None,
|
| 341 |
+
clip_skip: Optional[int] = None,
|
| 342 |
+
):
|
| 343 |
+
r"""
|
| 344 |
+
Encodes the prompt into text encoder hidden states.
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 348 |
+
prompt to be encoded
|
| 349 |
+
device: (`torch.device`):
|
| 350 |
+
torch device
|
| 351 |
+
num_images_per_prompt (`int`):
|
| 352 |
+
number of images that should be generated per prompt
|
| 353 |
+
do_classifier_free_guidance (`bool`):
|
| 354 |
+
whether to use classifier free guidance or not
|
| 355 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 356 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 357 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 358 |
+
less than `1`).
|
| 359 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 360 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 361 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 362 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 363 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 364 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 365 |
+
argument.
|
| 366 |
+
lora_scale (`float`, *optional*):
|
| 367 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 368 |
+
clip_skip (`int`, *optional*):
|
| 369 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 370 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 371 |
+
"""
|
| 372 |
+
# set lora scale so that monkey patched LoRA
|
| 373 |
+
# function of text encoder can correctly access it
|
| 374 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 375 |
+
self._lora_scale = lora_scale
|
| 376 |
+
|
| 377 |
+
# dynamically adjust the LoRA scale
|
| 378 |
+
if not USE_PEFT_BACKEND:
|
| 379 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 380 |
+
else:
|
| 381 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 382 |
+
|
| 383 |
+
if prompt is not None and isinstance(prompt, str):
|
| 384 |
+
batch_size = 1
|
| 385 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 386 |
+
batch_size = len(prompt)
|
| 387 |
+
else:
|
| 388 |
+
batch_size = prompt_embeds.shape[0]
|
| 389 |
+
|
| 390 |
+
if prompt_embeds is None:
|
| 391 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 392 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 393 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 394 |
+
|
| 395 |
+
text_inputs = self.tokenizer(
|
| 396 |
+
prompt,
|
| 397 |
+
padding="max_length",
|
| 398 |
+
max_length=self.tokenizer.model_max_length,
|
| 399 |
+
truncation=True,
|
| 400 |
+
return_tensors="pt",
|
| 401 |
+
)
|
| 402 |
+
text_input_ids = text_inputs.input_ids
|
| 403 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 404 |
+
|
| 405 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 406 |
+
text_input_ids, untruncated_ids
|
| 407 |
+
):
|
| 408 |
+
removed_text = self.tokenizer.batch_decode(
|
| 409 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 410 |
+
)
|
| 411 |
+
logger.warning(
|
| 412 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 413 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 417 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 418 |
+
else:
|
| 419 |
+
attention_mask = None
|
| 420 |
+
|
| 421 |
+
if clip_skip is None:
|
| 422 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 423 |
+
prompt_embeds = prompt_embeds[0]
|
| 424 |
+
else:
|
| 425 |
+
prompt_embeds = self.text_encoder(
|
| 426 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 427 |
+
)
|
| 428 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 429 |
+
# all the hidden states from the encoder layers. Then index into
|
| 430 |
+
# the tuple to access the hidden states from the desired layer.
|
| 431 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 432 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 433 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 434 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 435 |
+
# layer.
|
| 436 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 437 |
+
|
| 438 |
+
if self.text_encoder is not None:
|
| 439 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 440 |
+
elif self.unet is not None:
|
| 441 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 442 |
+
else:
|
| 443 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 444 |
+
|
| 445 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 446 |
+
|
| 447 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 448 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 449 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 450 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 451 |
+
|
| 452 |
+
# get unconditional embeddings for classifier free guidance
|
| 453 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 454 |
+
uncond_tokens: List[str]
|
| 455 |
+
if negative_prompt is None:
|
| 456 |
+
uncond_tokens = [""] * batch_size
|
| 457 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 458 |
+
raise TypeError(
|
| 459 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 460 |
+
f" {type(prompt)}."
|
| 461 |
+
)
|
| 462 |
+
elif isinstance(negative_prompt, str):
|
| 463 |
+
uncond_tokens = [negative_prompt]
|
| 464 |
+
elif batch_size != len(negative_prompt):
|
| 465 |
+
raise ValueError(
|
| 466 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 467 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 468 |
+
" the batch size of `prompt`."
|
| 469 |
+
)
|
| 470 |
+
else:
|
| 471 |
+
uncond_tokens = negative_prompt
|
| 472 |
+
|
| 473 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 474 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 475 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 476 |
+
|
| 477 |
+
max_length = prompt_embeds.shape[1]
|
| 478 |
+
uncond_input = self.tokenizer(
|
| 479 |
+
uncond_tokens,
|
| 480 |
+
padding="max_length",
|
| 481 |
+
max_length=max_length,
|
| 482 |
+
truncation=True,
|
| 483 |
+
return_tensors="pt",
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 487 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 488 |
+
else:
|
| 489 |
+
attention_mask = None
|
| 490 |
+
|
| 491 |
+
negative_prompt_embeds = self.text_encoder(
|
| 492 |
+
uncond_input.input_ids.to(device),
|
| 493 |
+
attention_mask=attention_mask,
|
| 494 |
+
)
|
| 495 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 496 |
+
|
| 497 |
+
if do_classifier_free_guidance:
|
| 498 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 499 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 500 |
+
|
| 501 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 502 |
+
|
| 503 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 504 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 505 |
+
|
| 506 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 507 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 508 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 509 |
+
|
| 510 |
+
return prompt_embeds, negative_prompt_embeds
|
| 511 |
+
|
| 512 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
| 513 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 514 |
+
|
| 515 |
+
if not isinstance(image, torch.Tensor):
|
| 516 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 517 |
+
|
| 518 |
+
image = image.to(device=device, dtype=dtype)
|
| 519 |
+
if output_hidden_states:
|
| 520 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
| 521 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
| 522 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
| 523 |
+
torch.zeros_like(image), output_hidden_states=True
|
| 524 |
+
).hidden_states[-2]
|
| 525 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
| 526 |
+
num_images_per_prompt, dim=0
|
| 527 |
+
)
|
| 528 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
| 529 |
+
else:
|
| 530 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 531 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 532 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
| 533 |
+
|
| 534 |
+
return image_embeds, uncond_image_embeds
|
| 535 |
+
|
| 536 |
+
def run_safety_checker(self, image, device, dtype):
|
| 537 |
+
if self.safety_checker is None:
|
| 538 |
+
has_nsfw_concept = None
|
| 539 |
+
else:
|
| 540 |
+
if torch.is_tensor(image):
|
| 541 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 542 |
+
else:
|
| 543 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 544 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 545 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 546 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 547 |
+
)
|
| 548 |
+
return image, has_nsfw_concept
|
| 549 |
+
|
| 550 |
+
def decode_latents(self, latents):
|
| 551 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 552 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 553 |
+
|
| 554 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 555 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 556 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 557 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 558 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 559 |
+
return image
|
| 560 |
+
|
| 561 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 562 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 563 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 564 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 565 |
+
# and should be between [0, 1]
|
| 566 |
+
|
| 567 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 568 |
+
extra_step_kwargs = {}
|
| 569 |
+
if accepts_eta:
|
| 570 |
+
extra_step_kwargs["eta"] = eta
|
| 571 |
+
|
| 572 |
+
# check if the scheduler accepts generator
|
| 573 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 574 |
+
if accepts_generator:
|
| 575 |
+
extra_step_kwargs["generator"] = generator
|
| 576 |
+
return extra_step_kwargs
|
| 577 |
+
|
| 578 |
+
def check_inputs(
|
| 579 |
+
self,
|
| 580 |
+
prompt,
|
| 581 |
+
strength,
|
| 582 |
+
callback_steps,
|
| 583 |
+
negative_prompt=None,
|
| 584 |
+
prompt_embeds=None,
|
| 585 |
+
negative_prompt_embeds=None,
|
| 586 |
+
callback_on_step_end_tensor_inputs=None,
|
| 587 |
+
):
|
| 588 |
+
if strength < 0 or strength > 1:
|
| 589 |
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
| 590 |
+
|
| 591 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 592 |
+
raise ValueError(
|
| 593 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 594 |
+
f" {type(callback_steps)}."
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 598 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 599 |
+
):
|
| 600 |
+
raise ValueError(
|
| 601 |
+
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]}"
|
| 602 |
+
)
|
| 603 |
+
if prompt is not None and prompt_embeds is not None:
|
| 604 |
+
raise ValueError(
|
| 605 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 606 |
+
" only forward one of the two."
|
| 607 |
+
)
|
| 608 |
+
elif prompt is None and prompt_embeds is None:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 611 |
+
)
|
| 612 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 613 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 614 |
+
|
| 615 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 616 |
+
raise ValueError(
|
| 617 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 618 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 622 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 623 |
+
raise ValueError(
|
| 624 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 625 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 626 |
+
f" {negative_prompt_embeds.shape}."
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
def get_timesteps(self, num_inference_steps, strength, device):
|
| 630 |
+
# get the original timestep using init_timestep
|
| 631 |
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
| 632 |
+
|
| 633 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
| 634 |
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
| 635 |
+
|
| 636 |
+
return timesteps, num_inference_steps - t_start
|
| 637 |
+
|
| 638 |
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
|
| 639 |
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
| 640 |
+
raise ValueError(
|
| 641 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
image = image.to(device=device, dtype=dtype)
|
| 645 |
+
|
| 646 |
+
batch_size = batch_size * num_images_per_prompt
|
| 647 |
+
|
| 648 |
+
if image.shape[1] == 4:
|
| 649 |
+
init_latents = image
|
| 650 |
+
|
| 651 |
+
else:
|
| 652 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 653 |
+
raise ValueError(
|
| 654 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 655 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
elif isinstance(generator, list):
|
| 659 |
+
init_latents = [
|
| 660 |
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
| 661 |
+
for i in range(batch_size)
|
| 662 |
+
]
|
| 663 |
+
init_latents = torch.cat(init_latents, dim=0)
|
| 664 |
+
else:
|
| 665 |
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
| 666 |
+
|
| 667 |
+
init_latents = self.vae.config.scaling_factor * init_latents
|
| 668 |
+
|
| 669 |
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
| 670 |
+
# expand init_latents for batch_size
|
| 671 |
+
deprecation_message = (
|
| 672 |
+
f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
|
| 673 |
+
" images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
|
| 674 |
+
" that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
|
| 675 |
+
" your script to pass as many initial images as text prompts to suppress this warning."
|
| 676 |
+
)
|
| 677 |
+
deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
|
| 678 |
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
| 679 |
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
| 680 |
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
| 681 |
+
raise ValueError(
|
| 682 |
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
| 683 |
+
)
|
| 684 |
+
else:
|
| 685 |
+
init_latents = torch.cat([init_latents], dim=0)
|
| 686 |
+
|
| 687 |
+
shape = init_latents.shape
|
| 688 |
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 689 |
+
|
| 690 |
+
# get latents
|
| 691 |
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
| 692 |
+
latents = init_latents
|
| 693 |
+
|
| 694 |
+
return latents
|
| 695 |
+
|
| 696 |
+
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
| 697 |
+
"""
|
| 698 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
timesteps (`torch.Tensor`):
|
| 702 |
+
generate embedding vectors at these timesteps
|
| 703 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
| 704 |
+
dimension of the embeddings to generate
|
| 705 |
+
dtype:
|
| 706 |
+
data type of the generated embeddings
|
| 707 |
+
|
| 708 |
+
Returns:
|
| 709 |
+
`torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
|
| 710 |
+
"""
|
| 711 |
+
assert len(w.shape) == 1
|
| 712 |
+
w = w * 1000.0
|
| 713 |
+
|
| 714 |
+
half_dim = embedding_dim // 2
|
| 715 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
| 716 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
| 717 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
| 718 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 719 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 720 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
| 721 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
| 722 |
+
return emb
|
| 723 |
+
|
| 724 |
+
@property
|
| 725 |
+
def guidance_scale(self):
|
| 726 |
+
return self._guidance_scale
|
| 727 |
+
|
| 728 |
+
@property
|
| 729 |
+
def clip_skip(self):
|
| 730 |
+
return self._clip_skip
|
| 731 |
+
|
| 732 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 733 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 734 |
+
# corresponds to doing no classifier free guidance.
|
| 735 |
+
@property
|
| 736 |
+
def do_classifier_free_guidance(self):
|
| 737 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
| 738 |
+
|
| 739 |
+
@property
|
| 740 |
+
def cross_attention_kwargs(self):
|
| 741 |
+
return self._cross_attention_kwargs
|
| 742 |
+
|
| 743 |
+
@property
|
| 744 |
+
def num_timesteps(self):
|
| 745 |
+
return self._num_timesteps
|
| 746 |
+
|
| 747 |
+
@torch.no_grad()
|
| 748 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 749 |
+
def __call__(
|
| 750 |
+
self,
|
| 751 |
+
prompt: Union[str, List[str]] = None,
|
| 752 |
+
image: PipelineImageInput = None,
|
| 753 |
+
strength: float = 0.8,
|
| 754 |
+
num_inference_steps: Optional[int] = 50,
|
| 755 |
+
timesteps: List[int] = None,
|
| 756 |
+
guidance_scale: Optional[float] = 7.5,
|
| 757 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 758 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 759 |
+
eta: Optional[float] = 0.0,
|
| 760 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 761 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 762 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 763 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 764 |
+
output_type: Optional[str] = "pil",
|
| 765 |
+
return_dict: bool = True,
|
| 766 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 767 |
+
clip_skip: int = None,
|
| 768 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 769 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 770 |
+
**kwargs,
|
| 771 |
+
):
|
| 772 |
+
r"""
|
| 773 |
+
The call function to the pipeline for generation.
|
| 774 |
+
|
| 775 |
+
Args:
|
| 776 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 777 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 778 |
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
| 779 |
+
`Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
|
| 780 |
+
numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
|
| 781 |
+
or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
|
| 782 |
+
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
|
| 783 |
+
latents as `image`, but if passing latents directly it is not encoded again.
|
| 784 |
+
strength (`float`, *optional*, defaults to 0.8):
|
| 785 |
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
| 786 |
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
| 787 |
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
| 788 |
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
| 789 |
+
essentially ignores `image`.
|
| 790 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 791 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 792 |
+
expense of slower inference. This parameter is modulated by `strength`.
|
| 793 |
+
timesteps (`List[int]`, *optional*):
|
| 794 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
| 795 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
| 796 |
+
passed will be used. Must be in descending order.
|
| 797 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 798 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 799 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 800 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 801 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 802 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 803 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 804 |
+
The number of images to generate per prompt.
|
| 805 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 806 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 807 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 808 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 809 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 810 |
+
generation deterministic.
|
| 811 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 812 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 813 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 814 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 815 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 816 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 817 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
| 818 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 819 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 820 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 821 |
+
Whether or not to return a [`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] instead of a
|
| 822 |
+
plain tuple.
|
| 823 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 824 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 825 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 826 |
+
clip_skip (`int`, *optional*):
|
| 827 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 828 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 829 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 830 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 831 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 832 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 833 |
+
`callback_on_step_end_tensor_inputs`.
|
| 834 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 835 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 836 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 837 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 838 |
+
Examples:
|
| 839 |
+
|
| 840 |
+
Returns:
|
| 841 |
+
[`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] or `tuple`:
|
| 842 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.AltDiffusionPipelineOutput`] is returned,
|
| 843 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 844 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 845 |
+
"not-safe-for-work" (nsfw) content.
|
| 846 |
+
"""
|
| 847 |
+
|
| 848 |
+
callback = kwargs.pop("callback", None)
|
| 849 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 850 |
+
|
| 851 |
+
if callback is not None:
|
| 852 |
+
deprecate(
|
| 853 |
+
"callback",
|
| 854 |
+
"1.0.0",
|
| 855 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 856 |
+
)
|
| 857 |
+
if callback_steps is not None:
|
| 858 |
+
deprecate(
|
| 859 |
+
"callback_steps",
|
| 860 |
+
"1.0.0",
|
| 861 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
# 1. Check inputs. Raise error if not correct
|
| 865 |
+
self.check_inputs(
|
| 866 |
+
prompt,
|
| 867 |
+
strength,
|
| 868 |
+
callback_steps,
|
| 869 |
+
negative_prompt,
|
| 870 |
+
prompt_embeds,
|
| 871 |
+
negative_prompt_embeds,
|
| 872 |
+
callback_on_step_end_tensor_inputs,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
self._guidance_scale = guidance_scale
|
| 876 |
+
self._clip_skip = clip_skip
|
| 877 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 878 |
+
|
| 879 |
+
# 2. Define call parameters
|
| 880 |
+
if prompt is not None and isinstance(prompt, str):
|
| 881 |
+
batch_size = 1
|
| 882 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 883 |
+
batch_size = len(prompt)
|
| 884 |
+
else:
|
| 885 |
+
batch_size = prompt_embeds.shape[0]
|
| 886 |
+
|
| 887 |
+
device = self._execution_device
|
| 888 |
+
|
| 889 |
+
# 3. Encode input prompt
|
| 890 |
+
text_encoder_lora_scale = (
|
| 891 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 892 |
+
)
|
| 893 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 894 |
+
prompt,
|
| 895 |
+
device,
|
| 896 |
+
num_images_per_prompt,
|
| 897 |
+
self.do_classifier_free_guidance,
|
| 898 |
+
negative_prompt,
|
| 899 |
+
prompt_embeds=prompt_embeds,
|
| 900 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 901 |
+
lora_scale=text_encoder_lora_scale,
|
| 902 |
+
clip_skip=self.clip_skip,
|
| 903 |
+
)
|
| 904 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 905 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 906 |
+
# to avoid doing two forward passes
|
| 907 |
+
if self.do_classifier_free_guidance:
|
| 908 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 909 |
+
|
| 910 |
+
if ip_adapter_image is not None:
|
| 911 |
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
| 912 |
+
image_embeds, negative_image_embeds = self.encode_image(
|
| 913 |
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
| 914 |
+
)
|
| 915 |
+
if self.do_classifier_free_guidance:
|
| 916 |
+
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
| 917 |
+
|
| 918 |
+
# 4. Preprocess image
|
| 919 |
+
image = self.image_processor.preprocess(image)
|
| 920 |
+
|
| 921 |
+
# 5. set timesteps
|
| 922 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
| 923 |
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
| 924 |
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
| 925 |
+
|
| 926 |
+
# 6. Prepare latent variables
|
| 927 |
+
latents = self.prepare_latents(
|
| 928 |
+
image,
|
| 929 |
+
latent_timestep,
|
| 930 |
+
batch_size,
|
| 931 |
+
num_images_per_prompt,
|
| 932 |
+
prompt_embeds.dtype,
|
| 933 |
+
device,
|
| 934 |
+
generator,
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 938 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 939 |
+
|
| 940 |
+
# 7.1 Add image embeds for IP-Adapter
|
| 941 |
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
| 942 |
+
|
| 943 |
+
# 7.2 Optionally get Guidance Scale Embedding
|
| 944 |
+
timestep_cond = None
|
| 945 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
| 946 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
| 947 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
| 948 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
| 949 |
+
).to(device=device, dtype=latents.dtype)
|
| 950 |
+
|
| 951 |
+
# 8. Denoising loop
|
| 952 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 953 |
+
self._num_timesteps = len(timesteps)
|
| 954 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 955 |
+
for i, t in enumerate(timesteps):
|
| 956 |
+
# expand the latents if we are doing classifier free guidance
|
| 957 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 958 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 959 |
+
|
| 960 |
+
# predict the noise residual
|
| 961 |
+
noise_pred = self.unet(
|
| 962 |
+
latent_model_input,
|
| 963 |
+
t,
|
| 964 |
+
encoder_hidden_states=prompt_embeds,
|
| 965 |
+
timestep_cond=timestep_cond,
|
| 966 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 967 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 968 |
+
return_dict=False,
|
| 969 |
+
)[0]
|
| 970 |
+
|
| 971 |
+
# perform guidance
|
| 972 |
+
if self.do_classifier_free_guidance:
|
| 973 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 974 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 975 |
+
|
| 976 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 977 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 978 |
+
|
| 979 |
+
if callback_on_step_end is not None:
|
| 980 |
+
callback_kwargs = {}
|
| 981 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 982 |
+
callback_kwargs[k] = locals()[k]
|
| 983 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 984 |
+
|
| 985 |
+
latents = callback_outputs.pop("latents", latents)
|
| 986 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 987 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 988 |
+
|
| 989 |
+
# call the callback, if provided
|
| 990 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 991 |
+
progress_bar.update()
|
| 992 |
+
if callback is not None and i % callback_steps == 0:
|
| 993 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 994 |
+
callback(step_idx, t, latents)
|
| 995 |
+
|
| 996 |
+
if not output_type == "latent":
|
| 997 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
| 998 |
+
0
|
| 999 |
+
]
|
| 1000 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 1001 |
+
else:
|
| 1002 |
+
image = latents
|
| 1003 |
+
has_nsfw_concept = None
|
| 1004 |
+
|
| 1005 |
+
if has_nsfw_concept is None:
|
| 1006 |
+
do_denormalize = [True] * image.shape[0]
|
| 1007 |
+
else:
|
| 1008 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 1009 |
+
|
| 1010 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 1011 |
+
|
| 1012 |
+
# Offload all models
|
| 1013 |
+
self.maybe_free_model_hooks()
|
| 1014 |
+
|
| 1015 |
+
if not return_dict:
|
| 1016 |
+
return (image, has_nsfw_concept)
|
| 1017 |
+
|
| 1018 |
+
return AltDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ....utils import DIFFUSERS_SLOW_IMPORT, _LazyModule
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_import_structure = {"pipeline_latent_diffusion_uncond": ["LDMPipeline"]}
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 9 |
+
from .pipeline_latent_diffusion_uncond import LDMPipeline
|
| 10 |
+
else:
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.modules[__name__] = _LazyModule(
|
| 14 |
+
__name__,
|
| 15 |
+
globals()["__file__"],
|
| 16 |
+
_import_structure,
|
| 17 |
+
module_spec=__spec__,
|
| 18 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (581 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/__pycache__/pipeline_latent_diffusion_uncond.cpython-310.pyc
ADDED
|
Binary file (4.58 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from typing import List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from ....models import UNet2DModel, VQModel
|
| 21 |
+
from ....schedulers import DDIMScheduler
|
| 22 |
+
from ....utils.torch_utils import randn_tensor
|
| 23 |
+
from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LDMPipeline(DiffusionPipeline):
|
| 27 |
+
r"""
|
| 28 |
+
Pipeline for unconditional image generation using latent diffusion.
|
| 29 |
+
|
| 30 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 31 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 32 |
+
|
| 33 |
+
Parameters:
|
| 34 |
+
vqvae ([`VQModel`]):
|
| 35 |
+
Vector-quantized (VQ) model to encode and decode images to and from latent representations.
|
| 36 |
+
unet ([`UNet2DModel`]):
|
| 37 |
+
A `UNet2DModel` to denoise the encoded image latents.
|
| 38 |
+
scheduler ([`SchedulerMixin`]):
|
| 39 |
+
[`DDIMScheduler`] is used in combination with `unet` to denoise the encoded image latents.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, vqvae: VQModel, unet: UNet2DModel, scheduler: DDIMScheduler):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.register_modules(vqvae=vqvae, unet=unet, scheduler=scheduler)
|
| 45 |
+
|
| 46 |
+
@torch.no_grad()
|
| 47 |
+
def __call__(
|
| 48 |
+
self,
|
| 49 |
+
batch_size: int = 1,
|
| 50 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 51 |
+
eta: float = 0.0,
|
| 52 |
+
num_inference_steps: int = 50,
|
| 53 |
+
output_type: Optional[str] = "pil",
|
| 54 |
+
return_dict: bool = True,
|
| 55 |
+
**kwargs,
|
| 56 |
+
) -> Union[Tuple, ImagePipelineOutput]:
|
| 57 |
+
r"""
|
| 58 |
+
The call function to the pipeline for generation.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
batch_size (`int`, *optional*, defaults to 1):
|
| 62 |
+
Number of images to generate.
|
| 63 |
+
generator (`torch.Generator`, *optional*):
|
| 64 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 65 |
+
generation deterministic.
|
| 66 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 67 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 68 |
+
expense of slower inference.
|
| 69 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 70 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 71 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```py
|
| 77 |
+
>>> from diffusers import LDMPipeline
|
| 78 |
+
|
| 79 |
+
>>> # load model and scheduler
|
| 80 |
+
>>> pipe = LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256")
|
| 81 |
+
|
| 82 |
+
>>> # run pipeline in inference (sample random noise and denoise)
|
| 83 |
+
>>> image = pipe().images[0]
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`:
|
| 88 |
+
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
|
| 89 |
+
returned where the first element is a list with the generated images
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
latents = randn_tensor(
|
| 93 |
+
(batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
|
| 94 |
+
generator=generator,
|
| 95 |
+
)
|
| 96 |
+
latents = latents.to(self.device)
|
| 97 |
+
|
| 98 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 99 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 100 |
+
|
| 101 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
| 102 |
+
|
| 103 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 104 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 105 |
+
|
| 106 |
+
extra_kwargs = {}
|
| 107 |
+
if accepts_eta:
|
| 108 |
+
extra_kwargs["eta"] = eta
|
| 109 |
+
|
| 110 |
+
for t in self.progress_bar(self.scheduler.timesteps):
|
| 111 |
+
latent_model_input = self.scheduler.scale_model_input(latents, t)
|
| 112 |
+
# predict the noise residual
|
| 113 |
+
noise_prediction = self.unet(latent_model_input, t).sample
|
| 114 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 115 |
+
latents = self.scheduler.step(noise_prediction, t, latents, **extra_kwargs).prev_sample
|
| 116 |
+
|
| 117 |
+
# adjust latents with inverse of vae scale
|
| 118 |
+
latents = latents / self.vqvae.config.scaling_factor
|
| 119 |
+
# decode the image latents with the VAE
|
| 120 |
+
image = self.vqvae.decode(latents).sample
|
| 121 |
+
|
| 122 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 123 |
+
image = image.cpu().permute(0, 2, 3, 1).numpy()
|
| 124 |
+
if output_type == "pil":
|
| 125 |
+
image = self.numpy_to_pil(image)
|
| 126 |
+
|
| 127 |
+
if not return_dict:
|
| 128 |
+
return (image,)
|
| 129 |
+
|
| 130 |
+
return ImagePipelineOutput(images=image)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ....utils import DIFFUSERS_SLOW_IMPORT, _LazyModule
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_import_structure = {"pipeline_pndm": ["PNDMPipeline"]}
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 9 |
+
from .pipeline_pndm import PNDMPipeline
|
| 10 |
+
else:
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.modules[__name__] = _LazyModule(
|
| 14 |
+
__name__,
|
| 15 |
+
globals()["__file__"],
|
| 16 |
+
_import_structure,
|
| 17 |
+
module_spec=__spec__,
|
| 18 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (544 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/__pycache__/pipeline_pndm.cpython-310.pyc
ADDED
|
Binary file (4.12 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/pndm/pipeline_pndm.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from typing import List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from ....models import UNet2DModel
|
| 21 |
+
from ....schedulers import PNDMScheduler
|
| 22 |
+
from ....utils.torch_utils import randn_tensor
|
| 23 |
+
from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PNDMPipeline(DiffusionPipeline):
|
| 27 |
+
r"""
|
| 28 |
+
Pipeline for unconditional image generation.
|
| 29 |
+
|
| 30 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 31 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 32 |
+
|
| 33 |
+
Parameters:
|
| 34 |
+
unet ([`UNet2DModel`]):
|
| 35 |
+
A `UNet2DModel` to denoise the encoded image latents.
|
| 36 |
+
scheduler ([`PNDMScheduler`]):
|
| 37 |
+
A `PNDMScheduler` to be used in combination with `unet` to denoise the encoded image.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
unet: UNet2DModel
|
| 41 |
+
scheduler: PNDMScheduler
|
| 42 |
+
|
| 43 |
+
def __init__(self, unet: UNet2DModel, scheduler: PNDMScheduler):
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
scheduler = PNDMScheduler.from_config(scheduler.config)
|
| 47 |
+
|
| 48 |
+
self.register_modules(unet=unet, scheduler=scheduler)
|
| 49 |
+
|
| 50 |
+
@torch.no_grad()
|
| 51 |
+
def __call__(
|
| 52 |
+
self,
|
| 53 |
+
batch_size: int = 1,
|
| 54 |
+
num_inference_steps: int = 50,
|
| 55 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 56 |
+
output_type: Optional[str] = "pil",
|
| 57 |
+
return_dict: bool = True,
|
| 58 |
+
**kwargs,
|
| 59 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 60 |
+
r"""
|
| 61 |
+
The call function to the pipeline for generation.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
batch_size (`int`, `optional`, defaults to 1):
|
| 65 |
+
The number of images to generate.
|
| 66 |
+
num_inference_steps (`int`, `optional`, defaults to 50):
|
| 67 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 68 |
+
expense of slower inference.
|
| 69 |
+
generator (`torch.Generator`, `optional`):
|
| 70 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 71 |
+
generation deterministic.
|
| 72 |
+
output_type (`str`, `optional`, defaults to `"pil"`):
|
| 73 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 74 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 75 |
+
Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
|
| 76 |
+
|
| 77 |
+
Example:
|
| 78 |
+
|
| 79 |
+
```py
|
| 80 |
+
>>> from diffusers import PNDMPipeline
|
| 81 |
+
|
| 82 |
+
>>> # load model and scheduler
|
| 83 |
+
>>> pndm = PNDMPipeline.from_pretrained("google/ddpm-cifar10-32")
|
| 84 |
+
|
| 85 |
+
>>> # run pipeline in inference (sample random noise and denoise)
|
| 86 |
+
>>> image = pndm().images[0]
|
| 87 |
+
|
| 88 |
+
>>> # save image
|
| 89 |
+
>>> image.save("pndm_generated_image.png")
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`:
|
| 94 |
+
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
|
| 95 |
+
returned where the first element is a list with the generated images.
|
| 96 |
+
"""
|
| 97 |
+
# For more information on the sampling method you can take a look at Algorithm 2 of
|
| 98 |
+
# the official paper: https://arxiv.org/pdf/2202.09778.pdf
|
| 99 |
+
|
| 100 |
+
# Sample gaussian noise to begin loop
|
| 101 |
+
image = randn_tensor(
|
| 102 |
+
(batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
|
| 103 |
+
generator=generator,
|
| 104 |
+
device=self.device,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
| 108 |
+
for t in self.progress_bar(self.scheduler.timesteps):
|
| 109 |
+
model_output = self.unet(image, t).sample
|
| 110 |
+
|
| 111 |
+
image = self.scheduler.step(model_output, t, image).prev_sample
|
| 112 |
+
|
| 113 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 114 |
+
image = image.cpu().permute(0, 2, 3, 1).numpy()
|
| 115 |
+
if output_type == "pil":
|
| 116 |
+
image = self.numpy_to_pil(image)
|
| 117 |
+
|
| 118 |
+
if not return_dict:
|
| 119 |
+
return (image,)
|
| 120 |
+
|
| 121 |
+
return ImagePipelineOutput(images=image)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/score_sde_ve/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (566 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/score_sde_ve/__pycache__/pipeline_score_sde_ve.cpython-310.pyc
ADDED
|
Binary file (3.81 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
from typing import TYPE_CHECKING
|
| 3 |
+
from ....utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
_LazyModule,
|
| 6 |
+
is_note_seq_available,
|
| 7 |
+
OptionalDependencyNotAvailable,
|
| 8 |
+
is_torch_available,
|
| 9 |
+
is_transformers_available,
|
| 10 |
+
get_objects_from_module,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
_dummy_objects = {}
|
| 14 |
+
_import_structure = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 18 |
+
raise OptionalDependencyNotAvailable()
|
| 19 |
+
except OptionalDependencyNotAvailable:
|
| 20 |
+
from ....utils import dummy_torch_and_transformers_objects # noqa F403
|
| 21 |
+
|
| 22 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 23 |
+
else:
|
| 24 |
+
_import_structure["continous_encoder"] = ["SpectrogramContEncoder"]
|
| 25 |
+
_import_structure["notes_encoder"] = ["SpectrogramNotesEncoder"]
|
| 26 |
+
_import_structure["pipeline_spectrogram_diffusion"] = [
|
| 27 |
+
"SpectrogramContEncoder",
|
| 28 |
+
"SpectrogramDiffusionPipeline",
|
| 29 |
+
"T5FilmDecoder",
|
| 30 |
+
]
|
| 31 |
+
try:
|
| 32 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 33 |
+
raise OptionalDependencyNotAvailable()
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
from ....utils import dummy_transformers_and_torch_and_note_seq_objects
|
| 36 |
+
|
| 37 |
+
_dummy_objects.update(get_objects_from_module(dummy_transformers_and_torch_and_note_seq_objects))
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["midi_utils"] = ["MidiProcessor"]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 43 |
+
try:
|
| 44 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 45 |
+
raise OptionalDependencyNotAvailable()
|
| 46 |
+
|
| 47 |
+
except OptionalDependencyNotAvailable:
|
| 48 |
+
from ....utils.dummy_torch_and_transformers_objects import *
|
| 49 |
+
else:
|
| 50 |
+
from .pipeline_spectrogram_diffusion import SpectrogramDiffusionPipeline
|
| 51 |
+
from .pipeline_spectrogram_diffusion import SpectrogramContEncoder
|
| 52 |
+
from .pipeline_spectrogram_diffusion import SpectrogramNotesEncoder
|
| 53 |
+
from .pipeline_spectrogram_diffusion import T5FilmDecoder
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 57 |
+
raise OptionalDependencyNotAvailable()
|
| 58 |
+
except OptionalDependencyNotAvailable:
|
| 59 |
+
from ....utils.dummy_transformers_and_torch_and_note_seq_objects import *
|
| 60 |
+
|
| 61 |
+
else:
|
| 62 |
+
from .midi_utils import MidiProcessor
|
| 63 |
+
|
| 64 |
+
else:
|
| 65 |
+
import sys
|
| 66 |
+
|
| 67 |
+
sys.modules[__name__] = _LazyModule(
|
| 68 |
+
__name__,
|
| 69 |
+
globals()["__file__"],
|
| 70 |
+
_import_structure,
|
| 71 |
+
module_spec=__spec__,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
for name, value in _dummy_objects.items():
|
| 75 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/continuous_encoder.cpython-310.pyc
ADDED
|
Binary file (2.29 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/midi_utils.cpython-310.pyc
ADDED
|
Binary file (21.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/notes_encoder.cpython-310.pyc
ADDED
|
Binary file (2.17 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/__pycache__/pipeline_spectrogram_diffusion.cpython-310.pyc
ADDED
|
Binary file (6.2 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The Music Spectrogram Diffusion Authors.
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
from transformers.modeling_utils import ModuleUtilsMixin
|
| 19 |
+
from transformers.models.t5.modeling_t5 import (
|
| 20 |
+
T5Block,
|
| 21 |
+
T5Config,
|
| 22 |
+
T5LayerNorm,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from ....configuration_utils import ConfigMixin, register_to_config
|
| 26 |
+
from ....models import ModelMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SpectrogramContEncoder(ModelMixin, ConfigMixin, ModuleUtilsMixin):
|
| 30 |
+
@register_to_config
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
input_dims: int,
|
| 34 |
+
targets_context_length: int,
|
| 35 |
+
d_model: int,
|
| 36 |
+
dropout_rate: float,
|
| 37 |
+
num_layers: int,
|
| 38 |
+
num_heads: int,
|
| 39 |
+
d_kv: int,
|
| 40 |
+
d_ff: int,
|
| 41 |
+
feed_forward_proj: str,
|
| 42 |
+
is_decoder: bool = False,
|
| 43 |
+
):
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
self.input_proj = nn.Linear(input_dims, d_model, bias=False)
|
| 47 |
+
|
| 48 |
+
self.position_encoding = nn.Embedding(targets_context_length, d_model)
|
| 49 |
+
self.position_encoding.weight.requires_grad = False
|
| 50 |
+
|
| 51 |
+
self.dropout_pre = nn.Dropout(p=dropout_rate)
|
| 52 |
+
|
| 53 |
+
t5config = T5Config(
|
| 54 |
+
d_model=d_model,
|
| 55 |
+
num_heads=num_heads,
|
| 56 |
+
d_kv=d_kv,
|
| 57 |
+
d_ff=d_ff,
|
| 58 |
+
feed_forward_proj=feed_forward_proj,
|
| 59 |
+
dropout_rate=dropout_rate,
|
| 60 |
+
is_decoder=is_decoder,
|
| 61 |
+
is_encoder_decoder=False,
|
| 62 |
+
)
|
| 63 |
+
self.encoders = nn.ModuleList()
|
| 64 |
+
for lyr_num in range(num_layers):
|
| 65 |
+
lyr = T5Block(t5config)
|
| 66 |
+
self.encoders.append(lyr)
|
| 67 |
+
|
| 68 |
+
self.layer_norm = T5LayerNorm(d_model)
|
| 69 |
+
self.dropout_post = nn.Dropout(p=dropout_rate)
|
| 70 |
+
|
| 71 |
+
def forward(self, encoder_inputs, encoder_inputs_mask):
|
| 72 |
+
x = self.input_proj(encoder_inputs)
|
| 73 |
+
|
| 74 |
+
# terminal relative positional encodings
|
| 75 |
+
max_positions = encoder_inputs.shape[1]
|
| 76 |
+
input_positions = torch.arange(max_positions, device=encoder_inputs.device)
|
| 77 |
+
|
| 78 |
+
seq_lens = encoder_inputs_mask.sum(-1)
|
| 79 |
+
input_positions = torch.roll(input_positions.unsqueeze(0), tuple(seq_lens.tolist()), dims=0)
|
| 80 |
+
x += self.position_encoding(input_positions)
|
| 81 |
+
|
| 82 |
+
x = self.dropout_pre(x)
|
| 83 |
+
|
| 84 |
+
# inverted the attention mask
|
| 85 |
+
input_shape = encoder_inputs.size()
|
| 86 |
+
extended_attention_mask = self.get_extended_attention_mask(encoder_inputs_mask, input_shape)
|
| 87 |
+
|
| 88 |
+
for lyr in self.encoders:
|
| 89 |
+
x = lyr(x, extended_attention_mask)[0]
|
| 90 |
+
x = self.layer_norm(x)
|
| 91 |
+
|
| 92 |
+
return self.dropout_post(x), encoder_inputs_mask
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The Music Spectrogram Diffusion Authors.
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import dataclasses
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from typing import Any, Callable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
|
| 25 |
+
from ....utils import is_note_seq_available
|
| 26 |
+
from .pipeline_spectrogram_diffusion import TARGET_FEATURE_LENGTH
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_note_seq_available():
|
| 30 |
+
import note_seq
|
| 31 |
+
else:
|
| 32 |
+
raise ImportError("Please install note-seq via `pip install note-seq`")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
INPUT_FEATURE_LENGTH = 2048
|
| 36 |
+
|
| 37 |
+
SAMPLE_RATE = 16000
|
| 38 |
+
HOP_SIZE = 320
|
| 39 |
+
FRAME_RATE = int(SAMPLE_RATE // HOP_SIZE)
|
| 40 |
+
|
| 41 |
+
DEFAULT_STEPS_PER_SECOND = 100
|
| 42 |
+
DEFAULT_MAX_SHIFT_SECONDS = 10
|
| 43 |
+
DEFAULT_NUM_VELOCITY_BINS = 1
|
| 44 |
+
|
| 45 |
+
SLAKH_CLASS_PROGRAMS = {
|
| 46 |
+
"Acoustic Piano": 0,
|
| 47 |
+
"Electric Piano": 4,
|
| 48 |
+
"Chromatic Percussion": 8,
|
| 49 |
+
"Organ": 16,
|
| 50 |
+
"Acoustic Guitar": 24,
|
| 51 |
+
"Clean Electric Guitar": 26,
|
| 52 |
+
"Distorted Electric Guitar": 29,
|
| 53 |
+
"Acoustic Bass": 32,
|
| 54 |
+
"Electric Bass": 33,
|
| 55 |
+
"Violin": 40,
|
| 56 |
+
"Viola": 41,
|
| 57 |
+
"Cello": 42,
|
| 58 |
+
"Contrabass": 43,
|
| 59 |
+
"Orchestral Harp": 46,
|
| 60 |
+
"Timpani": 47,
|
| 61 |
+
"String Ensemble": 48,
|
| 62 |
+
"Synth Strings": 50,
|
| 63 |
+
"Choir and Voice": 52,
|
| 64 |
+
"Orchestral Hit": 55,
|
| 65 |
+
"Trumpet": 56,
|
| 66 |
+
"Trombone": 57,
|
| 67 |
+
"Tuba": 58,
|
| 68 |
+
"French Horn": 60,
|
| 69 |
+
"Brass Section": 61,
|
| 70 |
+
"Soprano/Alto Sax": 64,
|
| 71 |
+
"Tenor Sax": 66,
|
| 72 |
+
"Baritone Sax": 67,
|
| 73 |
+
"Oboe": 68,
|
| 74 |
+
"English Horn": 69,
|
| 75 |
+
"Bassoon": 70,
|
| 76 |
+
"Clarinet": 71,
|
| 77 |
+
"Pipe": 73,
|
| 78 |
+
"Synth Lead": 80,
|
| 79 |
+
"Synth Pad": 88,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclasses.dataclass
|
| 84 |
+
class NoteRepresentationConfig:
|
| 85 |
+
"""Configuration note representations."""
|
| 86 |
+
|
| 87 |
+
onsets_only: bool
|
| 88 |
+
include_ties: bool
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclasses.dataclass
|
| 92 |
+
class NoteEventData:
|
| 93 |
+
pitch: int
|
| 94 |
+
velocity: Optional[int] = None
|
| 95 |
+
program: Optional[int] = None
|
| 96 |
+
is_drum: Optional[bool] = None
|
| 97 |
+
instrument: Optional[int] = None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dataclasses.dataclass
|
| 101 |
+
class NoteEncodingState:
|
| 102 |
+
"""Encoding state for note transcription, keeping track of active pitches."""
|
| 103 |
+
|
| 104 |
+
# velocity bin for active pitches and programs
|
| 105 |
+
active_pitches: MutableMapping[Tuple[int, int], int] = dataclasses.field(default_factory=dict)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@dataclasses.dataclass
|
| 109 |
+
class EventRange:
|
| 110 |
+
type: str
|
| 111 |
+
min_value: int
|
| 112 |
+
max_value: int
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclasses.dataclass
|
| 116 |
+
class Event:
|
| 117 |
+
type: str
|
| 118 |
+
value: int
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Tokenizer:
|
| 122 |
+
def __init__(self, regular_ids: int):
|
| 123 |
+
# The special tokens: 0=PAD, 1=EOS, and 2=UNK
|
| 124 |
+
self._num_special_tokens = 3
|
| 125 |
+
self._num_regular_tokens = regular_ids
|
| 126 |
+
|
| 127 |
+
def encode(self, token_ids):
|
| 128 |
+
encoded = []
|
| 129 |
+
for token_id in token_ids:
|
| 130 |
+
if not 0 <= token_id < self._num_regular_tokens:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"token_id {token_id} does not fall within valid range of [0, {self._num_regular_tokens})"
|
| 133 |
+
)
|
| 134 |
+
encoded.append(token_id + self._num_special_tokens)
|
| 135 |
+
|
| 136 |
+
# Add EOS token
|
| 137 |
+
encoded.append(1)
|
| 138 |
+
|
| 139 |
+
# Pad to till INPUT_FEATURE_LENGTH
|
| 140 |
+
encoded = encoded + [0] * (INPUT_FEATURE_LENGTH - len(encoded))
|
| 141 |
+
|
| 142 |
+
return encoded
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Codec:
|
| 146 |
+
"""Encode and decode events.
|
| 147 |
+
|
| 148 |
+
Useful for declaring what certain ranges of a vocabulary should be used for. This is intended to be used from
|
| 149 |
+
Python before encoding or after decoding with GenericTokenVocabulary. This class is more lightweight and does not
|
| 150 |
+
include things like EOS or UNK token handling.
|
| 151 |
+
|
| 152 |
+
To ensure that 'shift' events are always the first block of the vocab and start at 0, that event type is required
|
| 153 |
+
and specified separately.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
def __init__(self, max_shift_steps: int, steps_per_second: float, event_ranges: List[EventRange]):
|
| 157 |
+
"""Define Codec.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
max_shift_steps: Maximum number of shift steps that can be encoded.
|
| 161 |
+
steps_per_second: Shift steps will be interpreted as having a duration of
|
| 162 |
+
1 / steps_per_second.
|
| 163 |
+
event_ranges: Other supported event types and their ranges.
|
| 164 |
+
"""
|
| 165 |
+
self.steps_per_second = steps_per_second
|
| 166 |
+
self._shift_range = EventRange(type="shift", min_value=0, max_value=max_shift_steps)
|
| 167 |
+
self._event_ranges = [self._shift_range] + event_ranges
|
| 168 |
+
# Ensure all event types have unique names.
|
| 169 |
+
assert len(self._event_ranges) == len({er.type for er in self._event_ranges})
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def num_classes(self) -> int:
|
| 173 |
+
return sum(er.max_value - er.min_value + 1 for er in self._event_ranges)
|
| 174 |
+
|
| 175 |
+
# The next couple methods are simplified special case methods just for shift
|
| 176 |
+
# events that are intended to be used from within autograph functions.
|
| 177 |
+
|
| 178 |
+
def is_shift_event_index(self, index: int) -> bool:
|
| 179 |
+
return (self._shift_range.min_value <= index) and (index <= self._shift_range.max_value)
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def max_shift_steps(self) -> int:
|
| 183 |
+
return self._shift_range.max_value
|
| 184 |
+
|
| 185 |
+
def encode_event(self, event: Event) -> int:
|
| 186 |
+
"""Encode an event to an index."""
|
| 187 |
+
offset = 0
|
| 188 |
+
for er in self._event_ranges:
|
| 189 |
+
if event.type == er.type:
|
| 190 |
+
if not er.min_value <= event.value <= er.max_value:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
f"Event value {event.value} is not within valid range "
|
| 193 |
+
f"[{er.min_value}, {er.max_value}] for type {event.type}"
|
| 194 |
+
)
|
| 195 |
+
return offset + event.value - er.min_value
|
| 196 |
+
offset += er.max_value - er.min_value + 1
|
| 197 |
+
|
| 198 |
+
raise ValueError(f"Unknown event type: {event.type}")
|
| 199 |
+
|
| 200 |
+
def event_type_range(self, event_type: str) -> Tuple[int, int]:
|
| 201 |
+
"""Return [min_id, max_id] for an event type."""
|
| 202 |
+
offset = 0
|
| 203 |
+
for er in self._event_ranges:
|
| 204 |
+
if event_type == er.type:
|
| 205 |
+
return offset, offset + (er.max_value - er.min_value)
|
| 206 |
+
offset += er.max_value - er.min_value + 1
|
| 207 |
+
|
| 208 |
+
raise ValueError(f"Unknown event type: {event_type}")
|
| 209 |
+
|
| 210 |
+
def decode_event_index(self, index: int) -> Event:
|
| 211 |
+
"""Decode an event index to an Event."""
|
| 212 |
+
offset = 0
|
| 213 |
+
for er in self._event_ranges:
|
| 214 |
+
if offset <= index <= offset + er.max_value - er.min_value:
|
| 215 |
+
return Event(type=er.type, value=er.min_value + index - offset)
|
| 216 |
+
offset += er.max_value - er.min_value + 1
|
| 217 |
+
|
| 218 |
+
raise ValueError(f"Unknown event index: {index}")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@dataclasses.dataclass
|
| 222 |
+
class ProgramGranularity:
|
| 223 |
+
# both tokens_map_fn and program_map_fn should be idempotent
|
| 224 |
+
tokens_map_fn: Callable[[Sequence[int], Codec], Sequence[int]]
|
| 225 |
+
program_map_fn: Callable[[int], int]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def drop_programs(tokens, codec: Codec):
|
| 229 |
+
"""Drops program change events from a token sequence."""
|
| 230 |
+
min_program_id, max_program_id = codec.event_type_range("program")
|
| 231 |
+
return tokens[(tokens < min_program_id) | (tokens > max_program_id)]
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def programs_to_midi_classes(tokens, codec):
|
| 235 |
+
"""Modifies program events to be the first program in the MIDI class."""
|
| 236 |
+
min_program_id, max_program_id = codec.event_type_range("program")
|
| 237 |
+
is_program = (tokens >= min_program_id) & (tokens <= max_program_id)
|
| 238 |
+
return np.where(is_program, min_program_id + 8 * ((tokens - min_program_id) // 8), tokens)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
PROGRAM_GRANULARITIES = {
|
| 242 |
+
# "flat" granularity; drop program change tokens and set NoteSequence
|
| 243 |
+
# programs to zero
|
| 244 |
+
"flat": ProgramGranularity(tokens_map_fn=drop_programs, program_map_fn=lambda program: 0),
|
| 245 |
+
# map each program to the first program in its MIDI class
|
| 246 |
+
"midi_class": ProgramGranularity(
|
| 247 |
+
tokens_map_fn=programs_to_midi_classes, program_map_fn=lambda program: 8 * (program // 8)
|
| 248 |
+
),
|
| 249 |
+
# leave programs as is
|
| 250 |
+
"full": ProgramGranularity(tokens_map_fn=lambda tokens, codec: tokens, program_map_fn=lambda program: program),
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def frame(signal, frame_length, frame_step, pad_end=False, pad_value=0, axis=-1):
|
| 255 |
+
"""
|
| 256 |
+
equivalent of tf.signal.frame
|
| 257 |
+
"""
|
| 258 |
+
signal_length = signal.shape[axis]
|
| 259 |
+
if pad_end:
|
| 260 |
+
frames_overlap = frame_length - frame_step
|
| 261 |
+
rest_samples = np.abs(signal_length - frames_overlap) % np.abs(frame_length - frames_overlap)
|
| 262 |
+
pad_size = int(frame_length - rest_samples)
|
| 263 |
+
|
| 264 |
+
if pad_size != 0:
|
| 265 |
+
pad_axis = [0] * signal.ndim
|
| 266 |
+
pad_axis[axis] = pad_size
|
| 267 |
+
signal = F.pad(signal, pad_axis, "constant", pad_value)
|
| 268 |
+
frames = signal.unfold(axis, frame_length, frame_step)
|
| 269 |
+
return frames
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def program_to_slakh_program(program):
|
| 273 |
+
# this is done very hackily, probably should use a custom mapping
|
| 274 |
+
for slakh_program in sorted(SLAKH_CLASS_PROGRAMS.values(), reverse=True):
|
| 275 |
+
if program >= slakh_program:
|
| 276 |
+
return slakh_program
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def audio_to_frames(
|
| 280 |
+
samples,
|
| 281 |
+
hop_size: int,
|
| 282 |
+
frame_rate: int,
|
| 283 |
+
) -> Tuple[Sequence[Sequence[int]], torch.Tensor]:
|
| 284 |
+
"""Convert audio samples to non-overlapping frames and frame times."""
|
| 285 |
+
frame_size = hop_size
|
| 286 |
+
samples = np.pad(samples, [0, frame_size - len(samples) % frame_size], mode="constant")
|
| 287 |
+
|
| 288 |
+
# Split audio into frames.
|
| 289 |
+
frames = frame(
|
| 290 |
+
torch.Tensor(samples).unsqueeze(0),
|
| 291 |
+
frame_length=frame_size,
|
| 292 |
+
frame_step=frame_size,
|
| 293 |
+
pad_end=False, # TODO check why its off by 1 here when True
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
num_frames = len(samples) // frame_size
|
| 297 |
+
|
| 298 |
+
times = np.arange(num_frames) / frame_rate
|
| 299 |
+
return frames, times
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def note_sequence_to_onsets_and_offsets_and_programs(
|
| 303 |
+
ns: note_seq.NoteSequence,
|
| 304 |
+
) -> Tuple[Sequence[float], Sequence[NoteEventData]]:
|
| 305 |
+
"""Extract onset & offset times and pitches & programs from a NoteSequence.
|
| 306 |
+
|
| 307 |
+
The onset & offset times will not necessarily be in sorted order.
|
| 308 |
+
|
| 309 |
+
Args:
|
| 310 |
+
ns: NoteSequence from which to extract onsets and offsets.
|
| 311 |
+
|
| 312 |
+
Returns:
|
| 313 |
+
times: A list of note onset and offset times. values: A list of NoteEventData objects where velocity is zero for
|
| 314 |
+
note
|
| 315 |
+
offsets.
|
| 316 |
+
"""
|
| 317 |
+
# Sort by program and pitch and put offsets before onsets as a tiebreaker for
|
| 318 |
+
# subsequent stable sort.
|
| 319 |
+
notes = sorted(ns.notes, key=lambda note: (note.is_drum, note.program, note.pitch))
|
| 320 |
+
times = [note.end_time for note in notes if not note.is_drum] + [note.start_time for note in notes]
|
| 321 |
+
values = [
|
| 322 |
+
NoteEventData(pitch=note.pitch, velocity=0, program=note.program, is_drum=False)
|
| 323 |
+
for note in notes
|
| 324 |
+
if not note.is_drum
|
| 325 |
+
] + [
|
| 326 |
+
NoteEventData(pitch=note.pitch, velocity=note.velocity, program=note.program, is_drum=note.is_drum)
|
| 327 |
+
for note in notes
|
| 328 |
+
]
|
| 329 |
+
return times, values
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def num_velocity_bins_from_codec(codec: Codec):
|
| 333 |
+
"""Get number of velocity bins from event codec."""
|
| 334 |
+
lo, hi = codec.event_type_range("velocity")
|
| 335 |
+
return hi - lo
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# segment an array into segments of length n
|
| 339 |
+
def segment(a, n):
|
| 340 |
+
return [a[i : i + n] for i in range(0, len(a), n)]
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def velocity_to_bin(velocity, num_velocity_bins):
|
| 344 |
+
if velocity == 0:
|
| 345 |
+
return 0
|
| 346 |
+
else:
|
| 347 |
+
return math.ceil(num_velocity_bins * velocity / note_seq.MAX_MIDI_VELOCITY)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def note_event_data_to_events(
|
| 351 |
+
state: Optional[NoteEncodingState],
|
| 352 |
+
value: NoteEventData,
|
| 353 |
+
codec: Codec,
|
| 354 |
+
) -> Sequence[Event]:
|
| 355 |
+
"""Convert note event data to a sequence of events."""
|
| 356 |
+
if value.velocity is None:
|
| 357 |
+
# onsets only, no program or velocity
|
| 358 |
+
return [Event("pitch", value.pitch)]
|
| 359 |
+
else:
|
| 360 |
+
num_velocity_bins = num_velocity_bins_from_codec(codec)
|
| 361 |
+
velocity_bin = velocity_to_bin(value.velocity, num_velocity_bins)
|
| 362 |
+
if value.program is None:
|
| 363 |
+
# onsets + offsets + velocities only, no programs
|
| 364 |
+
if state is not None:
|
| 365 |
+
state.active_pitches[(value.pitch, 0)] = velocity_bin
|
| 366 |
+
return [Event("velocity", velocity_bin), Event("pitch", value.pitch)]
|
| 367 |
+
else:
|
| 368 |
+
if value.is_drum:
|
| 369 |
+
# drum events use a separate vocabulary
|
| 370 |
+
return [Event("velocity", velocity_bin), Event("drum", value.pitch)]
|
| 371 |
+
else:
|
| 372 |
+
# program + velocity + pitch
|
| 373 |
+
if state is not None:
|
| 374 |
+
state.active_pitches[(value.pitch, value.program)] = velocity_bin
|
| 375 |
+
return [
|
| 376 |
+
Event("program", value.program),
|
| 377 |
+
Event("velocity", velocity_bin),
|
| 378 |
+
Event("pitch", value.pitch),
|
| 379 |
+
]
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def note_encoding_state_to_events(state: NoteEncodingState) -> Sequence[Event]:
|
| 383 |
+
"""Output program and pitch events for active notes plus a final tie event."""
|
| 384 |
+
events = []
|
| 385 |
+
for pitch, program in sorted(state.active_pitches.keys(), key=lambda k: k[::-1]):
|
| 386 |
+
if state.active_pitches[(pitch, program)]:
|
| 387 |
+
events += [Event("program", program), Event("pitch", pitch)]
|
| 388 |
+
events.append(Event("tie", 0))
|
| 389 |
+
return events
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def encode_and_index_events(
|
| 393 |
+
state, event_times, event_values, codec, frame_times, encode_event_fn, encoding_state_to_events_fn=None
|
| 394 |
+
):
|
| 395 |
+
"""Encode a sequence of timed events and index to audio frame times.
|
| 396 |
+
|
| 397 |
+
Encodes time shifts as repeated single step shifts for later run length encoding.
|
| 398 |
+
|
| 399 |
+
Optionally, also encodes a sequence of "state events", keeping track of the current encoding state at each audio
|
| 400 |
+
frame. This can be used e.g. to prepend events representing the current state to a targets segment.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
state: Initial event encoding state.
|
| 404 |
+
event_times: Sequence of event times.
|
| 405 |
+
event_values: Sequence of event values.
|
| 406 |
+
encode_event_fn: Function that transforms event value into a sequence of one
|
| 407 |
+
or more Event objects.
|
| 408 |
+
codec: An Codec object that maps Event objects to indices.
|
| 409 |
+
frame_times: Time for every audio frame.
|
| 410 |
+
encoding_state_to_events_fn: Function that transforms encoding state into a
|
| 411 |
+
sequence of one or more Event objects.
|
| 412 |
+
|
| 413 |
+
Returns:
|
| 414 |
+
events: Encoded events and shifts. event_start_indices: Corresponding start event index for every audio frame.
|
| 415 |
+
Note: one event can correspond to multiple audio indices due to sampling rate differences. This makes
|
| 416 |
+
splitting sequences tricky because the same event can appear at the end of one sequence and the beginning of
|
| 417 |
+
another.
|
| 418 |
+
event_end_indices: Corresponding end event index for every audio frame. Used
|
| 419 |
+
to ensure when slicing that one chunk ends where the next begins. Should always be true that
|
| 420 |
+
event_end_indices[i] = event_start_indices[i + 1].
|
| 421 |
+
state_events: Encoded "state" events representing the encoding state before
|
| 422 |
+
each event.
|
| 423 |
+
state_event_indices: Corresponding state event index for every audio frame.
|
| 424 |
+
"""
|
| 425 |
+
indices = np.argsort(event_times, kind="stable")
|
| 426 |
+
event_steps = [round(event_times[i] * codec.steps_per_second) for i in indices]
|
| 427 |
+
event_values = [event_values[i] for i in indices]
|
| 428 |
+
|
| 429 |
+
events = []
|
| 430 |
+
state_events = []
|
| 431 |
+
event_start_indices = []
|
| 432 |
+
state_event_indices = []
|
| 433 |
+
|
| 434 |
+
cur_step = 0
|
| 435 |
+
cur_event_idx = 0
|
| 436 |
+
cur_state_event_idx = 0
|
| 437 |
+
|
| 438 |
+
def fill_event_start_indices_to_cur_step():
|
| 439 |
+
while (
|
| 440 |
+
len(event_start_indices) < len(frame_times)
|
| 441 |
+
and frame_times[len(event_start_indices)] < cur_step / codec.steps_per_second
|
| 442 |
+
):
|
| 443 |
+
event_start_indices.append(cur_event_idx)
|
| 444 |
+
state_event_indices.append(cur_state_event_idx)
|
| 445 |
+
|
| 446 |
+
for event_step, event_value in zip(event_steps, event_values):
|
| 447 |
+
while event_step > cur_step:
|
| 448 |
+
events.append(codec.encode_event(Event(type="shift", value=1)))
|
| 449 |
+
cur_step += 1
|
| 450 |
+
fill_event_start_indices_to_cur_step()
|
| 451 |
+
cur_event_idx = len(events)
|
| 452 |
+
cur_state_event_idx = len(state_events)
|
| 453 |
+
if encoding_state_to_events_fn:
|
| 454 |
+
# Dump state to state events *before* processing the next event, because
|
| 455 |
+
# we want to capture the state prior to the occurrence of the event.
|
| 456 |
+
for e in encoding_state_to_events_fn(state):
|
| 457 |
+
state_events.append(codec.encode_event(e))
|
| 458 |
+
|
| 459 |
+
for e in encode_event_fn(state, event_value, codec):
|
| 460 |
+
events.append(codec.encode_event(e))
|
| 461 |
+
|
| 462 |
+
# After the last event, continue filling out the event_start_indices array.
|
| 463 |
+
# The inequality is not strict because if our current step lines up exactly
|
| 464 |
+
# with (the start of) an audio frame, we need to add an additional shift event
|
| 465 |
+
# to "cover" that frame.
|
| 466 |
+
while cur_step / codec.steps_per_second <= frame_times[-1]:
|
| 467 |
+
events.append(codec.encode_event(Event(type="shift", value=1)))
|
| 468 |
+
cur_step += 1
|
| 469 |
+
fill_event_start_indices_to_cur_step()
|
| 470 |
+
cur_event_idx = len(events)
|
| 471 |
+
|
| 472 |
+
# Now fill in event_end_indices. We need this extra array to make sure that
|
| 473 |
+
# when we slice events, each slice ends exactly where the subsequent slice
|
| 474 |
+
# begins.
|
| 475 |
+
event_end_indices = event_start_indices[1:] + [len(events)]
|
| 476 |
+
|
| 477 |
+
events = np.array(events).astype(np.int32)
|
| 478 |
+
state_events = np.array(state_events).astype(np.int32)
|
| 479 |
+
event_start_indices = segment(np.array(event_start_indices).astype(np.int32), TARGET_FEATURE_LENGTH)
|
| 480 |
+
event_end_indices = segment(np.array(event_end_indices).astype(np.int32), TARGET_FEATURE_LENGTH)
|
| 481 |
+
state_event_indices = segment(np.array(state_event_indices).astype(np.int32), TARGET_FEATURE_LENGTH)
|
| 482 |
+
|
| 483 |
+
outputs = []
|
| 484 |
+
for start_indices, end_indices, event_indices in zip(event_start_indices, event_end_indices, state_event_indices):
|
| 485 |
+
outputs.append(
|
| 486 |
+
{
|
| 487 |
+
"inputs": events,
|
| 488 |
+
"event_start_indices": start_indices,
|
| 489 |
+
"event_end_indices": end_indices,
|
| 490 |
+
"state_events": state_events,
|
| 491 |
+
"state_event_indices": event_indices,
|
| 492 |
+
}
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
return outputs
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def extract_sequence_with_indices(features, state_events_end_token=None, feature_key="inputs"):
|
| 499 |
+
"""Extract target sequence corresponding to audio token segment."""
|
| 500 |
+
features = features.copy()
|
| 501 |
+
start_idx = features["event_start_indices"][0]
|
| 502 |
+
end_idx = features["event_end_indices"][-1]
|
| 503 |
+
|
| 504 |
+
features[feature_key] = features[feature_key][start_idx:end_idx]
|
| 505 |
+
|
| 506 |
+
if state_events_end_token is not None:
|
| 507 |
+
# Extract the state events corresponding to the audio start token, and
|
| 508 |
+
# prepend them to the targets array.
|
| 509 |
+
state_event_start_idx = features["state_event_indices"][0]
|
| 510 |
+
state_event_end_idx = state_event_start_idx + 1
|
| 511 |
+
while features["state_events"][state_event_end_idx - 1] != state_events_end_token:
|
| 512 |
+
state_event_end_idx += 1
|
| 513 |
+
features[feature_key] = np.concatenate(
|
| 514 |
+
[
|
| 515 |
+
features["state_events"][state_event_start_idx:state_event_end_idx],
|
| 516 |
+
features[feature_key],
|
| 517 |
+
],
|
| 518 |
+
axis=0,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
return features
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def map_midi_programs(
|
| 525 |
+
feature, codec: Codec, granularity_type: str = "full", feature_key: str = "inputs"
|
| 526 |
+
) -> Mapping[str, Any]:
|
| 527 |
+
"""Apply MIDI program map to token sequences."""
|
| 528 |
+
granularity = PROGRAM_GRANULARITIES[granularity_type]
|
| 529 |
+
|
| 530 |
+
feature[feature_key] = granularity.tokens_map_fn(feature[feature_key], codec)
|
| 531 |
+
return feature
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def run_length_encode_shifts_fn(
|
| 535 |
+
features,
|
| 536 |
+
codec: Codec,
|
| 537 |
+
feature_key: str = "inputs",
|
| 538 |
+
state_change_event_types: Sequence[str] = (),
|
| 539 |
+
) -> Callable[[Mapping[str, Any]], Mapping[str, Any]]:
|
| 540 |
+
"""Return a function that run-length encodes shifts for a given codec.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
codec: The Codec to use for shift events.
|
| 544 |
+
feature_key: The feature key for which to run-length encode shifts.
|
| 545 |
+
state_change_event_types: A list of event types that represent state
|
| 546 |
+
changes; tokens corresponding to these event types will be interpreted as state changes and redundant ones
|
| 547 |
+
will be removed.
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
A preprocessing function that run-length encodes single-step shifts.
|
| 551 |
+
"""
|
| 552 |
+
state_change_event_ranges = [codec.event_type_range(event_type) for event_type in state_change_event_types]
|
| 553 |
+
|
| 554 |
+
def run_length_encode_shifts(features: MutableMapping[str, Any]) -> Mapping[str, Any]:
|
| 555 |
+
"""Combine leading/interior shifts, trim trailing shifts.
|
| 556 |
+
|
| 557 |
+
Args:
|
| 558 |
+
features: Dict of features to process.
|
| 559 |
+
|
| 560 |
+
Returns:
|
| 561 |
+
A dict of features.
|
| 562 |
+
"""
|
| 563 |
+
events = features[feature_key]
|
| 564 |
+
|
| 565 |
+
shift_steps = 0
|
| 566 |
+
total_shift_steps = 0
|
| 567 |
+
output = np.array([], dtype=np.int32)
|
| 568 |
+
|
| 569 |
+
current_state = np.zeros(len(state_change_event_ranges), dtype=np.int32)
|
| 570 |
+
|
| 571 |
+
for event in events:
|
| 572 |
+
if codec.is_shift_event_index(event):
|
| 573 |
+
shift_steps += 1
|
| 574 |
+
total_shift_steps += 1
|
| 575 |
+
|
| 576 |
+
else:
|
| 577 |
+
# If this event is a state change and has the same value as the current
|
| 578 |
+
# state, we can skip it entirely.
|
| 579 |
+
is_redundant = False
|
| 580 |
+
for i, (min_index, max_index) in enumerate(state_change_event_ranges):
|
| 581 |
+
if (min_index <= event) and (event <= max_index):
|
| 582 |
+
if current_state[i] == event:
|
| 583 |
+
is_redundant = True
|
| 584 |
+
current_state[i] = event
|
| 585 |
+
if is_redundant:
|
| 586 |
+
continue
|
| 587 |
+
|
| 588 |
+
# Once we've reached a non-shift event, RLE all previous shift events
|
| 589 |
+
# before outputting the non-shift event.
|
| 590 |
+
if shift_steps > 0:
|
| 591 |
+
shift_steps = total_shift_steps
|
| 592 |
+
while shift_steps > 0:
|
| 593 |
+
output_steps = np.minimum(codec.max_shift_steps, shift_steps)
|
| 594 |
+
output = np.concatenate([output, [output_steps]], axis=0)
|
| 595 |
+
shift_steps -= output_steps
|
| 596 |
+
output = np.concatenate([output, [event]], axis=0)
|
| 597 |
+
|
| 598 |
+
features[feature_key] = output
|
| 599 |
+
return features
|
| 600 |
+
|
| 601 |
+
return run_length_encode_shifts(features)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def note_representation_processor_chain(features, codec: Codec, note_representation_config: NoteRepresentationConfig):
|
| 605 |
+
tie_token = codec.encode_event(Event("tie", 0))
|
| 606 |
+
state_events_end_token = tie_token if note_representation_config.include_ties else None
|
| 607 |
+
|
| 608 |
+
features = extract_sequence_with_indices(
|
| 609 |
+
features, state_events_end_token=state_events_end_token, feature_key="inputs"
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
features = map_midi_programs(features, codec)
|
| 613 |
+
|
| 614 |
+
features = run_length_encode_shifts_fn(features, codec, state_change_event_types=["velocity", "program"])
|
| 615 |
+
|
| 616 |
+
return features
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class MidiProcessor:
|
| 620 |
+
def __init__(self):
|
| 621 |
+
self.codec = Codec(
|
| 622 |
+
max_shift_steps=DEFAULT_MAX_SHIFT_SECONDS * DEFAULT_STEPS_PER_SECOND,
|
| 623 |
+
steps_per_second=DEFAULT_STEPS_PER_SECOND,
|
| 624 |
+
event_ranges=[
|
| 625 |
+
EventRange("pitch", note_seq.MIN_MIDI_PITCH, note_seq.MAX_MIDI_PITCH),
|
| 626 |
+
EventRange("velocity", 0, DEFAULT_NUM_VELOCITY_BINS),
|
| 627 |
+
EventRange("tie", 0, 0),
|
| 628 |
+
EventRange("program", note_seq.MIN_MIDI_PROGRAM, note_seq.MAX_MIDI_PROGRAM),
|
| 629 |
+
EventRange("drum", note_seq.MIN_MIDI_PITCH, note_seq.MAX_MIDI_PITCH),
|
| 630 |
+
],
|
| 631 |
+
)
|
| 632 |
+
self.tokenizer = Tokenizer(self.codec.num_classes)
|
| 633 |
+
self.note_representation_config = NoteRepresentationConfig(onsets_only=False, include_ties=True)
|
| 634 |
+
|
| 635 |
+
def __call__(self, midi: Union[bytes, os.PathLike, str]):
|
| 636 |
+
if not isinstance(midi, bytes):
|
| 637 |
+
with open(midi, "rb") as f:
|
| 638 |
+
midi = f.read()
|
| 639 |
+
|
| 640 |
+
ns = note_seq.midi_to_note_sequence(midi)
|
| 641 |
+
ns_sus = note_seq.apply_sustain_control_changes(ns)
|
| 642 |
+
|
| 643 |
+
for note in ns_sus.notes:
|
| 644 |
+
if not note.is_drum:
|
| 645 |
+
note.program = program_to_slakh_program(note.program)
|
| 646 |
+
|
| 647 |
+
samples = np.zeros(int(ns_sus.total_time * SAMPLE_RATE))
|
| 648 |
+
|
| 649 |
+
_, frame_times = audio_to_frames(samples, HOP_SIZE, FRAME_RATE)
|
| 650 |
+
times, values = note_sequence_to_onsets_and_offsets_and_programs(ns_sus)
|
| 651 |
+
|
| 652 |
+
events = encode_and_index_events(
|
| 653 |
+
state=NoteEncodingState(),
|
| 654 |
+
event_times=times,
|
| 655 |
+
event_values=values,
|
| 656 |
+
frame_times=frame_times,
|
| 657 |
+
codec=self.codec,
|
| 658 |
+
encode_event_fn=note_event_data_to_events,
|
| 659 |
+
encoding_state_to_events_fn=note_encoding_state_to_events,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
events = [
|
| 663 |
+
note_representation_processor_chain(event, self.codec, self.note_representation_config) for event in events
|
| 664 |
+
]
|
| 665 |
+
input_tokens = [self.tokenizer.encode(event["inputs"]) for event in events]
|
| 666 |
+
|
| 667 |
+
return input_tokens
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The Music Spectrogram Diffusion Authors.
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
from transformers.modeling_utils import ModuleUtilsMixin
|
| 19 |
+
from transformers.models.t5.modeling_t5 import T5Block, T5Config, T5LayerNorm
|
| 20 |
+
|
| 21 |
+
from ....configuration_utils import ConfigMixin, register_to_config
|
| 22 |
+
from ....models import ModelMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SpectrogramNotesEncoder(ModelMixin, ConfigMixin, ModuleUtilsMixin):
|
| 26 |
+
@register_to_config
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
max_length: int,
|
| 30 |
+
vocab_size: int,
|
| 31 |
+
d_model: int,
|
| 32 |
+
dropout_rate: float,
|
| 33 |
+
num_layers: int,
|
| 34 |
+
num_heads: int,
|
| 35 |
+
d_kv: int,
|
| 36 |
+
d_ff: int,
|
| 37 |
+
feed_forward_proj: str,
|
| 38 |
+
is_decoder: bool = False,
|
| 39 |
+
):
|
| 40 |
+
super().__init__()
|
| 41 |
+
|
| 42 |
+
self.token_embedder = nn.Embedding(vocab_size, d_model)
|
| 43 |
+
|
| 44 |
+
self.position_encoding = nn.Embedding(max_length, d_model)
|
| 45 |
+
self.position_encoding.weight.requires_grad = False
|
| 46 |
+
|
| 47 |
+
self.dropout_pre = nn.Dropout(p=dropout_rate)
|
| 48 |
+
|
| 49 |
+
t5config = T5Config(
|
| 50 |
+
vocab_size=vocab_size,
|
| 51 |
+
d_model=d_model,
|
| 52 |
+
num_heads=num_heads,
|
| 53 |
+
d_kv=d_kv,
|
| 54 |
+
d_ff=d_ff,
|
| 55 |
+
dropout_rate=dropout_rate,
|
| 56 |
+
feed_forward_proj=feed_forward_proj,
|
| 57 |
+
is_decoder=is_decoder,
|
| 58 |
+
is_encoder_decoder=False,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
self.encoders = nn.ModuleList()
|
| 62 |
+
for lyr_num in range(num_layers):
|
| 63 |
+
lyr = T5Block(t5config)
|
| 64 |
+
self.encoders.append(lyr)
|
| 65 |
+
|
| 66 |
+
self.layer_norm = T5LayerNorm(d_model)
|
| 67 |
+
self.dropout_post = nn.Dropout(p=dropout_rate)
|
| 68 |
+
|
| 69 |
+
def forward(self, encoder_input_tokens, encoder_inputs_mask):
|
| 70 |
+
x = self.token_embedder(encoder_input_tokens)
|
| 71 |
+
|
| 72 |
+
seq_length = encoder_input_tokens.shape[1]
|
| 73 |
+
inputs_positions = torch.arange(seq_length, device=encoder_input_tokens.device)
|
| 74 |
+
x += self.position_encoding(inputs_positions)
|
| 75 |
+
|
| 76 |
+
x = self.dropout_pre(x)
|
| 77 |
+
|
| 78 |
+
# inverted the attention mask
|
| 79 |
+
input_shape = encoder_input_tokens.size()
|
| 80 |
+
extended_attention_mask = self.get_extended_attention_mask(encoder_inputs_mask, input_shape)
|
| 81 |
+
|
| 82 |
+
for lyr in self.encoders:
|
| 83 |
+
x = lyr(x, extended_attention_mask)[0]
|
| 84 |
+
x = self.layer_norm(x)
|
| 85 |
+
|
| 86 |
+
return self.dropout_post(x), encoder_inputs_mask
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The Music Spectrogram Diffusion Authors.
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import Any, Callable, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from ....models import T5FilmDecoder
|
| 23 |
+
from ....schedulers import DDPMScheduler
|
| 24 |
+
from ....utils import is_onnx_available, logging
|
| 25 |
+
from ....utils.torch_utils import randn_tensor
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_onnx_available():
|
| 29 |
+
from ...onnx_utils import OnnxRuntimeModel
|
| 30 |
+
|
| 31 |
+
from ...pipeline_utils import AudioPipelineOutput, DiffusionPipeline
|
| 32 |
+
from .continuous_encoder import SpectrogramContEncoder
|
| 33 |
+
from .notes_encoder import SpectrogramNotesEncoder
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 37 |
+
|
| 38 |
+
TARGET_FEATURE_LENGTH = 256
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class SpectrogramDiffusionPipeline(DiffusionPipeline):
|
| 42 |
+
r"""
|
| 43 |
+
Pipeline for unconditional audio generation.
|
| 44 |
+
|
| 45 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 46 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
notes_encoder ([`SpectrogramNotesEncoder`]):
|
| 50 |
+
continuous_encoder ([`SpectrogramContEncoder`]):
|
| 51 |
+
decoder ([`T5FilmDecoder`]):
|
| 52 |
+
A [`T5FilmDecoder`] to denoise the encoded audio latents.
|
| 53 |
+
scheduler ([`DDPMScheduler`]):
|
| 54 |
+
A scheduler to be used in combination with `decoder` to denoise the encoded audio latents.
|
| 55 |
+
melgan ([`OnnxRuntimeModel`]):
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
_optional_components = ["melgan"]
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
notes_encoder: SpectrogramNotesEncoder,
|
| 63 |
+
continuous_encoder: SpectrogramContEncoder,
|
| 64 |
+
decoder: T5FilmDecoder,
|
| 65 |
+
scheduler: DDPMScheduler,
|
| 66 |
+
melgan: OnnxRuntimeModel if is_onnx_available() else Any,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__()
|
| 69 |
+
|
| 70 |
+
# From MELGAN
|
| 71 |
+
self.min_value = math.log(1e-5) # Matches MelGAN training.
|
| 72 |
+
self.max_value = 4.0 # Largest value for most examples
|
| 73 |
+
self.n_dims = 128
|
| 74 |
+
|
| 75 |
+
self.register_modules(
|
| 76 |
+
notes_encoder=notes_encoder,
|
| 77 |
+
continuous_encoder=continuous_encoder,
|
| 78 |
+
decoder=decoder,
|
| 79 |
+
scheduler=scheduler,
|
| 80 |
+
melgan=melgan,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def scale_features(self, features, output_range=(-1.0, 1.0), clip=False):
|
| 84 |
+
"""Linearly scale features to network outputs range."""
|
| 85 |
+
min_out, max_out = output_range
|
| 86 |
+
if clip:
|
| 87 |
+
features = torch.clip(features, self.min_value, self.max_value)
|
| 88 |
+
# Scale to [0, 1].
|
| 89 |
+
zero_one = (features - self.min_value) / (self.max_value - self.min_value)
|
| 90 |
+
# Scale to [min_out, max_out].
|
| 91 |
+
return zero_one * (max_out - min_out) + min_out
|
| 92 |
+
|
| 93 |
+
def scale_to_features(self, outputs, input_range=(-1.0, 1.0), clip=False):
|
| 94 |
+
"""Invert by linearly scaling network outputs to features range."""
|
| 95 |
+
min_out, max_out = input_range
|
| 96 |
+
outputs = torch.clip(outputs, min_out, max_out) if clip else outputs
|
| 97 |
+
# Scale to [0, 1].
|
| 98 |
+
zero_one = (outputs - min_out) / (max_out - min_out)
|
| 99 |
+
# Scale to [self.min_value, self.max_value].
|
| 100 |
+
return zero_one * (self.max_value - self.min_value) + self.min_value
|
| 101 |
+
|
| 102 |
+
def encode(self, input_tokens, continuous_inputs, continuous_mask):
|
| 103 |
+
tokens_mask = input_tokens > 0
|
| 104 |
+
tokens_encoded, tokens_mask = self.notes_encoder(
|
| 105 |
+
encoder_input_tokens=input_tokens, encoder_inputs_mask=tokens_mask
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
continuous_encoded, continuous_mask = self.continuous_encoder(
|
| 109 |
+
encoder_inputs=continuous_inputs, encoder_inputs_mask=continuous_mask
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
|
| 113 |
+
|
| 114 |
+
def decode(self, encodings_and_masks, input_tokens, noise_time):
|
| 115 |
+
timesteps = noise_time
|
| 116 |
+
if not torch.is_tensor(timesteps):
|
| 117 |
+
timesteps = torch.tensor([timesteps], dtype=torch.long, device=input_tokens.device)
|
| 118 |
+
elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
|
| 119 |
+
timesteps = timesteps[None].to(input_tokens.device)
|
| 120 |
+
|
| 121 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 122 |
+
timesteps = timesteps * torch.ones(input_tokens.shape[0], dtype=timesteps.dtype, device=timesteps.device)
|
| 123 |
+
|
| 124 |
+
logits = self.decoder(
|
| 125 |
+
encodings_and_masks=encodings_and_masks, decoder_input_tokens=input_tokens, decoder_noise_time=timesteps
|
| 126 |
+
)
|
| 127 |
+
return logits
|
| 128 |
+
|
| 129 |
+
@torch.no_grad()
|
| 130 |
+
def __call__(
|
| 131 |
+
self,
|
| 132 |
+
input_tokens: List[List[int]],
|
| 133 |
+
generator: Optional[torch.Generator] = None,
|
| 134 |
+
num_inference_steps: int = 100,
|
| 135 |
+
return_dict: bool = True,
|
| 136 |
+
output_type: str = "numpy",
|
| 137 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 138 |
+
callback_steps: int = 1,
|
| 139 |
+
) -> Union[AudioPipelineOutput, Tuple]:
|
| 140 |
+
if (callback_steps is None) or (
|
| 141 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 142 |
+
):
|
| 143 |
+
raise ValueError(
|
| 144 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 145 |
+
f" {type(callback_steps)}."
|
| 146 |
+
)
|
| 147 |
+
r"""
|
| 148 |
+
The call function to the pipeline for generation.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
input_tokens (`List[List[int]]`):
|
| 152 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 153 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 154 |
+
generation deterministic.
|
| 155 |
+
num_inference_steps (`int`, *optional*, defaults to 100):
|
| 156 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality audio at the
|
| 157 |
+
expense of slower inference.
|
| 158 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 159 |
+
Whether or not to return a [`~pipelines.AudioPipelineOutput`] instead of a plain tuple.
|
| 160 |
+
output_type (`str`, *optional*, defaults to `"numpy"`):
|
| 161 |
+
The output format of the generated audio.
|
| 162 |
+
callback (`Callable`, *optional*):
|
| 163 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 164 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 165 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 166 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 167 |
+
every step.
|
| 168 |
+
|
| 169 |
+
Example:
|
| 170 |
+
|
| 171 |
+
```py
|
| 172 |
+
>>> from diffusers import SpectrogramDiffusionPipeline, MidiProcessor
|
| 173 |
+
|
| 174 |
+
>>> pipe = SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
|
| 175 |
+
>>> pipe = pipe.to("cuda")
|
| 176 |
+
>>> processor = MidiProcessor()
|
| 177 |
+
|
| 178 |
+
>>> # Download MIDI from: wget http://www.piano-midi.de/midis/beethoven/beethoven_hammerklavier_2.mid
|
| 179 |
+
>>> output = pipe(processor("beethoven_hammerklavier_2.mid"))
|
| 180 |
+
|
| 181 |
+
>>> audio = output.audios[0]
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
[`pipelines.AudioPipelineOutput`] or `tuple`:
|
| 186 |
+
If `return_dict` is `True`, [`pipelines.AudioPipelineOutput`] is returned, otherwise a `tuple` is
|
| 187 |
+
returned where the first element is a list with the generated audio.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
pred_mel = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims], dtype=np.float32)
|
| 191 |
+
full_pred_mel = np.zeros([1, 0, self.n_dims], np.float32)
|
| 192 |
+
ones = torch.ones((1, TARGET_FEATURE_LENGTH), dtype=bool, device=self.device)
|
| 193 |
+
|
| 194 |
+
for i, encoder_input_tokens in enumerate(input_tokens):
|
| 195 |
+
if i == 0:
|
| 196 |
+
encoder_continuous_inputs = torch.from_numpy(pred_mel[:1].copy()).to(
|
| 197 |
+
device=self.device, dtype=self.decoder.dtype
|
| 198 |
+
)
|
| 199 |
+
# The first chunk has no previous context.
|
| 200 |
+
encoder_continuous_mask = torch.zeros((1, TARGET_FEATURE_LENGTH), dtype=bool, device=self.device)
|
| 201 |
+
else:
|
| 202 |
+
# The full song pipeline does not feed in a context feature, so the mask
|
| 203 |
+
# will be all 0s after the feature converter. Because we know we're
|
| 204 |
+
# feeding in a full context chunk from the previous prediction, set it
|
| 205 |
+
# to all 1s.
|
| 206 |
+
encoder_continuous_mask = ones
|
| 207 |
+
|
| 208 |
+
encoder_continuous_inputs = self.scale_features(
|
| 209 |
+
encoder_continuous_inputs, output_range=[-1.0, 1.0], clip=True
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
encodings_and_masks = self.encode(
|
| 213 |
+
input_tokens=torch.IntTensor([encoder_input_tokens]).to(device=self.device),
|
| 214 |
+
continuous_inputs=encoder_continuous_inputs,
|
| 215 |
+
continuous_mask=encoder_continuous_mask,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
|
| 219 |
+
x = randn_tensor(
|
| 220 |
+
shape=encoder_continuous_inputs.shape,
|
| 221 |
+
generator=generator,
|
| 222 |
+
device=self.device,
|
| 223 |
+
dtype=self.decoder.dtype,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# set step values
|
| 227 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
| 228 |
+
|
| 229 |
+
# Denoising diffusion loop
|
| 230 |
+
for j, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
|
| 231 |
+
output = self.decode(
|
| 232 |
+
encodings_and_masks=encodings_and_masks,
|
| 233 |
+
input_tokens=x,
|
| 234 |
+
noise_time=t / self.scheduler.config.num_train_timesteps, # rescale to [0, 1)
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
# Compute previous output: x_t -> x_t-1
|
| 238 |
+
x = self.scheduler.step(output, t, x, generator=generator).prev_sample
|
| 239 |
+
|
| 240 |
+
mel = self.scale_to_features(x, input_range=[-1.0, 1.0])
|
| 241 |
+
encoder_continuous_inputs = mel[:1]
|
| 242 |
+
pred_mel = mel.cpu().float().numpy()
|
| 243 |
+
|
| 244 |
+
full_pred_mel = np.concatenate([full_pred_mel, pred_mel[:1]], axis=1)
|
| 245 |
+
|
| 246 |
+
# call the callback, if provided
|
| 247 |
+
if callback is not None and i % callback_steps == 0:
|
| 248 |
+
callback(i, full_pred_mel)
|
| 249 |
+
|
| 250 |
+
logger.info("Generated segment", i)
|
| 251 |
+
|
| 252 |
+
if output_type == "numpy" and not is_onnx_available():
|
| 253 |
+
raise ValueError(
|
| 254 |
+
"Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'."
|
| 255 |
+
)
|
| 256 |
+
elif output_type == "numpy" and self.melgan is None:
|
| 257 |
+
raise ValueError(
|
| 258 |
+
"Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'."
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
if output_type == "numpy":
|
| 262 |
+
output = self.melgan(input_features=full_pred_mel.astype(np.float32))
|
| 263 |
+
else:
|
| 264 |
+
output = full_pred_mel
|
| 265 |
+
|
| 266 |
+
if not return_dict:
|
| 267 |
+
return (output,)
|
| 268 |
+
|
| 269 |
+
return AudioPipelineOutput(audios=output)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ....utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
is_torch_available,
|
| 8 |
+
is_transformers_available,
|
| 9 |
+
is_transformers_version,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_dummy_objects = {}
|
| 14 |
+
_import_structure = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")):
|
| 18 |
+
raise OptionalDependencyNotAvailable()
|
| 19 |
+
except OptionalDependencyNotAvailable:
|
| 20 |
+
from ....utils.dummy_torch_and_transformers_objects import (
|
| 21 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 22 |
+
VersatileDiffusionImageVariationPipeline,
|
| 23 |
+
VersatileDiffusionPipeline,
|
| 24 |
+
VersatileDiffusionTextToImagePipeline,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
_dummy_objects.update(
|
| 28 |
+
{
|
| 29 |
+
"VersatileDiffusionDualGuidedPipeline": VersatileDiffusionDualGuidedPipeline,
|
| 30 |
+
"VersatileDiffusionImageVariationPipeline": VersatileDiffusionImageVariationPipeline,
|
| 31 |
+
"VersatileDiffusionPipeline": VersatileDiffusionPipeline,
|
| 32 |
+
"VersatileDiffusionTextToImagePipeline": VersatileDiffusionTextToImagePipeline,
|
| 33 |
+
}
|
| 34 |
+
)
|
| 35 |
+
else:
|
| 36 |
+
_import_structure["modeling_text_unet"] = ["UNetFlatConditionModel"]
|
| 37 |
+
_import_structure["pipeline_versatile_diffusion"] = ["VersatileDiffusionPipeline"]
|
| 38 |
+
_import_structure["pipeline_versatile_diffusion_dual_guided"] = ["VersatileDiffusionDualGuidedPipeline"]
|
| 39 |
+
_import_structure["pipeline_versatile_diffusion_image_variation"] = ["VersatileDiffusionImageVariationPipeline"]
|
| 40 |
+
_import_structure["pipeline_versatile_diffusion_text_to_image"] = ["VersatileDiffusionTextToImagePipeline"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 44 |
+
try:
|
| 45 |
+
if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")):
|
| 46 |
+
raise OptionalDependencyNotAvailable()
|
| 47 |
+
except OptionalDependencyNotAvailable:
|
| 48 |
+
from ....utils.dummy_torch_and_transformers_objects import (
|
| 49 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 50 |
+
VersatileDiffusionImageVariationPipeline,
|
| 51 |
+
VersatileDiffusionPipeline,
|
| 52 |
+
VersatileDiffusionTextToImagePipeline,
|
| 53 |
+
)
|
| 54 |
+
else:
|
| 55 |
+
from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
|
| 56 |
+
from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
|
| 57 |
+
from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
|
| 58 |
+
from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
|
| 59 |
+
|
| 60 |
+
else:
|
| 61 |
+
import sys
|
| 62 |
+
|
| 63 |
+
sys.modules[__name__] = _LazyModule(
|
| 64 |
+
__name__,
|
| 65 |
+
globals()["__file__"],
|
| 66 |
+
_import_structure,
|
| 67 |
+
module_spec=__spec__,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
for name, value in _dummy_objects.items():
|
| 71 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.57 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/modeling_text_unet.cpython-310.pyc
ADDED
|
Binary file (63.7 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion.cpython-310.pyc
ADDED
|
Binary file (20.3 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_dual_guided.cpython-310.pyc
ADDED
|
Binary file (17.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_image_variation.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/__pycache__/pipeline_versatile_diffusion_text_to_image.cpython-310.pyc
ADDED
|
Binary file (15.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from typing import Callable, List, Optional, Union
|
| 3 |
+
|
| 4 |
+
import PIL.Image
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModel
|
| 7 |
+
|
| 8 |
+
from ....models import AutoencoderKL, UNet2DConditionModel
|
| 9 |
+
from ....schedulers import KarrasDiffusionSchedulers
|
| 10 |
+
from ....utils import logging
|
| 11 |
+
from ...pipeline_utils import DiffusionPipeline
|
| 12 |
+
from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
|
| 13 |
+
from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
|
| 14 |
+
from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class VersatileDiffusionPipeline(DiffusionPipeline):
|
| 21 |
+
r"""
|
| 22 |
+
Pipeline for text-to-image generation using Stable Diffusion.
|
| 23 |
+
|
| 24 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 25 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
vae ([`AutoencoderKL`]):
|
| 29 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 30 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 31 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 32 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 33 |
+
A `CLIPTokenizer` to tokenize text.
|
| 34 |
+
unet ([`UNet2DConditionModel`]):
|
| 35 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 36 |
+
scheduler ([`SchedulerMixin`]):
|
| 37 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 38 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 39 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 40 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 41 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 42 |
+
about a model's potential harms.
|
| 43 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 44 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
tokenizer: CLIPTokenizer
|
| 48 |
+
image_feature_extractor: CLIPImageProcessor
|
| 49 |
+
text_encoder: CLIPTextModel
|
| 50 |
+
image_encoder: CLIPVisionModel
|
| 51 |
+
image_unet: UNet2DConditionModel
|
| 52 |
+
text_unet: UNet2DConditionModel
|
| 53 |
+
vae: AutoencoderKL
|
| 54 |
+
scheduler: KarrasDiffusionSchedulers
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
tokenizer: CLIPTokenizer,
|
| 59 |
+
image_feature_extractor: CLIPImageProcessor,
|
| 60 |
+
text_encoder: CLIPTextModel,
|
| 61 |
+
image_encoder: CLIPVisionModel,
|
| 62 |
+
image_unet: UNet2DConditionModel,
|
| 63 |
+
text_unet: UNet2DConditionModel,
|
| 64 |
+
vae: AutoencoderKL,
|
| 65 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 66 |
+
):
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
self.register_modules(
|
| 70 |
+
tokenizer=tokenizer,
|
| 71 |
+
image_feature_extractor=image_feature_extractor,
|
| 72 |
+
text_encoder=text_encoder,
|
| 73 |
+
image_encoder=image_encoder,
|
| 74 |
+
image_unet=image_unet,
|
| 75 |
+
text_unet=text_unet,
|
| 76 |
+
vae=vae,
|
| 77 |
+
scheduler=scheduler,
|
| 78 |
+
)
|
| 79 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 80 |
+
|
| 81 |
+
@torch.no_grad()
|
| 82 |
+
def image_variation(
|
| 83 |
+
self,
|
| 84 |
+
image: Union[torch.FloatTensor, PIL.Image.Image],
|
| 85 |
+
height: Optional[int] = None,
|
| 86 |
+
width: Optional[int] = None,
|
| 87 |
+
num_inference_steps: int = 50,
|
| 88 |
+
guidance_scale: float = 7.5,
|
| 89 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 90 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 91 |
+
eta: float = 0.0,
|
| 92 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 93 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 94 |
+
output_type: Optional[str] = "pil",
|
| 95 |
+
return_dict: bool = True,
|
| 96 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 97 |
+
callback_steps: int = 1,
|
| 98 |
+
):
|
| 99 |
+
r"""
|
| 100 |
+
The call function to the pipeline for generation.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
image (`PIL.Image.Image`, `List[PIL.Image.Image]` or `torch.Tensor`):
|
| 104 |
+
The image prompt or prompts to guide the image generation.
|
| 105 |
+
height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 106 |
+
The height in pixels of the generated image.
|
| 107 |
+
width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 108 |
+
The width in pixels of the generated image.
|
| 109 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 110 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 111 |
+
expense of slower inference.
|
| 112 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 113 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 114 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 115 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 116 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 117 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 118 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 119 |
+
The number of images to generate per prompt.
|
| 120 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 121 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 122 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 123 |
+
generator (`torch.Generator`, *optional*):
|
| 124 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 125 |
+
generation deterministic.
|
| 126 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 127 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 128 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 129 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 130 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 131 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 132 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 133 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 134 |
+
plain tuple.
|
| 135 |
+
callback (`Callable`, *optional*):
|
| 136 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 137 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 138 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 139 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 140 |
+
every step.
|
| 141 |
+
|
| 142 |
+
Examples:
|
| 143 |
+
|
| 144 |
+
```py
|
| 145 |
+
>>> from diffusers import VersatileDiffusionPipeline
|
| 146 |
+
>>> import torch
|
| 147 |
+
>>> import requests
|
| 148 |
+
>>> from io import BytesIO
|
| 149 |
+
>>> from PIL import Image
|
| 150 |
+
|
| 151 |
+
>>> # let's download an initial image
|
| 152 |
+
>>> url = "https://huggingface.co/datasets/diffusers/images/resolve/main/benz.jpg"
|
| 153 |
+
|
| 154 |
+
>>> response = requests.get(url)
|
| 155 |
+
>>> image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 156 |
+
|
| 157 |
+
>>> pipe = VersatileDiffusionPipeline.from_pretrained(
|
| 158 |
+
... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
|
| 159 |
+
... )
|
| 160 |
+
>>> pipe = pipe.to("cuda")
|
| 161 |
+
|
| 162 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(0)
|
| 163 |
+
>>> image = pipe.image_variation(image, generator=generator).images[0]
|
| 164 |
+
>>> image.save("./car_variation.png")
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 169 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 170 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 171 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 172 |
+
"not-safe-for-work" (nsfw) content.
|
| 173 |
+
"""
|
| 174 |
+
expected_components = inspect.signature(VersatileDiffusionImageVariationPipeline.__init__).parameters.keys()
|
| 175 |
+
components = {name: component for name, component in self.components.items() if name in expected_components}
|
| 176 |
+
return VersatileDiffusionImageVariationPipeline(**components)(
|
| 177 |
+
image=image,
|
| 178 |
+
height=height,
|
| 179 |
+
width=width,
|
| 180 |
+
num_inference_steps=num_inference_steps,
|
| 181 |
+
guidance_scale=guidance_scale,
|
| 182 |
+
negative_prompt=negative_prompt,
|
| 183 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 184 |
+
eta=eta,
|
| 185 |
+
generator=generator,
|
| 186 |
+
latents=latents,
|
| 187 |
+
output_type=output_type,
|
| 188 |
+
return_dict=return_dict,
|
| 189 |
+
callback=callback,
|
| 190 |
+
callback_steps=callback_steps,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
@torch.no_grad()
|
| 194 |
+
def text_to_image(
|
| 195 |
+
self,
|
| 196 |
+
prompt: Union[str, List[str]],
|
| 197 |
+
height: Optional[int] = None,
|
| 198 |
+
width: Optional[int] = None,
|
| 199 |
+
num_inference_steps: int = 50,
|
| 200 |
+
guidance_scale: float = 7.5,
|
| 201 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 202 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 203 |
+
eta: float = 0.0,
|
| 204 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 205 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 206 |
+
output_type: Optional[str] = "pil",
|
| 207 |
+
return_dict: bool = True,
|
| 208 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 209 |
+
callback_steps: int = 1,
|
| 210 |
+
):
|
| 211 |
+
r"""
|
| 212 |
+
The call function to the pipeline for generation.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
prompt (`str` or `List[str]`):
|
| 216 |
+
The prompt or prompts to guide image generation.
|
| 217 |
+
height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 218 |
+
The height in pixels of the generated image.
|
| 219 |
+
width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 220 |
+
The width in pixels of the generated image.
|
| 221 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 222 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 223 |
+
expense of slower inference.
|
| 224 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 225 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 226 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 227 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 228 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 229 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 230 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 231 |
+
The number of images to generate per prompt.
|
| 232 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 233 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 234 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 235 |
+
generator (`torch.Generator`, *optional*):
|
| 236 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 237 |
+
generation deterministic.
|
| 238 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 239 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 240 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 241 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 242 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 243 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 244 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 245 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 246 |
+
plain tuple.
|
| 247 |
+
callback (`Callable`, *optional*):
|
| 248 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 249 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 250 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 251 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 252 |
+
every step.
|
| 253 |
+
|
| 254 |
+
Examples:
|
| 255 |
+
|
| 256 |
+
```py
|
| 257 |
+
>>> from diffusers import VersatileDiffusionPipeline
|
| 258 |
+
>>> import torch
|
| 259 |
+
|
| 260 |
+
>>> pipe = VersatileDiffusionPipeline.from_pretrained(
|
| 261 |
+
... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
|
| 262 |
+
... )
|
| 263 |
+
>>> pipe = pipe.to("cuda")
|
| 264 |
+
|
| 265 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(0)
|
| 266 |
+
>>> image = pipe.text_to_image("an astronaut riding on a horse on mars", generator=generator).images[0]
|
| 267 |
+
>>> image.save("./astronaut.png")
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 272 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 273 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 274 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 275 |
+
"not-safe-for-work" (nsfw) content.
|
| 276 |
+
"""
|
| 277 |
+
expected_components = inspect.signature(VersatileDiffusionTextToImagePipeline.__init__).parameters.keys()
|
| 278 |
+
components = {name: component for name, component in self.components.items() if name in expected_components}
|
| 279 |
+
temp_pipeline = VersatileDiffusionTextToImagePipeline(**components)
|
| 280 |
+
output = temp_pipeline(
|
| 281 |
+
prompt=prompt,
|
| 282 |
+
height=height,
|
| 283 |
+
width=width,
|
| 284 |
+
num_inference_steps=num_inference_steps,
|
| 285 |
+
guidance_scale=guidance_scale,
|
| 286 |
+
negative_prompt=negative_prompt,
|
| 287 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 288 |
+
eta=eta,
|
| 289 |
+
generator=generator,
|
| 290 |
+
latents=latents,
|
| 291 |
+
output_type=output_type,
|
| 292 |
+
return_dict=return_dict,
|
| 293 |
+
callback=callback,
|
| 294 |
+
callback_steps=callback_steps,
|
| 295 |
+
)
|
| 296 |
+
# swap the attention blocks back to the original state
|
| 297 |
+
temp_pipeline._swap_unet_attention_blocks()
|
| 298 |
+
|
| 299 |
+
return output
|
| 300 |
+
|
| 301 |
+
@torch.no_grad()
|
| 302 |
+
def dual_guided(
|
| 303 |
+
self,
|
| 304 |
+
prompt: Union[PIL.Image.Image, List[PIL.Image.Image]],
|
| 305 |
+
image: Union[str, List[str]],
|
| 306 |
+
text_to_image_strength: float = 0.5,
|
| 307 |
+
height: Optional[int] = None,
|
| 308 |
+
width: Optional[int] = None,
|
| 309 |
+
num_inference_steps: int = 50,
|
| 310 |
+
guidance_scale: float = 7.5,
|
| 311 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 312 |
+
eta: float = 0.0,
|
| 313 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 314 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 315 |
+
output_type: Optional[str] = "pil",
|
| 316 |
+
return_dict: bool = True,
|
| 317 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 318 |
+
callback_steps: int = 1,
|
| 319 |
+
):
|
| 320 |
+
r"""
|
| 321 |
+
The call function to the pipeline for generation.
|
| 322 |
+
|
| 323 |
+
Args:
|
| 324 |
+
prompt (`str` or `List[str]`):
|
| 325 |
+
The prompt or prompts to guide image generation.
|
| 326 |
+
height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 327 |
+
The height in pixels of the generated image.
|
| 328 |
+
width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 329 |
+
The width in pixels of the generated image.
|
| 330 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 331 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 332 |
+
expense of slower inference.
|
| 333 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 334 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 335 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 336 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 337 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 338 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 339 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 340 |
+
The number of images to generate per prompt.
|
| 341 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 342 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 343 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 344 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 345 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 346 |
+
generation deterministic.
|
| 347 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 348 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 349 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 350 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 351 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 352 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 353 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 354 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 355 |
+
plain tuple.
|
| 356 |
+
callback (`Callable`, *optional*):
|
| 357 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 358 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 359 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 360 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 361 |
+
every step.
|
| 362 |
+
|
| 363 |
+
Examples:
|
| 364 |
+
|
| 365 |
+
```py
|
| 366 |
+
>>> from diffusers import VersatileDiffusionPipeline
|
| 367 |
+
>>> import torch
|
| 368 |
+
>>> import requests
|
| 369 |
+
>>> from io import BytesIO
|
| 370 |
+
>>> from PIL import Image
|
| 371 |
+
|
| 372 |
+
>>> # let's download an initial image
|
| 373 |
+
>>> url = "https://huggingface.co/datasets/diffusers/images/resolve/main/benz.jpg"
|
| 374 |
+
|
| 375 |
+
>>> response = requests.get(url)
|
| 376 |
+
>>> image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 377 |
+
>>> text = "a red car in the sun"
|
| 378 |
+
|
| 379 |
+
>>> pipe = VersatileDiffusionPipeline.from_pretrained(
|
| 380 |
+
... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
|
| 381 |
+
... )
|
| 382 |
+
>>> pipe = pipe.to("cuda")
|
| 383 |
+
|
| 384 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(0)
|
| 385 |
+
>>> text_to_image_strength = 0.75
|
| 386 |
+
|
| 387 |
+
>>> image = pipe.dual_guided(
|
| 388 |
+
... prompt=text, image=image, text_to_image_strength=text_to_image_strength, generator=generator
|
| 389 |
+
... ).images[0]
|
| 390 |
+
>>> image.save("./car_variation.png")
|
| 391 |
+
```
|
| 392 |
+
|
| 393 |
+
Returns:
|
| 394 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`:
|
| 395 |
+
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
|
| 396 |
+
returned where the first element is a list with the generated images.
|
| 397 |
+
"""
|
| 398 |
+
|
| 399 |
+
expected_components = inspect.signature(VersatileDiffusionDualGuidedPipeline.__init__).parameters.keys()
|
| 400 |
+
components = {name: component for name, component in self.components.items() if name in expected_components}
|
| 401 |
+
temp_pipeline = VersatileDiffusionDualGuidedPipeline(**components)
|
| 402 |
+
output = temp_pipeline(
|
| 403 |
+
prompt=prompt,
|
| 404 |
+
image=image,
|
| 405 |
+
text_to_image_strength=text_to_image_strength,
|
| 406 |
+
height=height,
|
| 407 |
+
width=width,
|
| 408 |
+
num_inference_steps=num_inference_steps,
|
| 409 |
+
guidance_scale=guidance_scale,
|
| 410 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 411 |
+
eta=eta,
|
| 412 |
+
generator=generator,
|
| 413 |
+
latents=latents,
|
| 414 |
+
output_type=output_type,
|
| 415 |
+
return_dict=return_dict,
|
| 416 |
+
callback=callback,
|
| 417 |
+
callback_steps=callback_steps,
|
| 418 |
+
)
|
| 419 |
+
temp_pipeline._revert_dual_attention()
|
| 420 |
+
|
| 421 |
+
return output
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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right 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from typing import Callable, List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import PIL.Image
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from transformers import (
|
| 23 |
+
CLIPImageProcessor,
|
| 24 |
+
CLIPTextModelWithProjection,
|
| 25 |
+
CLIPTokenizer,
|
| 26 |
+
CLIPVisionModelWithProjection,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from ....image_processor import VaeImageProcessor
|
| 30 |
+
from ....models import AutoencoderKL, DualTransformer2DModel, Transformer2DModel, UNet2DConditionModel
|
| 31 |
+
from ....schedulers import KarrasDiffusionSchedulers
|
| 32 |
+
from ....utils import deprecate, logging
|
| 33 |
+
from ....utils.torch_utils import randn_tensor
|
| 34 |
+
from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 35 |
+
from .modeling_text_unet import UNetFlatConditionModel
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class VersatileDiffusionDualGuidedPipeline(DiffusionPipeline):
|
| 42 |
+
r"""
|
| 43 |
+
Pipeline for image-text dual-guided generation using Versatile Diffusion.
|
| 44 |
+
|
| 45 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 46 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 47 |
+
|
| 48 |
+
Parameters:
|
| 49 |
+
vqvae ([`VQModel`]):
|
| 50 |
+
Vector-quantized (VQ) model to encode and decode images to and from latent representations.
|
| 51 |
+
bert ([`LDMBertModel`]):
|
| 52 |
+
Text-encoder model based on [`~transformers.BERT`].
|
| 53 |
+
tokenizer ([`~transformers.BertTokenizer`]):
|
| 54 |
+
A `BertTokenizer` to tokenize text.
|
| 55 |
+
unet ([`UNet2DConditionModel`]):
|
| 56 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 57 |
+
scheduler ([`SchedulerMixin`]):
|
| 58 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 59 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
model_cpu_offload_seq = "bert->unet->vqvae"
|
| 63 |
+
|
| 64 |
+
tokenizer: CLIPTokenizer
|
| 65 |
+
image_feature_extractor: CLIPImageProcessor
|
| 66 |
+
text_encoder: CLIPTextModelWithProjection
|
| 67 |
+
image_encoder: CLIPVisionModelWithProjection
|
| 68 |
+
image_unet: UNet2DConditionModel
|
| 69 |
+
text_unet: UNetFlatConditionModel
|
| 70 |
+
vae: AutoencoderKL
|
| 71 |
+
scheduler: KarrasDiffusionSchedulers
|
| 72 |
+
|
| 73 |
+
_optional_components = ["text_unet"]
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
tokenizer: CLIPTokenizer,
|
| 78 |
+
image_feature_extractor: CLIPImageProcessor,
|
| 79 |
+
text_encoder: CLIPTextModelWithProjection,
|
| 80 |
+
image_encoder: CLIPVisionModelWithProjection,
|
| 81 |
+
image_unet: UNet2DConditionModel,
|
| 82 |
+
text_unet: UNetFlatConditionModel,
|
| 83 |
+
vae: AutoencoderKL,
|
| 84 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 85 |
+
):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.register_modules(
|
| 88 |
+
tokenizer=tokenizer,
|
| 89 |
+
image_feature_extractor=image_feature_extractor,
|
| 90 |
+
text_encoder=text_encoder,
|
| 91 |
+
image_encoder=image_encoder,
|
| 92 |
+
image_unet=image_unet,
|
| 93 |
+
text_unet=text_unet,
|
| 94 |
+
vae=vae,
|
| 95 |
+
scheduler=scheduler,
|
| 96 |
+
)
|
| 97 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 98 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 99 |
+
|
| 100 |
+
if self.text_unet is not None and (
|
| 101 |
+
"dual_cross_attention" not in self.image_unet.config or not self.image_unet.config.dual_cross_attention
|
| 102 |
+
):
|
| 103 |
+
# if loading from a universal checkpoint rather than a saved dual-guided pipeline
|
| 104 |
+
self._convert_to_dual_attention()
|
| 105 |
+
|
| 106 |
+
def remove_unused_weights(self):
|
| 107 |
+
self.register_modules(text_unet=None)
|
| 108 |
+
|
| 109 |
+
def _convert_to_dual_attention(self):
|
| 110 |
+
"""
|
| 111 |
+
Replace image_unet's `Transformer2DModel` blocks with `DualTransformer2DModel` that contains transformer blocks
|
| 112 |
+
from both `image_unet` and `text_unet`
|
| 113 |
+
"""
|
| 114 |
+
for name, module in self.image_unet.named_modules():
|
| 115 |
+
if isinstance(module, Transformer2DModel):
|
| 116 |
+
parent_name, index = name.rsplit(".", 1)
|
| 117 |
+
index = int(index)
|
| 118 |
+
|
| 119 |
+
image_transformer = self.image_unet.get_submodule(parent_name)[index]
|
| 120 |
+
text_transformer = self.text_unet.get_submodule(parent_name)[index]
|
| 121 |
+
|
| 122 |
+
config = image_transformer.config
|
| 123 |
+
dual_transformer = DualTransformer2DModel(
|
| 124 |
+
num_attention_heads=config.num_attention_heads,
|
| 125 |
+
attention_head_dim=config.attention_head_dim,
|
| 126 |
+
in_channels=config.in_channels,
|
| 127 |
+
num_layers=config.num_layers,
|
| 128 |
+
dropout=config.dropout,
|
| 129 |
+
norm_num_groups=config.norm_num_groups,
|
| 130 |
+
cross_attention_dim=config.cross_attention_dim,
|
| 131 |
+
attention_bias=config.attention_bias,
|
| 132 |
+
sample_size=config.sample_size,
|
| 133 |
+
num_vector_embeds=config.num_vector_embeds,
|
| 134 |
+
activation_fn=config.activation_fn,
|
| 135 |
+
num_embeds_ada_norm=config.num_embeds_ada_norm,
|
| 136 |
+
)
|
| 137 |
+
dual_transformer.transformers[0] = image_transformer
|
| 138 |
+
dual_transformer.transformers[1] = text_transformer
|
| 139 |
+
|
| 140 |
+
self.image_unet.get_submodule(parent_name)[index] = dual_transformer
|
| 141 |
+
self.image_unet.register_to_config(dual_cross_attention=True)
|
| 142 |
+
|
| 143 |
+
def _revert_dual_attention(self):
|
| 144 |
+
"""
|
| 145 |
+
Revert the image_unet `DualTransformer2DModel` blocks back to `Transformer2DModel` with image_unet weights Call
|
| 146 |
+
this function if you reuse `image_unet` in another pipeline, e.g. `VersatileDiffusionPipeline`
|
| 147 |
+
"""
|
| 148 |
+
for name, module in self.image_unet.named_modules():
|
| 149 |
+
if isinstance(module, DualTransformer2DModel):
|
| 150 |
+
parent_name, index = name.rsplit(".", 1)
|
| 151 |
+
index = int(index)
|
| 152 |
+
self.image_unet.get_submodule(parent_name)[index] = module.transformers[0]
|
| 153 |
+
|
| 154 |
+
self.image_unet.register_to_config(dual_cross_attention=False)
|
| 155 |
+
|
| 156 |
+
def _encode_text_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance):
|
| 157 |
+
r"""
|
| 158 |
+
Encodes the prompt into text encoder hidden states.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
prompt (`str` or `List[str]`):
|
| 162 |
+
prompt to be encoded
|
| 163 |
+
device: (`torch.device`):
|
| 164 |
+
torch device
|
| 165 |
+
num_images_per_prompt (`int`):
|
| 166 |
+
number of images that should be generated per prompt
|
| 167 |
+
do_classifier_free_guidance (`bool`):
|
| 168 |
+
whether to use classifier free guidance or not
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def normalize_embeddings(encoder_output):
|
| 172 |
+
embeds = self.text_encoder.text_projection(encoder_output.last_hidden_state)
|
| 173 |
+
embeds_pooled = encoder_output.text_embeds
|
| 174 |
+
embeds = embeds / torch.norm(embeds_pooled.unsqueeze(1), dim=-1, keepdim=True)
|
| 175 |
+
return embeds
|
| 176 |
+
|
| 177 |
+
batch_size = len(prompt)
|
| 178 |
+
|
| 179 |
+
text_inputs = self.tokenizer(
|
| 180 |
+
prompt,
|
| 181 |
+
padding="max_length",
|
| 182 |
+
max_length=self.tokenizer.model_max_length,
|
| 183 |
+
truncation=True,
|
| 184 |
+
return_tensors="pt",
|
| 185 |
+
)
|
| 186 |
+
text_input_ids = text_inputs.input_ids
|
| 187 |
+
untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="pt").input_ids
|
| 188 |
+
|
| 189 |
+
if not torch.equal(text_input_ids, untruncated_ids):
|
| 190 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
|
| 191 |
+
logger.warning(
|
| 192 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 193 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 197 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 198 |
+
else:
|
| 199 |
+
attention_mask = None
|
| 200 |
+
|
| 201 |
+
prompt_embeds = self.text_encoder(
|
| 202 |
+
text_input_ids.to(device),
|
| 203 |
+
attention_mask=attention_mask,
|
| 204 |
+
)
|
| 205 |
+
prompt_embeds = normalize_embeddings(prompt_embeds)
|
| 206 |
+
|
| 207 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 208 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 209 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 210 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 211 |
+
|
| 212 |
+
# get unconditional embeddings for classifier free guidance
|
| 213 |
+
if do_classifier_free_guidance:
|
| 214 |
+
uncond_tokens = [""] * batch_size
|
| 215 |
+
max_length = text_input_ids.shape[-1]
|
| 216 |
+
uncond_input = self.tokenizer(
|
| 217 |
+
uncond_tokens,
|
| 218 |
+
padding="max_length",
|
| 219 |
+
max_length=max_length,
|
| 220 |
+
truncation=True,
|
| 221 |
+
return_tensors="pt",
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 225 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 226 |
+
else:
|
| 227 |
+
attention_mask = None
|
| 228 |
+
|
| 229 |
+
negative_prompt_embeds = self.text_encoder(
|
| 230 |
+
uncond_input.input_ids.to(device),
|
| 231 |
+
attention_mask=attention_mask,
|
| 232 |
+
)
|
| 233 |
+
negative_prompt_embeds = normalize_embeddings(negative_prompt_embeds)
|
| 234 |
+
|
| 235 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 236 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 237 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 238 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 239 |
+
|
| 240 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 241 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 242 |
+
# to avoid doing two forward passes
|
| 243 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 244 |
+
|
| 245 |
+
return prompt_embeds
|
| 246 |
+
|
| 247 |
+
def _encode_image_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance):
|
| 248 |
+
r"""
|
| 249 |
+
Encodes the prompt into text encoder hidden states.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
prompt (`str` or `List[str]`):
|
| 253 |
+
prompt to be encoded
|
| 254 |
+
device: (`torch.device`):
|
| 255 |
+
torch device
|
| 256 |
+
num_images_per_prompt (`int`):
|
| 257 |
+
number of images that should be generated per prompt
|
| 258 |
+
do_classifier_free_guidance (`bool`):
|
| 259 |
+
whether to use classifier free guidance or not
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
def normalize_embeddings(encoder_output):
|
| 263 |
+
embeds = self.image_encoder.vision_model.post_layernorm(encoder_output.last_hidden_state)
|
| 264 |
+
embeds = self.image_encoder.visual_projection(embeds)
|
| 265 |
+
embeds_pooled = embeds[:, 0:1]
|
| 266 |
+
embeds = embeds / torch.norm(embeds_pooled, dim=-1, keepdim=True)
|
| 267 |
+
return embeds
|
| 268 |
+
|
| 269 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
| 270 |
+
|
| 271 |
+
# get prompt text embeddings
|
| 272 |
+
image_input = self.image_feature_extractor(images=prompt, return_tensors="pt")
|
| 273 |
+
pixel_values = image_input.pixel_values.to(device).to(self.image_encoder.dtype)
|
| 274 |
+
image_embeddings = self.image_encoder(pixel_values)
|
| 275 |
+
image_embeddings = normalize_embeddings(image_embeddings)
|
| 276 |
+
|
| 277 |
+
# duplicate image embeddings for each generation per prompt, using mps friendly method
|
| 278 |
+
bs_embed, seq_len, _ = image_embeddings.shape
|
| 279 |
+
image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
|
| 280 |
+
image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 281 |
+
|
| 282 |
+
# get unconditional embeddings for classifier free guidance
|
| 283 |
+
if do_classifier_free_guidance:
|
| 284 |
+
uncond_images = [np.zeros((512, 512, 3)) + 0.5] * batch_size
|
| 285 |
+
uncond_images = self.image_feature_extractor(images=uncond_images, return_tensors="pt")
|
| 286 |
+
pixel_values = uncond_images.pixel_values.to(device).to(self.image_encoder.dtype)
|
| 287 |
+
negative_prompt_embeds = self.image_encoder(pixel_values)
|
| 288 |
+
negative_prompt_embeds = normalize_embeddings(negative_prompt_embeds)
|
| 289 |
+
|
| 290 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 291 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 292 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 293 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 294 |
+
|
| 295 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 296 |
+
# Here we concatenate the unconditional and conditional embeddings into a single batch
|
| 297 |
+
# to avoid doing two forward passes
|
| 298 |
+
image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
|
| 299 |
+
|
| 300 |
+
return image_embeddings
|
| 301 |
+
|
| 302 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
| 303 |
+
def decode_latents(self, latents):
|
| 304 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 305 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 306 |
+
|
| 307 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 308 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 309 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 310 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 311 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 312 |
+
return image
|
| 313 |
+
|
| 314 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 315 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 316 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 317 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 318 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 319 |
+
# and should be between [0, 1]
|
| 320 |
+
|
| 321 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 322 |
+
extra_step_kwargs = {}
|
| 323 |
+
if accepts_eta:
|
| 324 |
+
extra_step_kwargs["eta"] = eta
|
| 325 |
+
|
| 326 |
+
# check if the scheduler accepts generator
|
| 327 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 328 |
+
if accepts_generator:
|
| 329 |
+
extra_step_kwargs["generator"] = generator
|
| 330 |
+
return extra_step_kwargs
|
| 331 |
+
|
| 332 |
+
def check_inputs(self, prompt, image, height, width, callback_steps):
|
| 333 |
+
if not isinstance(prompt, str) and not isinstance(prompt, PIL.Image.Image) and not isinstance(prompt, list):
|
| 334 |
+
raise ValueError(f"`prompt` has to be of type `str` `PIL.Image` or `list` but is {type(prompt)}")
|
| 335 |
+
if not isinstance(image, str) and not isinstance(image, PIL.Image.Image) and not isinstance(image, list):
|
| 336 |
+
raise ValueError(f"`image` has to be of type `str` `PIL.Image` or `list` but is {type(image)}")
|
| 337 |
+
|
| 338 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 339 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 340 |
+
|
| 341 |
+
if (callback_steps is None) or (
|
| 342 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 343 |
+
):
|
| 344 |
+
raise ValueError(
|
| 345 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 346 |
+
f" {type(callback_steps)}."
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 350 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 351 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 352 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 353 |
+
raise ValueError(
|
| 354 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 355 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if latents is None:
|
| 359 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 360 |
+
else:
|
| 361 |
+
latents = latents.to(device)
|
| 362 |
+
|
| 363 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 364 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 365 |
+
return latents
|
| 366 |
+
|
| 367 |
+
def set_transformer_params(self, mix_ratio: float = 0.5, condition_types: Tuple = ("text", "image")):
|
| 368 |
+
for name, module in self.image_unet.named_modules():
|
| 369 |
+
if isinstance(module, DualTransformer2DModel):
|
| 370 |
+
module.mix_ratio = mix_ratio
|
| 371 |
+
|
| 372 |
+
for i, type in enumerate(condition_types):
|
| 373 |
+
if type == "text":
|
| 374 |
+
module.condition_lengths[i] = self.text_encoder.config.max_position_embeddings
|
| 375 |
+
module.transformer_index_for_condition[i] = 1 # use the second (text) transformer
|
| 376 |
+
else:
|
| 377 |
+
module.condition_lengths[i] = 257
|
| 378 |
+
module.transformer_index_for_condition[i] = 0 # use the first (image) transformer
|
| 379 |
+
|
| 380 |
+
@torch.no_grad()
|
| 381 |
+
def __call__(
|
| 382 |
+
self,
|
| 383 |
+
prompt: Union[PIL.Image.Image, List[PIL.Image.Image]],
|
| 384 |
+
image: Union[str, List[str]],
|
| 385 |
+
text_to_image_strength: float = 0.5,
|
| 386 |
+
height: Optional[int] = None,
|
| 387 |
+
width: Optional[int] = None,
|
| 388 |
+
num_inference_steps: int = 50,
|
| 389 |
+
guidance_scale: float = 7.5,
|
| 390 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 391 |
+
eta: float = 0.0,
|
| 392 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 393 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 394 |
+
output_type: Optional[str] = "pil",
|
| 395 |
+
return_dict: bool = True,
|
| 396 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 397 |
+
callback_steps: int = 1,
|
| 398 |
+
**kwargs,
|
| 399 |
+
):
|
| 400 |
+
r"""
|
| 401 |
+
The call function to the pipeline for generation.
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
prompt (`str` or `List[str]`):
|
| 405 |
+
The prompt or prompts to guide image generation.
|
| 406 |
+
height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 407 |
+
The height in pixels of the generated image.
|
| 408 |
+
width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 409 |
+
The width in pixels of the generated image.
|
| 410 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 411 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 412 |
+
expense of slower inference.
|
| 413 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 414 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 415 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 416 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 417 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 418 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 419 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 420 |
+
The number of images to generate per prompt.
|
| 421 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 422 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 423 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 424 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 425 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 426 |
+
generation deterministic.
|
| 427 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 428 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 429 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 430 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 431 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 432 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 433 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 434 |
+
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
|
| 435 |
+
callback (`Callable`, *optional*):
|
| 436 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 437 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 438 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 439 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 440 |
+
every step.
|
| 441 |
+
|
| 442 |
+
Examples:
|
| 443 |
+
|
| 444 |
+
```py
|
| 445 |
+
>>> from diffusers import VersatileDiffusionDualGuidedPipeline
|
| 446 |
+
>>> import torch
|
| 447 |
+
>>> import requests
|
| 448 |
+
>>> from io import BytesIO
|
| 449 |
+
>>> from PIL import Image
|
| 450 |
+
|
| 451 |
+
>>> # let's download an initial image
|
| 452 |
+
>>> url = "https://huggingface.co/datasets/diffusers/images/resolve/main/benz.jpg"
|
| 453 |
+
|
| 454 |
+
>>> response = requests.get(url)
|
| 455 |
+
>>> image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 456 |
+
>>> text = "a red car in the sun"
|
| 457 |
+
|
| 458 |
+
>>> pipe = VersatileDiffusionDualGuidedPipeline.from_pretrained(
|
| 459 |
+
... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
|
| 460 |
+
... )
|
| 461 |
+
>>> pipe.remove_unused_weights()
|
| 462 |
+
>>> pipe = pipe.to("cuda")
|
| 463 |
+
|
| 464 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(0)
|
| 465 |
+
>>> text_to_image_strength = 0.75
|
| 466 |
+
|
| 467 |
+
>>> image = pipe(
|
| 468 |
+
... prompt=text, image=image, text_to_image_strength=text_to_image_strength, generator=generator
|
| 469 |
+
... ).images[0]
|
| 470 |
+
>>> image.save("./car_variation.png")
|
| 471 |
+
```
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`:
|
| 475 |
+
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
|
| 476 |
+
returned where the first element is a list with the generated images.
|
| 477 |
+
"""
|
| 478 |
+
# 0. Default height and width to unet
|
| 479 |
+
height = height or self.image_unet.config.sample_size * self.vae_scale_factor
|
| 480 |
+
width = width or self.image_unet.config.sample_size * self.vae_scale_factor
|
| 481 |
+
|
| 482 |
+
# 1. Check inputs. Raise error if not correct
|
| 483 |
+
self.check_inputs(prompt, image, height, width, callback_steps)
|
| 484 |
+
|
| 485 |
+
# 2. Define call parameters
|
| 486 |
+
prompt = [prompt] if not isinstance(prompt, list) else prompt
|
| 487 |
+
image = [image] if not isinstance(image, list) else image
|
| 488 |
+
batch_size = len(prompt)
|
| 489 |
+
device = self._execution_device
|
| 490 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 491 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 492 |
+
# corresponds to doing no classifier free guidance.
|
| 493 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 494 |
+
|
| 495 |
+
# 3. Encode input prompts
|
| 496 |
+
prompt_embeds = self._encode_text_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance)
|
| 497 |
+
image_embeddings = self._encode_image_prompt(image, device, num_images_per_prompt, do_classifier_free_guidance)
|
| 498 |
+
dual_prompt_embeddings = torch.cat([prompt_embeds, image_embeddings], dim=1)
|
| 499 |
+
prompt_types = ("text", "image")
|
| 500 |
+
|
| 501 |
+
# 4. Prepare timesteps
|
| 502 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 503 |
+
timesteps = self.scheduler.timesteps
|
| 504 |
+
|
| 505 |
+
# 5. Prepare latent variables
|
| 506 |
+
num_channels_latents = self.image_unet.config.in_channels
|
| 507 |
+
latents = self.prepare_latents(
|
| 508 |
+
batch_size * num_images_per_prompt,
|
| 509 |
+
num_channels_latents,
|
| 510 |
+
height,
|
| 511 |
+
width,
|
| 512 |
+
dual_prompt_embeddings.dtype,
|
| 513 |
+
device,
|
| 514 |
+
generator,
|
| 515 |
+
latents,
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
# 6. Prepare extra step kwargs.
|
| 519 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 520 |
+
|
| 521 |
+
# 7. Combine the attention blocks of the image and text UNets
|
| 522 |
+
self.set_transformer_params(text_to_image_strength, prompt_types)
|
| 523 |
+
|
| 524 |
+
# 8. Denoising loop
|
| 525 |
+
for i, t in enumerate(self.progress_bar(timesteps)):
|
| 526 |
+
# expand the latents if we are doing classifier free guidance
|
| 527 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 528 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 529 |
+
|
| 530 |
+
# predict the noise residual
|
| 531 |
+
noise_pred = self.image_unet(latent_model_input, t, encoder_hidden_states=dual_prompt_embeddings).sample
|
| 532 |
+
|
| 533 |
+
# perform guidance
|
| 534 |
+
if do_classifier_free_guidance:
|
| 535 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 536 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 537 |
+
|
| 538 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 539 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 540 |
+
|
| 541 |
+
# call the callback, if provided
|
| 542 |
+
if callback is not None and i % callback_steps == 0:
|
| 543 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 544 |
+
callback(step_idx, t, latents)
|
| 545 |
+
|
| 546 |
+
if not output_type == "latent":
|
| 547 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 548 |
+
else:
|
| 549 |
+
image = latents
|
| 550 |
+
|
| 551 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 552 |
+
|
| 553 |
+
if not return_dict:
|
| 554 |
+
return (image,)
|
| 555 |
+
|
| 556 |
+
return ImagePipelineOutput(images=image)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from typing import Callable, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import PIL.Image
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
| 23 |
+
|
| 24 |
+
from ....image_processor import VaeImageProcessor
|
| 25 |
+
from ....models import AutoencoderKL, UNet2DConditionModel
|
| 26 |
+
from ....schedulers import KarrasDiffusionSchedulers
|
| 27 |
+
from ....utils import deprecate, logging
|
| 28 |
+
from ....utils.torch_utils import randn_tensor
|
| 29 |
+
from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class VersatileDiffusionImageVariationPipeline(DiffusionPipeline):
|
| 36 |
+
r"""
|
| 37 |
+
Pipeline for image variation using Versatile Diffusion.
|
| 38 |
+
|
| 39 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 40 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 41 |
+
|
| 42 |
+
Parameters:
|
| 43 |
+
vqvae ([`VQModel`]):
|
| 44 |
+
Vector-quantized (VQ) model to encode and decode images to and from latent representations.
|
| 45 |
+
bert ([`LDMBertModel`]):
|
| 46 |
+
Text-encoder model based on [`~transformers.BERT`].
|
| 47 |
+
tokenizer ([`~transformers.BertTokenizer`]):
|
| 48 |
+
A `BertTokenizer` to tokenize text.
|
| 49 |
+
unet ([`UNet2DConditionModel`]):
|
| 50 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 51 |
+
scheduler ([`SchedulerMixin`]):
|
| 52 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 53 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
model_cpu_offload_seq = "bert->unet->vqvae"
|
| 57 |
+
|
| 58 |
+
image_feature_extractor: CLIPImageProcessor
|
| 59 |
+
image_encoder: CLIPVisionModelWithProjection
|
| 60 |
+
image_unet: UNet2DConditionModel
|
| 61 |
+
vae: AutoencoderKL
|
| 62 |
+
scheduler: KarrasDiffusionSchedulers
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
image_feature_extractor: CLIPImageProcessor,
|
| 67 |
+
image_encoder: CLIPVisionModelWithProjection,
|
| 68 |
+
image_unet: UNet2DConditionModel,
|
| 69 |
+
vae: AutoencoderKL,
|
| 70 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 71 |
+
):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.register_modules(
|
| 74 |
+
image_feature_extractor=image_feature_extractor,
|
| 75 |
+
image_encoder=image_encoder,
|
| 76 |
+
image_unet=image_unet,
|
| 77 |
+
vae=vae,
|
| 78 |
+
scheduler=scheduler,
|
| 79 |
+
)
|
| 80 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 81 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 82 |
+
|
| 83 |
+
def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
|
| 84 |
+
r"""
|
| 85 |
+
Encodes the prompt into text encoder hidden states.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
prompt (`str` or `List[str]`):
|
| 89 |
+
prompt to be encoded
|
| 90 |
+
device: (`torch.device`):
|
| 91 |
+
torch device
|
| 92 |
+
num_images_per_prompt (`int`):
|
| 93 |
+
number of images that should be generated per prompt
|
| 94 |
+
do_classifier_free_guidance (`bool`):
|
| 95 |
+
whether to use classifier free guidance or not
|
| 96 |
+
negative_prompt (`str` or `List[str]`):
|
| 97 |
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
| 98 |
+
if `guidance_scale` is less than `1`).
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def normalize_embeddings(encoder_output):
|
| 102 |
+
embeds = self.image_encoder.vision_model.post_layernorm(encoder_output.last_hidden_state)
|
| 103 |
+
embeds = self.image_encoder.visual_projection(embeds)
|
| 104 |
+
embeds_pooled = embeds[:, 0:1]
|
| 105 |
+
embeds = embeds / torch.norm(embeds_pooled, dim=-1, keepdim=True)
|
| 106 |
+
return embeds
|
| 107 |
+
|
| 108 |
+
if isinstance(prompt, torch.Tensor) and len(prompt.shape) == 4:
|
| 109 |
+
prompt = list(prompt)
|
| 110 |
+
|
| 111 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
| 112 |
+
|
| 113 |
+
# get prompt text embeddings
|
| 114 |
+
image_input = self.image_feature_extractor(images=prompt, return_tensors="pt")
|
| 115 |
+
pixel_values = image_input.pixel_values.to(device).to(self.image_encoder.dtype)
|
| 116 |
+
image_embeddings = self.image_encoder(pixel_values)
|
| 117 |
+
image_embeddings = normalize_embeddings(image_embeddings)
|
| 118 |
+
|
| 119 |
+
# duplicate image embeddings for each generation per prompt, using mps friendly method
|
| 120 |
+
bs_embed, seq_len, _ = image_embeddings.shape
|
| 121 |
+
image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
|
| 122 |
+
image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 123 |
+
|
| 124 |
+
# get unconditional embeddings for classifier free guidance
|
| 125 |
+
if do_classifier_free_guidance:
|
| 126 |
+
uncond_images: List[str]
|
| 127 |
+
if negative_prompt is None:
|
| 128 |
+
uncond_images = [np.zeros((512, 512, 3)) + 0.5] * batch_size
|
| 129 |
+
elif type(prompt) is not type(negative_prompt):
|
| 130 |
+
raise TypeError(
|
| 131 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 132 |
+
f" {type(prompt)}."
|
| 133 |
+
)
|
| 134 |
+
elif isinstance(negative_prompt, PIL.Image.Image):
|
| 135 |
+
uncond_images = [negative_prompt]
|
| 136 |
+
elif batch_size != len(negative_prompt):
|
| 137 |
+
raise ValueError(
|
| 138 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 139 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 140 |
+
" the batch size of `prompt`."
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
uncond_images = negative_prompt
|
| 144 |
+
|
| 145 |
+
uncond_images = self.image_feature_extractor(images=uncond_images, return_tensors="pt")
|
| 146 |
+
pixel_values = uncond_images.pixel_values.to(device).to(self.image_encoder.dtype)
|
| 147 |
+
negative_prompt_embeds = self.image_encoder(pixel_values)
|
| 148 |
+
negative_prompt_embeds = normalize_embeddings(negative_prompt_embeds)
|
| 149 |
+
|
| 150 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 151 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 152 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 153 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 154 |
+
|
| 155 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 156 |
+
# Here we concatenate the unconditional and conditional embeddings into a single batch
|
| 157 |
+
# to avoid doing two forward passes
|
| 158 |
+
image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
|
| 159 |
+
|
| 160 |
+
return image_embeddings
|
| 161 |
+
|
| 162 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
| 163 |
+
def decode_latents(self, latents):
|
| 164 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 165 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 166 |
+
|
| 167 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 168 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 169 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 170 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 171 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 172 |
+
return image
|
| 173 |
+
|
| 174 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 175 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 176 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 177 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 178 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 179 |
+
# and should be between [0, 1]
|
| 180 |
+
|
| 181 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 182 |
+
extra_step_kwargs = {}
|
| 183 |
+
if accepts_eta:
|
| 184 |
+
extra_step_kwargs["eta"] = eta
|
| 185 |
+
|
| 186 |
+
# check if the scheduler accepts generator
|
| 187 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 188 |
+
if accepts_generator:
|
| 189 |
+
extra_step_kwargs["generator"] = generator
|
| 190 |
+
return extra_step_kwargs
|
| 191 |
+
|
| 192 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_image_variation.StableDiffusionImageVariationPipeline.check_inputs
|
| 193 |
+
def check_inputs(self, image, height, width, callback_steps):
|
| 194 |
+
if (
|
| 195 |
+
not isinstance(image, torch.Tensor)
|
| 196 |
+
and not isinstance(image, PIL.Image.Image)
|
| 197 |
+
and not isinstance(image, list)
|
| 198 |
+
):
|
| 199 |
+
raise ValueError(
|
| 200 |
+
"`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
|
| 201 |
+
f" {type(image)}"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 205 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 206 |
+
|
| 207 |
+
if (callback_steps is None) or (
|
| 208 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 209 |
+
):
|
| 210 |
+
raise ValueError(
|
| 211 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 212 |
+
f" {type(callback_steps)}."
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 216 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 217 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 218 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 221 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if latents is None:
|
| 225 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 226 |
+
else:
|
| 227 |
+
latents = latents.to(device)
|
| 228 |
+
|
| 229 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 230 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 231 |
+
return latents
|
| 232 |
+
|
| 233 |
+
@torch.no_grad()
|
| 234 |
+
def __call__(
|
| 235 |
+
self,
|
| 236 |
+
image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.Tensor],
|
| 237 |
+
height: Optional[int] = None,
|
| 238 |
+
width: Optional[int] = None,
|
| 239 |
+
num_inference_steps: int = 50,
|
| 240 |
+
guidance_scale: float = 7.5,
|
| 241 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 242 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 243 |
+
eta: float = 0.0,
|
| 244 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 245 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 246 |
+
output_type: Optional[str] = "pil",
|
| 247 |
+
return_dict: bool = True,
|
| 248 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 249 |
+
callback_steps: int = 1,
|
| 250 |
+
**kwargs,
|
| 251 |
+
):
|
| 252 |
+
r"""
|
| 253 |
+
The call function to the pipeline for generation.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
image (`PIL.Image.Image`, `List[PIL.Image.Image]` or `torch.Tensor`):
|
| 257 |
+
The image prompt or prompts to guide the image generation.
|
| 258 |
+
height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 259 |
+
The height in pixels of the generated image.
|
| 260 |
+
width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
|
| 261 |
+
The width in pixels of the generated image.
|
| 262 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 263 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 264 |
+
expense of slower inference.
|
| 265 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 266 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 267 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 268 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 269 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 270 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 271 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 272 |
+
The number of images to generate per prompt.
|
| 273 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 274 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 275 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 276 |
+
generator (`torch.Generator`, *optional*):
|
| 277 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 278 |
+
generation deterministic.
|
| 279 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 280 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 281 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 282 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 283 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 284 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 285 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 286 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 287 |
+
plain tuple.
|
| 288 |
+
callback (`Callable`, *optional*):
|
| 289 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 290 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 291 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 292 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 293 |
+
every step.
|
| 294 |
+
|
| 295 |
+
Examples:
|
| 296 |
+
|
| 297 |
+
```py
|
| 298 |
+
>>> from diffusers import VersatileDiffusionImageVariationPipeline
|
| 299 |
+
>>> import torch
|
| 300 |
+
>>> import requests
|
| 301 |
+
>>> from io import BytesIO
|
| 302 |
+
>>> from PIL import Image
|
| 303 |
+
|
| 304 |
+
>>> # let's download an initial image
|
| 305 |
+
>>> url = "https://huggingface.co/datasets/diffusers/images/resolve/main/benz.jpg"
|
| 306 |
+
|
| 307 |
+
>>> response = requests.get(url)
|
| 308 |
+
>>> image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 309 |
+
|
| 310 |
+
>>> pipe = VersatileDiffusionImageVariationPipeline.from_pretrained(
|
| 311 |
+
... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
|
| 312 |
+
... )
|
| 313 |
+
>>> pipe = pipe.to("cuda")
|
| 314 |
+
|
| 315 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(0)
|
| 316 |
+
>>> image = pipe(image, generator=generator).images[0]
|
| 317 |
+
>>> image.save("./car_variation.png")
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
Returns:
|
| 321 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 322 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 323 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images.
|
| 324 |
+
"""
|
| 325 |
+
# 0. Default height and width to unet
|
| 326 |
+
height = height or self.image_unet.config.sample_size * self.vae_scale_factor
|
| 327 |
+
width = width or self.image_unet.config.sample_size * self.vae_scale_factor
|
| 328 |
+
|
| 329 |
+
# 1. Check inputs. Raise error if not correct
|
| 330 |
+
self.check_inputs(image, height, width, callback_steps)
|
| 331 |
+
|
| 332 |
+
# 2. Define call parameters
|
| 333 |
+
batch_size = 1 if isinstance(image, PIL.Image.Image) else len(image)
|
| 334 |
+
device = self._execution_device
|
| 335 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 336 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 337 |
+
# corresponds to doing no classifier free guidance.
|
| 338 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 339 |
+
|
| 340 |
+
# 3. Encode input prompt
|
| 341 |
+
image_embeddings = self._encode_prompt(
|
| 342 |
+
image, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# 4. Prepare timesteps
|
| 346 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 347 |
+
timesteps = self.scheduler.timesteps
|
| 348 |
+
|
| 349 |
+
# 5. Prepare latent variables
|
| 350 |
+
num_channels_latents = self.image_unet.config.in_channels
|
| 351 |
+
latents = self.prepare_latents(
|
| 352 |
+
batch_size * num_images_per_prompt,
|
| 353 |
+
num_channels_latents,
|
| 354 |
+
height,
|
| 355 |
+
width,
|
| 356 |
+
image_embeddings.dtype,
|
| 357 |
+
device,
|
| 358 |
+
generator,
|
| 359 |
+
latents,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# 6. Prepare extra step kwargs.
|
| 363 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 364 |
+
|
| 365 |
+
# 7. Denoising loop
|
| 366 |
+
for i, t in enumerate(self.progress_bar(timesteps)):
|
| 367 |
+
# expand the latents if we are doing classifier free guidance
|
| 368 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 369 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 370 |
+
|
| 371 |
+
# predict the noise residual
|
| 372 |
+
noise_pred = self.image_unet(latent_model_input, t, encoder_hidden_states=image_embeddings).sample
|
| 373 |
+
|
| 374 |
+
# perform guidance
|
| 375 |
+
if do_classifier_free_guidance:
|
| 376 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 377 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 378 |
+
|
| 379 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 380 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 381 |
+
|
| 382 |
+
# call the callback, if provided
|
| 383 |
+
if callback is not None and i % callback_steps == 0:
|
| 384 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 385 |
+
callback(step_idx, t, latents)
|
| 386 |
+
|
| 387 |
+
if not output_type == "latent":
|
| 388 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 389 |
+
else:
|
| 390 |
+
image = latents
|
| 391 |
+
|
| 392 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 393 |
+
|
| 394 |
+
if not return_dict:
|
| 395 |
+
return (image,)
|
| 396 |
+
|
| 397 |
+
return ImagePipelineOutput(images=image)
|