auto_pipeline.py 58.2 KB
Newer Older
YiYi Xu's avatar
YiYi Xu committed
1
# coding=utf-8
2
# Copyright 2025 The HuggingFace Inc. team.
YiYi Xu's avatar
YiYi Xu committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from collections import OrderedDict

18
19
from huggingface_hub.utils import validate_hf_hub_args

YiYi Xu's avatar
YiYi Xu committed
20
from ..configuration_utils import ConfigMixin
21
from ..models.controlnets import ControlNetUnionModel
22
from ..utils import is_sentencepiece_available
23
from .aura_flow import AuraFlowPipeline
Edna's avatar
Edna committed
24
from .chroma import ChromaPipeline
Yuxuan.Zhang's avatar
Yuxuan.Zhang committed
25
from .cogview3 import CogView3PlusPipeline
Yuxuan Zhang's avatar
Yuxuan Zhang committed
26
from .cogview4 import CogView4ControlPipeline, CogView4Pipeline
YiYi Xu's avatar
YiYi Xu committed
27
28
29
30
from .controlnet import (
    StableDiffusionControlNetImg2ImgPipeline,
    StableDiffusionControlNetInpaintPipeline,
    StableDiffusionControlNetPipeline,
31
    StableDiffusionXLControlNetImg2ImgPipeline,
32
    StableDiffusionXLControlNetInpaintPipeline,
YiYi Xu's avatar
YiYi Xu committed
33
    StableDiffusionXLControlNetPipeline,
34
35
36
    StableDiffusionXLControlNetUnionImg2ImgPipeline,
    StableDiffusionXLControlNetUnionInpaintPipeline,
    StableDiffusionXLControlNetUnionPipeline,
YiYi Xu's avatar
YiYi Xu committed
37
)
38
39
40
41
from .controlnet_sd3 import (
    StableDiffusion3ControlNetInpaintingPipeline,
    StableDiffusion3ControlNetPipeline,
)
YiYi Xu's avatar
YiYi Xu committed
42
from .deepfloyd_if import IFImg2ImgPipeline, IFInpaintingPipeline, IFPipeline
43
from .flux import (
44
45
    FluxControlImg2ImgPipeline,
    FluxControlInpaintPipeline,
46
47
48
    FluxControlNetImg2ImgPipeline,
    FluxControlNetInpaintPipeline,
    FluxControlNetPipeline,
49
    FluxControlPipeline,
50
51
    FluxImg2ImgPipeline,
    FluxInpaintPipeline,
jlonge4's avatar
jlonge4 committed
52
    FluxKontextPipeline,
53
54
    FluxPipeline,
)
55
from .hunyuandit import HunyuanDiTPipeline
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from .kandinsky import (
    KandinskyCombinedPipeline,
    KandinskyImg2ImgCombinedPipeline,
    KandinskyImg2ImgPipeline,
    KandinskyInpaintCombinedPipeline,
    KandinskyInpaintPipeline,
    KandinskyPipeline,
)
from .kandinsky2_2 import (
    KandinskyV22CombinedPipeline,
    KandinskyV22Img2ImgCombinedPipeline,
    KandinskyV22Img2ImgPipeline,
    KandinskyV22InpaintCombinedPipeline,
    KandinskyV22InpaintPipeline,
    KandinskyV22Pipeline,
)
72
from .kandinsky3 import Kandinsky3Img2ImgPipeline, Kandinsky3Pipeline
73
from .latent_consistency_models import LatentConsistencyModelImg2ImgPipeline, LatentConsistencyModelPipeline
74
75
from .lumina import LuminaPipeline
from .lumina2 import Lumina2Pipeline
YiYi Xu's avatar
YiYi Xu committed
76
from .pag import (
77
    HunyuanDiTPAGPipeline,
78
    PixArtSigmaPAGPipeline,
79
    SanaPAGPipeline,
80
    StableDiffusion3PAGImg2ImgPipeline,
81
    StableDiffusion3PAGPipeline,
82
    StableDiffusionControlNetPAGInpaintPipeline,
83
    StableDiffusionControlNetPAGPipeline,
84
    StableDiffusionPAGImg2ImgPipeline,
85
    StableDiffusionPAGInpaintPipeline,
86
    StableDiffusionPAGPipeline,
87
    StableDiffusionXLControlNetPAGImg2ImgPipeline,
YiYi Xu's avatar
YiYi Xu committed
88
89
90
91
92
    StableDiffusionXLControlNetPAGPipeline,
    StableDiffusionXLPAGImg2ImgPipeline,
    StableDiffusionXLPAGInpaintPipeline,
    StableDiffusionXLPAGPipeline,
)
93
from .pixart_alpha import PixArtAlphaPipeline, PixArtSigmaPipeline
YiYi Xu's avatar
YiYi Xu committed
94
95
96
97
from .qwenimage import (
    QwenImageControlNetPipeline,
    QwenImageEditInpaintPipeline,
    QwenImageEditPipeline,
98
    QwenImageEditPlusPipeline,
YiYi Xu's avatar
YiYi Xu committed
99
100
101
102
    QwenImageImg2ImgPipeline,
    QwenImageInpaintPipeline,
    QwenImagePipeline,
)
103
from .sana import SanaPipeline
104
from .stable_cascade import StableCascadeCombinedPipeline, StableCascadeDecoderPipeline
YiYi Xu's avatar
YiYi Xu committed
105
106
107
108
109
from .stable_diffusion import (
    StableDiffusionImg2ImgPipeline,
    StableDiffusionInpaintPipeline,
    StableDiffusionPipeline,
)
110
111
from .stable_diffusion_3 import (
    StableDiffusion3Img2ImgPipeline,
112
    StableDiffusion3InpaintPipeline,
113
114
    StableDiffusion3Pipeline,
)
YiYi Xu's avatar
YiYi Xu committed
115
116
117
118
119
from .stable_diffusion_xl import (
    StableDiffusionXLImg2ImgPipeline,
    StableDiffusionXLInpaintPipeline,
    StableDiffusionXLPipeline,
)
YiYi Xu's avatar
YiYi Xu committed
120
from .wan import WanImageToVideoPipeline, WanPipeline, WanVideoToVideoPipeline
Kashif Rasul's avatar
Kashif Rasul committed
121
from .wuerstchen import WuerstchenCombinedPipeline, WuerstchenDecoderPipeline
122
from .z_image import ZImageImg2ImgPipeline, ZImagePipeline
YiYi Xu's avatar
YiYi Xu committed
123
124
125
126
127
128


AUTO_TEXT2IMAGE_PIPELINES_MAPPING = OrderedDict(
    [
        ("stable-diffusion", StableDiffusionPipeline),
        ("stable-diffusion-xl", StableDiffusionXLPipeline),
129
        ("stable-diffusion-3", StableDiffusion3Pipeline),
130
        ("stable-diffusion-3-pag", StableDiffusion3PAGPipeline),
YiYi Xu's avatar
YiYi Xu committed
131
        ("if", IFPipeline),
132
        ("hunyuan", HunyuanDiTPipeline),
133
        ("hunyuan-pag", HunyuanDiTPAGPipeline),
134
135
        ("kandinsky", KandinskyCombinedPipeline),
        ("kandinsky22", KandinskyV22CombinedPipeline),
136
        ("kandinsky3", Kandinsky3Pipeline),
YiYi Xu's avatar
YiYi Xu committed
137
138
        ("stable-diffusion-controlnet", StableDiffusionControlNetPipeline),
        ("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetPipeline),
139
        ("stable-diffusion-xl-controlnet-union", StableDiffusionXLControlNetUnionPipeline),
140
        ("stable-diffusion-3-controlnet", StableDiffusion3ControlNetPipeline),
Kashif Rasul's avatar
Kashif Rasul committed
141
        ("wuerstchen", WuerstchenCombinedPipeline),
142
        ("cascade", StableCascadeCombinedPipeline),
143
        ("lcm", LatentConsistencyModelPipeline),
144
145
        ("pixart-alpha", PixArtAlphaPipeline),
        ("pixart-sigma", PixArtSigmaPipeline),
146
147
        ("sana", SanaPipeline),
        ("sana-pag", SanaPAGPipeline),
148
        ("stable-diffusion-pag", StableDiffusionPAGPipeline),
149
        ("stable-diffusion-controlnet-pag", StableDiffusionControlNetPAGPipeline),
YiYi Xu's avatar
YiYi Xu committed
150
151
        ("stable-diffusion-xl-pag", StableDiffusionXLPAGPipeline),
        ("stable-diffusion-xl-controlnet-pag", StableDiffusionXLControlNetPAGPipeline),
152
        ("pixart-sigma-pag", PixArtSigmaPAGPipeline),
153
        ("auraflow", AuraFlowPipeline),
Sayak Paul's avatar
Sayak Paul committed
154
        ("flux", FluxPipeline),
155
        ("flux-control", FluxControlPipeline),
156
        ("flux-controlnet", FluxControlNetPipeline),
jlonge4's avatar
jlonge4 committed
157
        ("flux-kontext", FluxKontextPipeline),
158
159
        ("lumina", LuminaPipeline),
        ("lumina2", Lumina2Pipeline),
Edna's avatar
Edna committed
160
        ("chroma", ChromaPipeline),
Yuxuan.Zhang's avatar
Yuxuan.Zhang committed
161
        ("cogview3", CogView3PlusPipeline),
162
        ("cogview4", CogView4Pipeline),
Yuxuan Zhang's avatar
Yuxuan Zhang committed
163
        ("cogview4-control", CogView4ControlPipeline),
YiYi Xu's avatar
YiYi Xu committed
164
165
        ("qwenimage", QwenImagePipeline),
        ("qwenimage-controlnet", QwenImageControlNetPipeline),
166
        ("z-image", ZImagePipeline),
YiYi Xu's avatar
YiYi Xu committed
167
168
169
170
171
172
173
    ]
)

AUTO_IMAGE2IMAGE_PIPELINES_MAPPING = OrderedDict(
    [
        ("stable-diffusion", StableDiffusionImg2ImgPipeline),
        ("stable-diffusion-xl", StableDiffusionXLImg2ImgPipeline),
174
        ("stable-diffusion-3", StableDiffusion3Img2ImgPipeline),
175
        ("stable-diffusion-3-pag", StableDiffusion3PAGImg2ImgPipeline),
YiYi Xu's avatar
YiYi Xu committed
176
        ("if", IFImg2ImgPipeline),
177
178
        ("kandinsky", KandinskyImg2ImgCombinedPipeline),
        ("kandinsky22", KandinskyV22Img2ImgCombinedPipeline),
179
        ("kandinsky3", Kandinsky3Img2ImgPipeline),
YiYi Xu's avatar
YiYi Xu committed
180
        ("stable-diffusion-controlnet", StableDiffusionControlNetImg2ImgPipeline),
181
        ("stable-diffusion-pag", StableDiffusionPAGImg2ImgPipeline),
182
        ("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetImg2ImgPipeline),
183
        ("stable-diffusion-xl-controlnet-union", StableDiffusionXLControlNetUnionImg2ImgPipeline),
YiYi Xu's avatar
YiYi Xu committed
184
        ("stable-diffusion-xl-pag", StableDiffusionXLPAGImg2ImgPipeline),
185
        ("stable-diffusion-xl-controlnet-pag", StableDiffusionXLControlNetPAGImg2ImgPipeline),
186
        ("lcm", LatentConsistencyModelImg2ImgPipeline),
187
        ("flux", FluxImg2ImgPipeline),
188
        ("flux-controlnet", FluxControlNetImg2ImgPipeline),
189
        ("flux-control", FluxControlImg2ImgPipeline),
jlonge4's avatar
jlonge4 committed
190
        ("flux-kontext", FluxKontextPipeline),
YiYi Xu's avatar
YiYi Xu committed
191
192
        ("qwenimage", QwenImageImg2ImgPipeline),
        ("qwenimage-edit", QwenImageEditPipeline),
193
        ("qwenimage-edit-plus", QwenImageEditPlusPipeline),
194
        ("z-image", ZImageImg2ImgPipeline),
YiYi Xu's avatar
YiYi Xu committed
195
196
197
198
199
200
201
    ]
)

AUTO_INPAINT_PIPELINES_MAPPING = OrderedDict(
    [
        ("stable-diffusion", StableDiffusionInpaintPipeline),
        ("stable-diffusion-xl", StableDiffusionXLInpaintPipeline),
202
        ("stable-diffusion-3", StableDiffusion3InpaintPipeline),
YiYi Xu's avatar
YiYi Xu committed
203
        ("if", IFInpaintingPipeline),
204
205
206
        ("kandinsky", KandinskyInpaintCombinedPipeline),
        ("kandinsky22", KandinskyV22InpaintCombinedPipeline),
        ("stable-diffusion-controlnet", StableDiffusionControlNetInpaintPipeline),
207
        ("stable-diffusion-controlnet-pag", StableDiffusionControlNetPAGInpaintPipeline),
208
        ("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetInpaintPipeline),
209
        ("stable-diffusion-xl-controlnet-union", StableDiffusionXLControlNetUnionInpaintPipeline),
210
        ("stable-diffusion-3-controlnet", StableDiffusion3ControlNetInpaintingPipeline),
YiYi Xu's avatar
YiYi Xu committed
211
        ("stable-diffusion-xl-pag", StableDiffusionXLPAGInpaintPipeline),
212
        ("flux", FluxInpaintPipeline),
213
        ("flux-controlnet", FluxControlNetInpaintPipeline),
214
        ("flux-control", FluxControlInpaintPipeline),
215
        ("stable-diffusion-pag", StableDiffusionPAGInpaintPipeline),
YiYi Xu's avatar
YiYi Xu committed
216
217
        ("qwenimage", QwenImageInpaintPipeline),
        ("qwenimage-edit", QwenImageEditInpaintPipeline),
218
219
220
    ]
)

YiYi Xu's avatar
YiYi Xu committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
AUTO_TEXT2VIDEO_PIPELINES_MAPPING = OrderedDict(
    [
        ("wan", WanPipeline),
    ]
)

AUTO_IMAGE2VIDEO_PIPELINES_MAPPING = OrderedDict(
    [
        ("wan", WanImageToVideoPipeline),
    ]
)

AUTO_VIDEO2VIDEO_PIPELINES_MAPPING = OrderedDict(
    [
        ("wan", WanVideoToVideoPipeline),
    ]
)

239
240
241
242
_AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING = OrderedDict(
    [
        ("kandinsky", KandinskyPipeline),
        ("kandinsky22", KandinskyV22Pipeline),
Kashif Rasul's avatar
Kashif Rasul committed
243
        ("wuerstchen", WuerstchenDecoderPipeline),
244
        ("cascade", StableCascadeDecoderPipeline),
245
246
247
248
249
250
251
252
253
254
    ]
)
_AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING = OrderedDict(
    [
        ("kandinsky", KandinskyImg2ImgPipeline),
        ("kandinsky22", KandinskyV22Img2ImgPipeline),
    ]
)
_AUTO_INPAINT_DECODER_PIPELINES_MAPPING = OrderedDict(
    [
YiYi Xu's avatar
YiYi Xu committed
255
256
257
258
259
        ("kandinsky", KandinskyInpaintPipeline),
        ("kandinsky22", KandinskyV22InpaintPipeline),
    ]
)

260
if is_sentencepiece_available():
261
    from .kolors import KolorsImg2ImgPipeline, KolorsPipeline
Álvaro Somoza's avatar
Álvaro Somoza committed
262
    from .pag import KolorsPAGPipeline
263
264

    AUTO_TEXT2IMAGE_PIPELINES_MAPPING["kolors"] = KolorsPipeline
Álvaro Somoza's avatar
Álvaro Somoza committed
265
    AUTO_TEXT2IMAGE_PIPELINES_MAPPING["kolors-pag"] = KolorsPAGPipeline
266
    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING["kolors"] = KolorsImg2ImgPipeline
267

YiYi Xu's avatar
YiYi Xu committed
268
269
270
271
SUPPORTED_TASKS_MAPPINGS = [
    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
    AUTO_INPAINT_PIPELINES_MAPPING,
YiYi Xu's avatar
YiYi Xu committed
272
273
274
    AUTO_TEXT2VIDEO_PIPELINES_MAPPING,
    AUTO_IMAGE2VIDEO_PIPELINES_MAPPING,
    AUTO_VIDEO2VIDEO_PIPELINES_MAPPING,
275
276
277
    _AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING,
    _AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING,
    _AUTO_INPAINT_DECODER_PIPELINES_MAPPING,
YiYi Xu's avatar
YiYi Xu committed
278
279
280
]


281
282
283
284
285
286
287
288
289
290
291
292
293
294
def _get_connected_pipeline(pipeline_cls):
    # for now connected pipelines can only be loaded from decoder pipelines, such as kandinsky-community/kandinsky-2-2-decoder
    if pipeline_cls in _AUTO_TEXT2IMAGE_DECODER_PIPELINES_MAPPING.values():
        return _get_task_class(
            AUTO_TEXT2IMAGE_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False
        )
    if pipeline_cls in _AUTO_IMAGE2IMAGE_DECODER_PIPELINES_MAPPING.values():
        return _get_task_class(
            AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False
        )
    if pipeline_cls in _AUTO_INPAINT_DECODER_PIPELINES_MAPPING.values():
        return _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, pipeline_cls.__name__, throw_error_if_not_exist=False)


YiYi Xu's avatar
YiYi Xu committed
295
296
297
298
299
300
def _get_model(pipeline_class_name):
    for task_mapping in SUPPORTED_TASKS_MAPPINGS:
        for model_name, pipeline in task_mapping.items():
            if pipeline.__name__ == pipeline_class_name:
                return model_name

YiYi Xu's avatar
YiYi Xu committed
301

YiYi Xu's avatar
YiYi Xu committed
302
303
def _get_task_class(mapping, pipeline_class_name, throw_error_if_not_exist: bool = True):
    model_name = _get_model(pipeline_class_name)
YiYi Xu's avatar
YiYi Xu committed
304
305
306
307
308

    if model_name is not None:
        task_class = mapping.get(model_name, None)
        if task_class is not None:
            return task_class
309
310
311

    if throw_error_if_not_exist:
        raise ValueError(f"AutoPipeline can't find a pipeline linked to {pipeline_class_name} for {model_name}")
YiYi Xu's avatar
YiYi Xu committed
312
313
314
315
316


class AutoPipelineForText2Image(ConfigMixin):
    r"""

317
318
319
    [`AutoPipelineForText2Image`] is a generic pipeline class that instantiates a text-to-image pipeline class. The
    specific underlying pipeline class is automatically selected from either the
    [`~AutoPipelineForText2Image.from_pretrained`] or [`~AutoPipelineForText2Image.from_pipe`] methods.
YiYi Xu's avatar
YiYi Xu committed
320

321
    This class cannot be instantiated using `__init__()` (throws an error).
YiYi Xu's avatar
YiYi Xu committed
322
323
324
325
326
327
328

    Class attributes:

        - **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
          diffusion pipeline's components.

    """
329

YiYi Xu's avatar
YiYi Xu committed
330
331
332
333
334
335
336
337
338
339
    config_name = "model_index.json"

    def __init__(self, *args, **kwargs):
        raise EnvironmentError(
            f"{self.__class__.__name__} is designed to be instantiated "
            f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
            f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
        )

    @classmethod
340
    @validate_hf_hub_args
YiYi Xu's avatar
YiYi Xu committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a text-to-image Pytorch diffusion pipeline from pretrained pipeline weight.

        The from_pretrained() method takes care of returning the correct pipeline class instance by:
            1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
               config object
            2. Find the text-to-image pipeline linked to the pipeline class using pattern matching on pipeline class
               name.

        If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetPipeline`] object.

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```
358
        Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
YiYi Xu's avatar
YiYi Xu committed
359
360
361
362
363
        - 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
        You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
        ```

        Parameters:
364
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
YiYi Xu's avatar
YiYi Xu committed
365
366
367
368
369
370
371
                Can be either:

                    - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                      hosted on the Hub.
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
                      saved using
                    [`~DiffusionPipeline.save_pretrained`].
372
373
            torch_dtype (`torch.dtype`, *optional*):
                Override the default `torch.dtype` and load the model with another dtype.
YiYi Xu's avatar
YiYi Xu committed
374
375
376
377
378
379
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
380

YiYi Xu's avatar
YiYi Xu committed
381
382
383
384
385
386
387
388
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
389
            token (`str` or *bool*, *optional*):
YiYi Xu's avatar
YiYi Xu committed
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            custom_revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
                `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
                custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
                A map that specifies where each submodule should go. It doesn’t need to be defined for each
                parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
                same device.

                Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
                more information about each option see [designing a device
                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each GPU and the available CPU RAM if unset.
            offload_folder (`str` or `os.PathLike`, *optional*):
                The path to offload weights if device_map contains the value `"disk"`.
            offload_state_dict (`bool`, *optional*):
                If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
                the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
                when there is some disk offload.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
                Speed up model loading only loading the pretrained weights and not initializing the weights. This also
                tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
                Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
                argument to `True` will raise an error.
            use_safetensors (`bool`, *optional*, defaults to `None`):
                If set to `None`, the safetensors weights are downloaded if they're available **and** if the
                safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
                weights. If set to `False`, safetensors weights are not loaded.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
                class). The overwritten components are passed directly to the pipelines `__init__` method. See example
                below for more information.
            variant (`str`, *optional*):
                Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.

Steven Liu's avatar
Steven Liu committed
437
438
        > [!TIP] > To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in
        with `hf > auth login`.
YiYi Xu's avatar
YiYi Xu committed
439
440
441
442

        Examples:

        ```py
443
        >>> from diffusers import AutoPipelineForText2Image
YiYi Xu's avatar
YiYi Xu committed
444

445
        >>> pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
446
        >>> image = pipeline(prompt).images[0]
YiYi Xu's avatar
YiYi Xu committed
447
448
        ```
        """
449
        cache_dir = kwargs.pop("cache_dir", None)
450
451
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
452
        token = kwargs.pop("token", None)
453
454
455
456
457
458
459
        local_files_only = kwargs.pop("local_files_only", False)
        revision = kwargs.pop("revision", None)

        load_config_kwargs = {
            "cache_dir": cache_dir,
            "force_download": force_download,
            "proxies": proxies,
460
            "token": token,
461
462
463
464
465
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
YiYi Xu's avatar
YiYi Xu committed
466
        orig_class_name = config["_class_name"]
467
468
469
470
        if "ControlPipeline" in orig_class_name:
            to_replace = "ControlPipeline"
        else:
            to_replace = "Pipeline"
YiYi Xu's avatar
YiYi Xu committed
471
472

        if "controlnet" in kwargs:
473
            if isinstance(kwargs["controlnet"], ControlNetUnionModel):
474
                orig_class_name = config["_class_name"].replace(to_replace, "ControlNetUnionPipeline")
475
            else:
476
                orig_class_name = config["_class_name"].replace(to_replace, "ControlNetPipeline")
YiYi Xu's avatar
YiYi Xu committed
477
478
479
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
480
                orig_class_name = orig_class_name.replace(to_replace, "PAGPipeline")
YiYi Xu's avatar
YiYi Xu committed
481
482
483

        text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, orig_class_name)

484
        kwargs = {**load_config_kwargs, **kwargs}
YiYi Xu's avatar
YiYi Xu committed
485
486
487
488
489
490
491
492
493
494
495
        return text_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)

    @classmethod
    def from_pipe(cls, pipeline, **kwargs):
        r"""
        Instantiates a text-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.

        The from_pipe() method takes care of returning the correct pipeline class instance by finding the text-to-image
        pipeline linked to the pipeline class using pattern matching on pipeline class name.

        All the modules the pipeline contains will be used to initialize the new pipeline without reallocating
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
496
        additional memory.
YiYi Xu's avatar
YiYi Xu committed
497
498
499
500
501
502
503
504

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pipeline (`DiffusionPipeline`):
                an instantiated `DiffusionPipeline` object

        ```py
505
        >>> from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
YiYi Xu's avatar
YiYi Xu committed
506
507

        >>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
508
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5", requires_safety_checker=False
YiYi Xu's avatar
YiYi Xu committed
509
510
        ... )

511
512
        >>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i)
        >>> image = pipe_t2i(prompt).images[0]
YiYi Xu's avatar
YiYi Xu committed
513
514
515
516
517
518
519
520
521
        ```
        """

        original_config = dict(pipeline.config)
        original_cls_name = pipeline.__class__.__name__

        # derive the pipeline class to instantiate
        text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, original_cls_name)

522
523
        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
YiYi Xu's avatar
YiYi Xu committed
524
                to_replace = "PAGPipeline" if "PAG" in text_2_image_cls.__name__ else "Pipeline"
525
526
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
YiYi Xu's avatar
YiYi Xu committed
527
                    text_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace),
528
529
530
531
                )
            else:
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
YiYi Xu's avatar
YiYi Xu committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
                    text_2_image_cls.__name__.replace("ControlNet", ""),
                )

        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                    text_2_image_cls.__name__.replace("PAG", "").replace("Pipeline", "PAGPipeline"),
                )
            else:
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                    text_2_image_cls.__name__.replace("PAG", ""),
546
547
                )

YiYi Xu's avatar
YiYi Xu committed
548
        # define expected module and optional kwargs given the pipeline signature
549
        expected_modules, optional_kwargs = text_2_image_cls._get_signature_keys(text_2_image_cls)
YiYi Xu's avatar
YiYi Xu committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

        pretrained_model_name_or_path = original_config.pop("_name_or_path", None)

        # allow users pass modules in `kwargs` to override the original pipeline's components
        passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
        original_class_obj = {
            k: pipeline.components[k]
            for k, v in pipeline.components.items()
            if k in expected_modules and k not in passed_class_obj
        }

        # allow users pass optional kwargs to override the original pipelines config attribute
        passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
        original_pipe_kwargs = {
            k: original_config[k]
            for k, v in original_config.items()
            if k in optional_kwargs and k not in passed_pipe_kwargs
        }

        # config that were not expected by original pipeline is stored as private attribute
        # we will pass them as optional arguments if they can be accepted by the pipeline
        additional_pipe_kwargs = [
            k[1:]
            for k in original_config.keys()
            if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
        ]
        for k in additional_pipe_kwargs:
            original_pipe_kwargs[k] = original_config.pop(f"_{k}")

        text_2_image_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}

        # store unused config as private attribute
        unused_original_config = {
            f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
            for k, v in original_config.items()
            if k not in text_2_image_kwargs
        }

588
589
590
        missing_modules = (
            set(expected_modules) - set(text_2_image_cls._optional_components) - set(text_2_image_kwargs.keys())
        )
YiYi Xu's avatar
YiYi Xu committed
591
592
593

        if len(missing_modules) > 0:
            raise ValueError(
594
                f"Pipeline {text_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
YiYi Xu's avatar
YiYi Xu committed
595
596
597
598
599
600
601
602
603
604
605
606
            )

        model = text_2_image_cls(**text_2_image_kwargs)
        model.register_to_config(_name_or_path=pretrained_model_name_or_path)
        model.register_to_config(**unused_original_config)

        return model


class AutoPipelineForImage2Image(ConfigMixin):
    r"""

607
608
609
    [`AutoPipelineForImage2Image`] is a generic pipeline class that instantiates an image-to-image pipeline class. The
    specific underlying pipeline class is automatically selected from either the
    [`~AutoPipelineForImage2Image.from_pretrained`] or [`~AutoPipelineForImage2Image.from_pipe`] methods.
YiYi Xu's avatar
YiYi Xu committed
610

611
    This class cannot be instantiated using `__init__()` (throws an error).
YiYi Xu's avatar
YiYi Xu committed
612
613
614
615
616
617
618

    Class attributes:

        - **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
          diffusion pipeline's components.

    """
619

YiYi Xu's avatar
YiYi Xu committed
620
621
622
623
624
625
626
627
628
629
    config_name = "model_index.json"

    def __init__(self, *args, **kwargs):
        raise EnvironmentError(
            f"{self.__class__.__name__} is designed to be instantiated "
            f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
            f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
        )

    @classmethod
630
    @validate_hf_hub_args
YiYi Xu's avatar
YiYi Xu committed
631
632
633
634
635
636
637
638
639
640
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a image-to-image Pytorch diffusion pipeline from pretrained pipeline weight.

        The from_pretrained() method takes care of returning the correct pipeline class instance by:
            1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
               config object
            2. Find the image-to-image pipeline linked to the pipeline class using pattern matching on pipeline class
               name.

641
642
        If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetImg2ImgPipeline`]
        object.
YiYi Xu's avatar
YiYi Xu committed
643
644
645
646
647
648

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```
649
        Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
YiYi Xu's avatar
YiYi Xu committed
650
651
652
653
654
        - 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
        You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
        ```

        Parameters:
655
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
YiYi Xu's avatar
YiYi Xu committed
656
657
658
659
660
661
662
663
                Can be either:

                    - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                      hosted on the Hub.
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
                      saved using
                    [`~DiffusionPipeline.save_pretrained`].
            torch_dtype (`str` or `torch.dtype`, *optional*):
664
                Override the default `torch.dtype` and load the model with another dtype.
YiYi Xu's avatar
YiYi Xu committed
665
666
667
668
669
670
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
671

YiYi Xu's avatar
YiYi Xu committed
672
673
674
675
676
677
678
679
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
680
            token (`str` or *bool*, *optional*):
YiYi Xu's avatar
YiYi Xu committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            custom_revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
                `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
                custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
                A map that specifies where each submodule should go. It doesn’t need to be defined for each
                parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
                same device.

                Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
                more information about each option see [designing a device
                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each GPU and the available CPU RAM if unset.
            offload_folder (`str` or `os.PathLike`, *optional*):
                The path to offload weights if device_map contains the value `"disk"`.
            offload_state_dict (`bool`, *optional*):
                If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
                the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
                when there is some disk offload.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
                Speed up model loading only loading the pretrained weights and not initializing the weights. This also
                tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
                Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
                argument to `True` will raise an error.
            use_safetensors (`bool`, *optional*, defaults to `None`):
                If set to `None`, the safetensors weights are downloaded if they're available **and** if the
                safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
                weights. If set to `False`, safetensors weights are not loaded.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
                class). The overwritten components are passed directly to the pipelines `__init__` method. See example
                below for more information.
            variant (`str`, *optional*):
                Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.

Steven Liu's avatar
Steven Liu committed
728
729
        > [!TIP] > To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in
        with `hf > auth login`.
YiYi Xu's avatar
YiYi Xu committed
730
731
732
733

        Examples:

        ```py
734
        >>> from diffusers import AutoPipelineForImage2Image
YiYi Xu's avatar
YiYi Xu committed
735

736
        >>> pipeline = AutoPipelineForImage2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
737
        >>> image = pipeline(prompt, image).images[0]
YiYi Xu's avatar
YiYi Xu committed
738
739
        ```
        """
740
        cache_dir = kwargs.pop("cache_dir", None)
741
742
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
743
        token = kwargs.pop("token", None)
744
745
746
747
748
749
750
        local_files_only = kwargs.pop("local_files_only", False)
        revision = kwargs.pop("revision", None)

        load_config_kwargs = {
            "cache_dir": cache_dir,
            "force_download": force_download,
            "proxies": proxies,
751
            "token": token,
752
753
754
755
756
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
YiYi Xu's avatar
YiYi Xu committed
757
758
        orig_class_name = config["_class_name"]

759
760
        # the `orig_class_name` can be:
        # `- *Pipeline` (for regular text-to-image checkpoint)
761
        #  - `*ControlPipeline` (for Flux tools specific checkpoint)
762
        # `- *Img2ImgPipeline` (for refiner checkpoint)
763
764
765
766
767
768
        if "Img2Img" in orig_class_name:
            to_replace = "Img2ImgPipeline"
        elif "ControlPipeline" in orig_class_name:
            to_replace = "ControlPipeline"
        else:
            to_replace = "Pipeline"
769

YiYi Xu's avatar
YiYi Xu committed
770
        if "controlnet" in kwargs:
771
772
773
774
            if isinstance(kwargs["controlnet"], ControlNetUnionModel):
                orig_class_name = orig_class_name.replace(to_replace, "ControlNetUnion" + to_replace)
            else:
                orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
YiYi Xu's avatar
YiYi Xu committed
775
776
777
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
778
                orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)
YiYi Xu's avatar
YiYi Xu committed
779

780
781
782
        if to_replace == "ControlPipeline":
            orig_class_name = orig_class_name.replace(to_replace, "ControlImg2ImgPipeline")

YiYi Xu's avatar
YiYi Xu committed
783
784
        image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, orig_class_name)

785
        kwargs = {**load_config_kwargs, **kwargs}
YiYi Xu's avatar
YiYi Xu committed
786
787
788
789
790
791
792
793
794
795
796
        return image_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)

    @classmethod
    def from_pipe(cls, pipeline, **kwargs):
        r"""
        Instantiates a image-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.

        The from_pipe() method takes care of returning the correct pipeline class instance by finding the
        image-to-image pipeline linked to the pipeline class using pattern matching on pipeline class name.

        All the modules the pipeline contains will be used to initialize the new pipeline without reallocating
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
797
        additional memory.
YiYi Xu's avatar
YiYi Xu committed
798
799
800
801
802
803
804
805
806
807

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pipeline (`DiffusionPipeline`):
                an instantiated `DiffusionPipeline` object

        Examples:

        ```py
808
        >>> from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
YiYi Xu's avatar
YiYi Xu committed
809
810

        >>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
811
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5", requires_safety_checker=False
YiYi Xu's avatar
YiYi Xu committed
812
813
        ... )

814
815
        >>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
        >>> image = pipe_i2i(prompt, image).images[0]
YiYi Xu's avatar
YiYi Xu committed
816
817
818
819
820
821
822
823
824
        ```
        """

        original_config = dict(pipeline.config)
        original_cls_name = pipeline.__class__.__name__

        # derive the pipeline class to instantiate
        image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, original_cls_name)

825
826
        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
YiYi Xu's avatar
YiYi Xu committed
827
828
829
                to_replace = "Img2ImgPipeline"
                if "PAG" in image_2_image_cls.__name__:
                    to_replace = "PAG" + to_replace
830
831
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
832
                    image_2_image_cls.__name__.replace("ControlNet", "").replace(
YiYi Xu's avatar
YiYi Xu committed
833
                        to_replace, "ControlNet" + to_replace
834
                    ),
835
836
837
838
                )
            else:
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
YiYi Xu's avatar
YiYi Xu committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                    image_2_image_cls.__name__.replace("ControlNet", ""),
                )

        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                    image_2_image_cls.__name__.replace("PAG", "").replace("Img2ImgPipeline", "PAGImg2ImgPipeline"),
                )
            else:
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                    image_2_image_cls.__name__.replace("PAG", ""),
853
854
                )

YiYi Xu's avatar
YiYi Xu committed
855
        # define expected module and optional kwargs given the pipeline signature
856
        expected_modules, optional_kwargs = image_2_image_cls._get_signature_keys(image_2_image_cls)
YiYi Xu's avatar
YiYi Xu committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894

        pretrained_model_name_or_path = original_config.pop("_name_or_path", None)

        # allow users pass modules in `kwargs` to override the original pipeline's components
        passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
        original_class_obj = {
            k: pipeline.components[k]
            for k, v in pipeline.components.items()
            if k in expected_modules and k not in passed_class_obj
        }

        # allow users pass optional kwargs to override the original pipelines config attribute
        passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
        original_pipe_kwargs = {
            k: original_config[k]
            for k, v in original_config.items()
            if k in optional_kwargs and k not in passed_pipe_kwargs
        }

        # config attribute that were not expected by original pipeline is stored as its private attribute
        # we will pass them as optional arguments if they can be accepted by the pipeline
        additional_pipe_kwargs = [
            k[1:]
            for k in original_config.keys()
            if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
        ]
        for k in additional_pipe_kwargs:
            original_pipe_kwargs[k] = original_config.pop(f"_{k}")

        image_2_image_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}

        # store unused config as private attribute
        unused_original_config = {
            f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
            for k, v in original_config.items()
            if k not in image_2_image_kwargs
        }

895
896
897
        missing_modules = (
            set(expected_modules) - set(image_2_image_cls._optional_components) - set(image_2_image_kwargs.keys())
        )
YiYi Xu's avatar
YiYi Xu committed
898
899
900

        if len(missing_modules) > 0:
            raise ValueError(
901
                f"Pipeline {image_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
YiYi Xu's avatar
YiYi Xu committed
902
903
904
905
906
907
908
909
910
911
912
913
            )

        model = image_2_image_cls(**image_2_image_kwargs)
        model.register_to_config(_name_or_path=pretrained_model_name_or_path)
        model.register_to_config(**unused_original_config)

        return model


class AutoPipelineForInpainting(ConfigMixin):
    r"""

914
915
916
    [`AutoPipelineForInpainting`] is a generic pipeline class that instantiates an inpainting pipeline class. The
    specific underlying pipeline class is automatically selected from either the
    [`~AutoPipelineForInpainting.from_pretrained`] or [`~AutoPipelineForInpainting.from_pipe`] methods.
YiYi Xu's avatar
YiYi Xu committed
917

918
    This class cannot be instantiated using `__init__()` (throws an error).
YiYi Xu's avatar
YiYi Xu committed
919
920
921
922
923
924
925

    Class attributes:

        - **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
          diffusion pipeline's components.

    """
926

YiYi Xu's avatar
YiYi Xu committed
927
928
929
930
931
932
933
934
935
936
    config_name = "model_index.json"

    def __init__(self, *args, **kwargs):
        raise EnvironmentError(
            f"{self.__class__.__name__} is designed to be instantiated "
            f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
            f"`{self.__class__.__name__}.from_pipe(pipeline)` methods."
        )

    @classmethod
937
    @validate_hf_hub_args
YiYi Xu's avatar
YiYi Xu committed
938
939
940
941
942
943
944
945
946
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a inpainting Pytorch diffusion pipeline from pretrained pipeline weight.

        The from_pretrained() method takes care of returning the correct pipeline class instance by:
            1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
               config object
            2. Find the inpainting pipeline linked to the pipeline class using pattern matching on pipeline class name.

947
948
        If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetInpaintPipeline`]
        object.
YiYi Xu's avatar
YiYi Xu committed
949
950
951
952
953
954

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```
955
        Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
YiYi Xu's avatar
YiYi Xu committed
956
957
958
959
960
        - 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
        You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
        ```

        Parameters:
961
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
YiYi Xu's avatar
YiYi Xu committed
962
963
964
965
966
967
968
969
                Can be either:

                    - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                      hosted on the Hub.
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
                      saved using
                    [`~DiffusionPipeline.save_pretrained`].
            torch_dtype (`str` or `torch.dtype`, *optional*):
970
                Override the default `torch.dtype` and load the model with another dtype.
YiYi Xu's avatar
YiYi Xu committed
971
972
973
974
975
976
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
977

YiYi Xu's avatar
YiYi Xu committed
978
979
980
981
982
983
984
985
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
986
            token (`str` or *bool*, *optional*):
YiYi Xu's avatar
YiYi Xu committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            custom_revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
                `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
                custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
                A map that specifies where each submodule should go. It doesn’t need to be defined for each
                parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
                same device.

                Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
                more information about each option see [designing a device
                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each GPU and the available CPU RAM if unset.
            offload_folder (`str` or `os.PathLike`, *optional*):
                The path to offload weights if device_map contains the value `"disk"`.
            offload_state_dict (`bool`, *optional*):
                If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
                the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
                when there is some disk offload.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
                Speed up model loading only loading the pretrained weights and not initializing the weights. This also
                tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
                Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
                argument to `True` will raise an error.
            use_safetensors (`bool`, *optional*, defaults to `None`):
                If set to `None`, the safetensors weights are downloaded if they're available **and** if the
                safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
                weights. If set to `False`, safetensors weights are not loaded.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
                class). The overwritten components are passed directly to the pipelines `__init__` method. See example
                below for more information.
            variant (`str`, *optional*):
                Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.

Steven Liu's avatar
Steven Liu committed
1034
1035
        > [!TIP] > To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in
        with `hf > auth login`.
YiYi Xu's avatar
YiYi Xu committed
1036
1037
1038
1039

        Examples:

        ```py
1040
        >>> from diffusers import AutoPipelineForInpainting
YiYi Xu's avatar
YiYi Xu committed
1041

1042
        >>> pipeline = AutoPipelineForInpainting.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
1043
        >>> image = pipeline(prompt, image=init_image, mask_image=mask_image).images[0]
YiYi Xu's avatar
YiYi Xu committed
1044
1045
        ```
        """
1046
        cache_dir = kwargs.pop("cache_dir", None)
1047
1048
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
1049
        token = kwargs.pop("token", None)
1050
1051
1052
1053
1054
1055
1056
        local_files_only = kwargs.pop("local_files_only", False)
        revision = kwargs.pop("revision", None)

        load_config_kwargs = {
            "cache_dir": cache_dir,
            "force_download": force_download,
            "proxies": proxies,
1057
            "token": token,
1058
1059
1060
1061
1062
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
YiYi Xu's avatar
YiYi Xu committed
1063
1064
        orig_class_name = config["_class_name"]

1065
1066
        # The `orig_class_name`` can be:
        # `- *InpaintPipeline` (for inpaint-specific checkpoint)
1067
        #  - `*ControlPipeline` (for Flux tools specific checkpoint)
1068
        #  - or *Pipeline (for regular text-to-image checkpoint)
1069
1070
1071
1072
1073
1074
        if "Inpaint" in orig_class_name:
            to_replace = "InpaintPipeline"
        elif "ControlPipeline" in orig_class_name:
            to_replace = "ControlPipeline"
        else:
            to_replace = "Pipeline"
1075

YiYi Xu's avatar
YiYi Xu committed
1076
        if "controlnet" in kwargs:
1077
1078
1079
1080
            if isinstance(kwargs["controlnet"], ControlNetUnionModel):
                orig_class_name = orig_class_name.replace(to_replace, "ControlNetUnion" + to_replace)
            else:
                orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
YiYi Xu's avatar
YiYi Xu committed
1081
1082
1083
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
1084
                orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)
1085
1086
        if to_replace == "ControlPipeline":
            orig_class_name = orig_class_name.replace(to_replace, "ControlInpaintPipeline")
YiYi Xu's avatar
YiYi Xu committed
1087
1088
        inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, orig_class_name)

1089
        kwargs = {**load_config_kwargs, **kwargs}
YiYi Xu's avatar
YiYi Xu committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
        return inpainting_cls.from_pretrained(pretrained_model_or_path, **kwargs)

    @classmethod
    def from_pipe(cls, pipeline, **kwargs):
        r"""
        Instantiates a inpainting Pytorch diffusion pipeline from another instantiated diffusion pipeline class.

        The from_pipe() method takes care of returning the correct pipeline class instance by finding the inpainting
        pipeline linked to the pipeline class using pattern matching on pipeline class name.

        All the modules the pipeline class contain will be used to initialize the new pipeline without reallocating
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
1101
        additional memory.
YiYi Xu's avatar
YiYi Xu committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111

        The pipeline is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pipeline (`DiffusionPipeline`):
                an instantiated `DiffusionPipeline` object

        Examples:

        ```py
1112
        >>> from diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting
YiYi Xu's avatar
YiYi Xu committed
1113
1114
1115
1116
1117
1118

        >>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
        ...     "DeepFloyd/IF-I-XL-v1.0", requires_safety_checker=False
        ... )

        >>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
1119
        >>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image).images[0]
YiYi Xu's avatar
YiYi Xu committed
1120
1121
1122
1123
1124
1125
1126
1127
        ```
        """
        original_config = dict(pipeline.config)
        original_cls_name = pipeline.__class__.__name__

        # derive the pipeline class to instantiate
        inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, original_cls_name)

1128
1129
1130
1131
        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
1132
1133
1134
                    inpainting_cls.__name__.replace("ControlNet", "").replace(
                        "InpaintPipeline", "ControlNetInpaintPipeline"
                    ),
1135
1136
1137
1138
1139
1140
1141
                )
            else:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
                    inpainting_cls.__name__.replace("ControlNetInpaintPipeline", "InpaintPipeline"),
                )

YiYi Xu's avatar
YiYi Xu committed
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
                    inpainting_cls.__name__.replace("PAG", "").replace("InpaintPipeline", "PAGInpaintPipeline"),
                )
            else:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
                    inpainting_cls.__name__.replace("PAGInpaintPipeline", "InpaintPipeline"),
                )

YiYi Xu's avatar
YiYi Xu committed
1155
        # define expected module and optional kwargs given the pipeline signature
1156
        expected_modules, optional_kwargs = inpainting_cls._get_signature_keys(inpainting_cls)
YiYi Xu's avatar
YiYi Xu committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194

        pretrained_model_name_or_path = original_config.pop("_name_or_path", None)

        # allow users pass modules in `kwargs` to override the original pipeline's components
        passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
        original_class_obj = {
            k: pipeline.components[k]
            for k, v in pipeline.components.items()
            if k in expected_modules and k not in passed_class_obj
        }

        # allow users pass optional kwargs to override the original pipelines config attribute
        passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
        original_pipe_kwargs = {
            k: original_config[k]
            for k, v in original_config.items()
            if k in optional_kwargs and k not in passed_pipe_kwargs
        }

        # config that were not expected by original pipeline is stored as private attribute
        # we will pass them as optional arguments if they can be accepted by the pipeline
        additional_pipe_kwargs = [
            k[1:]
            for k in original_config.keys()
            if k.startswith("_") and k[1:] in optional_kwargs and k[1:] not in passed_pipe_kwargs
        ]
        for k in additional_pipe_kwargs:
            original_pipe_kwargs[k] = original_config.pop(f"_{k}")

        inpainting_kwargs = {**passed_class_obj, **original_class_obj, **passed_pipe_kwargs, **original_pipe_kwargs}

        # store unused config as private attribute
        unused_original_config = {
            f"{'' if k.startswith('_') else '_'}{k}": original_config[k]
            for k, v in original_config.items()
            if k not in inpainting_kwargs
        }

1195
1196
1197
        missing_modules = (
            set(expected_modules) - set(inpainting_cls._optional_components) - set(inpainting_kwargs.keys())
        )
YiYi Xu's avatar
YiYi Xu committed
1198
1199
1200

        if len(missing_modules) > 0:
            raise ValueError(
1201
                f"Pipeline {inpainting_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
YiYi Xu's avatar
YiYi Xu committed
1202
1203
1204
1205
1206
1207
1208
            )

        model = inpainting_cls(**inpainting_kwargs)
        model.register_to_config(_name_or_path=pretrained_model_name_or_path)
        model.register_to_config(**unused_original_config)

        return model