Skip to content

AutoPipeline

The AutoPipeline is designed to make it easy to load a checkpoint for a task without needing to know the specific pipeline class. Based on the task, the AutoPipeline automatically retrieves the correct pipeline class from the checkpoint model_index.json file.

Tip

Check out the AutoPipeline tutorial to learn how to use this API!

mindone.diffusers.AutoPipelineForText2Image

Bases: ConfigMixin

[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.

This class cannot be instantiated using __init__() (throws an error).

Class attributes:

- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
  diffusion pipeline's components.
Source code in mindone/diffusers/pipelines/auto_pipeline.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
class AutoPipelineForText2Image(ConfigMixin):
    r"""

    [`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.

    This class cannot be instantiated using `__init__()` (throws an error).

    Class attributes:

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

    """

    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
    @validate_hf_hub_args
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a text-to-image MindSpore 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:

        ```
        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:  # noqa: E501
        - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
                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`].
            mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
                Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
                dtype is automatically derived from the model's weights.
            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.

            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.
            token (`str` or *bool*, *optional*):
                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.
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each NPU and the available CPU RAM if unset.
            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`.

        <Tip>

        To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
        `huggingface-cli login`.

        </Tip>

        Examples:

        ```py
        >>> from mindone.diffusers import AutoPipelineForText2Image

        >>> pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> image = pipeline(prompt)[0][0]
        ```
        """
        cache_dir = kwargs.pop("cache_dir", None)
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
        token = kwargs.pop("token", None)
        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,
            "token": token,
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
        orig_class_name = config["_class_name"]

        if "controlnet" in kwargs:
            orig_class_name = config["_class_name"].replace("Pipeline", "ControlNetPipeline")
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                orig_class_name = orig_class_name.replace("Pipeline", "PAGPipeline")

        text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, orig_class_name)

        kwargs = {**load_config_kwargs, **kwargs}
        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 MindSpore 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
        additional memory.

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

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

        ```py
        >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

        >>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
        ...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
        ... )

        >>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i)
        >>> image = pipe_t2i(prompt)[0][0]
        ```
        """

        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)

        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
                to_replace = "PAGPipeline" if "PAG" in text_2_image_cls.__name__ else "Pipeline"
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                    text_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace),
                )
            else:
                text_2_image_cls = _get_task_class(
                    AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                    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", ""),
                )

        # define expected module and optional kwargs given the pipeline signature
        expected_modules, optional_kwargs = text_2_image_cls._get_signature_keys(text_2_image_cls)

        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
        }

        missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(text_2_image_kwargs.keys())

        if len(missing_modules) > 0:
            raise ValueError(
                f"Pipeline {text_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
            )

        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

mindone.diffusers.AutoPipelineForText2Image.from_pipe(pipeline, **kwargs) classmethod

Instantiates a text-to-image MindSpore 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 additional memory.

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

PARAMETER DESCRIPTION
pipeline

an instantiated DiffusionPipeline object

TYPE: `DiffusionPipeline`

>>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

>>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
... )

>>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i)
>>> image = pipe_t2i(prompt)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@classmethod
def from_pipe(cls, pipeline, **kwargs):
    r"""
    Instantiates a text-to-image MindSpore 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
    additional memory.

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

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

    ```py
    >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

    >>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
    ...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
    ... )

    >>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i)
    >>> image = pipe_t2i(prompt)[0][0]
    ```
    """

    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)

    if "controlnet" in kwargs:
        if kwargs["controlnet"] is not None:
            to_replace = "PAGPipeline" if "PAG" in text_2_image_cls.__name__ else "Pipeline"
            text_2_image_cls = _get_task_class(
                AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                text_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace),
            )
        else:
            text_2_image_cls = _get_task_class(
                AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
                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", ""),
            )

    # define expected module and optional kwargs given the pipeline signature
    expected_modules, optional_kwargs = text_2_image_cls._get_signature_keys(text_2_image_cls)

    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
    }

    missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(text_2_image_kwargs.keys())

    if len(missing_modules) > 0:
        raise ValueError(
            f"Pipeline {text_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
        )

    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

mindone.diffusers.AutoPipelineForText2Image.from_pretrained(pretrained_model_or_path, **kwargs) classmethod

Instantiates a text-to-image MindSpore 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:

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:  # noqa: E501
- conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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.
PARAMETER DESCRIPTION
pretrained_model_or_path

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`].

TYPE: `str` or `os.PathLike`, *optional*

mindspore_dtype

Override the default mindspore.dtype and load the model with another dtype. If "auto" is passed, the dtype is automatically derived from the model's weights.

TYPE: `str` or `mindspore.dtype`, *optional*

force_download

Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.

TYPE: `bool`, *optional*, defaults to `False`

cache_dir

Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used.

TYPE: `Union[str, os.PathLike]`, *optional*

proxies

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.

TYPE: `Dict[str, str]`, *optional*

output_loading_info(`bool`,

Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.

TYPE: *optional*, defaults to `False`

local_files_only

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.

TYPE: `bool`, *optional*, defaults to `False`

token

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.

TYPE: `str` or *bool*, *optional*

revision

The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git.

TYPE: `str`, *optional*, defaults to `"main"`

custom_revision

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.

TYPE: `str`, *optional*, defaults to `"main"`

mirror

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.

TYPE: `str`, *optional*

max_memory

A dictionary device identifier for the maximum memory. Will default to the maximum memory available for each NPU and the available CPU RAM if unset.

TYPE: `Dict`, *optional*

use_safetensors

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.

TYPE: `bool`, *optional*, defaults to `None`

kwargs

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.

TYPE: remaining dictionary of keyword arguments, *optional* DEFAULT: {}

variant

Load weights from a specified variant filename such as "fp16" or "ema". This is ignored when loading from_flax.

TYPE: `str`, *optional*

To use private or gated models, log-in with huggingface-cli login.

Examples:

>>> from mindone.diffusers import AutoPipelineForText2Image

>>> pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> image = pipeline(prompt)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
    r"""
    Instantiates a text-to-image MindSpore 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:

    ```
    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:  # noqa: E501
    - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
        pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
            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`].
        mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
            Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
            dtype is automatically derived from the model's weights.
        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.

        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.
        token (`str` or *bool*, *optional*):
            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.
        max_memory (`Dict`, *optional*):
            A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
            each NPU and the available CPU RAM if unset.
        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`.

    <Tip>

    To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
    `huggingface-cli login`.

    </Tip>

    Examples:

    ```py
    >>> from mindone.diffusers import AutoPipelineForText2Image

    >>> pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
    >>> image = pipeline(prompt)[0][0]
    ```
    """
    cache_dir = kwargs.pop("cache_dir", None)
    force_download = kwargs.pop("force_download", False)
    proxies = kwargs.pop("proxies", None)
    token = kwargs.pop("token", None)
    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,
        "token": token,
        "local_files_only": local_files_only,
        "revision": revision,
    }

    config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
    orig_class_name = config["_class_name"]

    if "controlnet" in kwargs:
        orig_class_name = config["_class_name"].replace("Pipeline", "ControlNetPipeline")
    if "enable_pag" in kwargs:
        enable_pag = kwargs.pop("enable_pag")
        if enable_pag:
            orig_class_name = orig_class_name.replace("Pipeline", "PAGPipeline")

    text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, orig_class_name)

    kwargs = {**load_config_kwargs, **kwargs}
    return text_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)

mindone.diffusers.AutoPipelineForImage2Image

Bases: ConfigMixin

[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.

This class cannot be instantiated using __init__() (throws an error).

Class attributes:

- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
  diffusion pipeline's components.
Source code in mindone/diffusers/pipelines/auto_pipeline.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
class AutoPipelineForImage2Image(ConfigMixin):
    r"""

    [`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.

    This class cannot be instantiated using `__init__()` (throws an error).

    Class attributes:

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

    """

    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
    @validate_hf_hub_args
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a image-to-image MindSpore 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.

        If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetImg2ImgPipeline`]
        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:

        ```
        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:  # noqa: E501
        - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
                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`].
            mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
                Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
                dtype is automatically derived from the model's weights.
            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.

            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.
            token (`str` or *bool*, *optional*):
                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.
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each NPU and the available CPU RAM if unset.
            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`.

        <Tip>

        To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
        `huggingface-cli login`.

        </Tip>

        Examples:

        ```py
        >>> from mindone.diffusers import AutoPipelineForImage2Image

        >>> pipeline = AutoPipelineForImage2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> image = pipeline(prompt, image)[0][0]
        ```
        """
        cache_dir = kwargs.pop("cache_dir", None)
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
        token = kwargs.pop("token", None)
        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,
            "token": token,
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
        orig_class_name = config["_class_name"]

        # the `orig_class_name` can be:
        # `- *Pipeline` (for regular text-to-image checkpoint)
        # `- *Img2ImgPipeline` (for refiner checkpoint)
        to_replace = "Img2ImgPipeline" if "Img2Img" in config["_class_name"] else "Pipeline"

        if "controlnet" in kwargs:
            orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)

        image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, orig_class_name)

        kwargs = {**load_config_kwargs, **kwargs}
        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
        additional memory.

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

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

        Examples:

        ```py
        >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

        >>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
        ...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
        ... )

        >>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
        >>> image = pipe_i2i(prompt, image)[0][0]
        ```
        """

        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)

        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
                to_replace = "Img2ImgPipeline"
                if "PAG" in image_2_image_cls.__name__:
                    to_replace = "PAG" + to_replace
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                    image_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace),
                )
            else:
                image_2_image_cls = _get_task_class(
                    AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                    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", ""),
                )

        # define expected module and optional kwargs given the pipeline signature
        expected_modules, optional_kwargs = image_2_image_cls._get_signature_keys(image_2_image_cls)

        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
        }

        missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(image_2_image_kwargs.keys())

        if len(missing_modules) > 0:
            raise ValueError(
                f"Pipeline {image_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
            )

        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

mindone.diffusers.AutoPipelineForImage2Image.from_pipe(pipeline, **kwargs) classmethod

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 additional memory.

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

PARAMETER DESCRIPTION
pipeline

an instantiated DiffusionPipeline object

TYPE: `DiffusionPipeline`

>>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

>>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
... )

>>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
>>> image = pipe_i2i(prompt, image)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
@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
    additional memory.

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

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

    Examples:

    ```py
    >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image

    >>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
    ...     "runwayml/stable-diffusion-v1-5", requires_safety_checker=False
    ... )

    >>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
    >>> image = pipe_i2i(prompt, image)[0][0]
    ```
    """

    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)

    if "controlnet" in kwargs:
        if kwargs["controlnet"] is not None:
            to_replace = "Img2ImgPipeline"
            if "PAG" in image_2_image_cls.__name__:
                to_replace = "PAG" + to_replace
            image_2_image_cls = _get_task_class(
                AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                image_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace),
            )
        else:
            image_2_image_cls = _get_task_class(
                AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
                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", ""),
            )

    # define expected module and optional kwargs given the pipeline signature
    expected_modules, optional_kwargs = image_2_image_cls._get_signature_keys(image_2_image_cls)

    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
    }

    missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(image_2_image_kwargs.keys())

    if len(missing_modules) > 0:
        raise ValueError(
            f"Pipeline {image_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
        )

    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

mindone.diffusers.AutoPipelineForImage2Image.from_pretrained(pretrained_model_or_path, **kwargs) classmethod

Instantiates a image-to-image MindSpore 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.

If a controlnet argument is passed, it will instantiate a [StableDiffusionControlNetImg2ImgPipeline] 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:

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:  # noqa: E501
- conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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.
PARAMETER DESCRIPTION
pretrained_model_or_path

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`].

TYPE: `str` or `os.PathLike`, *optional*

mindspore_dtype

Override the default mindspore.dtype and load the model with another dtype. If "auto" is passed, the dtype is automatically derived from the model's weights.

TYPE: `str` or `mindspore.dtype`, *optional*

force_download

Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.

TYPE: `bool`, *optional*, defaults to `False`

cache_dir

Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used.

TYPE: `Union[str, os.PathLike]`, *optional*

proxies

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.

TYPE: `Dict[str, str]`, *optional*

output_loading_info(`bool`,

Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.

TYPE: *optional*, defaults to `False`

local_files_only

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.

TYPE: `bool`, *optional*, defaults to `False`

token

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.

TYPE: `str` or *bool*, *optional*

revision

The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git.

TYPE: `str`, *optional*, defaults to `"main"`

custom_revision

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.

TYPE: `str`, *optional*, defaults to `"main"`

mirror

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.

TYPE: `str`, *optional*

max_memory

A dictionary device identifier for the maximum memory. Will default to the maximum memory available for each NPU and the available CPU RAM if unset.

TYPE: `Dict`, *optional*

use_safetensors

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.

TYPE: `bool`, *optional*, defaults to `None`

kwargs

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.

TYPE: remaining dictionary of keyword arguments, *optional* DEFAULT: {}

variant

Load weights from a specified variant filename such as "fp16" or "ema". This is ignored when loading from_flax.

TYPE: `str`, *optional*

To use private or gated models, log-in with huggingface-cli login.

Examples:

>>> from mindone.diffusers import AutoPipelineForImage2Image

>>> pipeline = AutoPipelineForImage2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> image = pipeline(prompt, image)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
    r"""
    Instantiates a image-to-image MindSpore 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.

    If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetImg2ImgPipeline`]
    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:

    ```
    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:  # noqa: E501
    - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
        pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
            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`].
        mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
            Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
            dtype is automatically derived from the model's weights.
        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.

        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.
        token (`str` or *bool*, *optional*):
            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.
        max_memory (`Dict`, *optional*):
            A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
            each NPU and the available CPU RAM if unset.
        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`.

    <Tip>

    To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
    `huggingface-cli login`.

    </Tip>

    Examples:

    ```py
    >>> from mindone.diffusers import AutoPipelineForImage2Image

    >>> pipeline = AutoPipelineForImage2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
    >>> image = pipeline(prompt, image)[0][0]
    ```
    """
    cache_dir = kwargs.pop("cache_dir", None)
    force_download = kwargs.pop("force_download", False)
    proxies = kwargs.pop("proxies", None)
    token = kwargs.pop("token", None)
    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,
        "token": token,
        "local_files_only": local_files_only,
        "revision": revision,
    }

    config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
    orig_class_name = config["_class_name"]

    # the `orig_class_name` can be:
    # `- *Pipeline` (for regular text-to-image checkpoint)
    # `- *Img2ImgPipeline` (for refiner checkpoint)
    to_replace = "Img2ImgPipeline" if "Img2Img" in config["_class_name"] else "Pipeline"

    if "controlnet" in kwargs:
        orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
    if "enable_pag" in kwargs:
        enable_pag = kwargs.pop("enable_pag")
        if enable_pag:
            orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)

    image_2_image_cls = _get_task_class(AUTO_IMAGE2IMAGE_PIPELINES_MAPPING, orig_class_name)

    kwargs = {**load_config_kwargs, **kwargs}
    return image_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs)

mindone.diffusers.AutoPipelineForInpainting

Bases: ConfigMixin

[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.

This class cannot be instantiated using __init__() (throws an error).

Class attributes:

- **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
  diffusion pipeline's components.
Source code in mindone/diffusers/pipelines/auto_pipeline.py
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 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
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 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
class AutoPipelineForInpainting(ConfigMixin):
    r"""

    [`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.

    This class cannot be instantiated using `__init__()` (throws an error).

    Class attributes:

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

    """

    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
    @validate_hf_hub_args
    def from_pretrained(cls, pretrained_model_or_path, **kwargs):
        r"""
        Instantiates a inpainting MindSpore 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.

        If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetInpaintPipeline`]
        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:

        ```
        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:  # noqa: E501
        - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
            pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
                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`].
            mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
                Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
                dtype is automatically derived from the model's weights.
            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.

            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.
            token (`str` or *bool*, *optional*):
                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.
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each NPU and the available CPU RAM if unset.
            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`.

        <Tip>

        To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
        `huggingface-cli login`.

        </Tip>

        Examples:

        ```py
        >>> from mindone.diffusers import AutoPipelineForInpainting

        >>> pipeline = AutoPipelineForInpainting.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> image = pipeline(prompt, image=init_image, mask_image=mask_image)[0][0]
        ```
        """
        cache_dir = kwargs.pop("cache_dir", None)
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
        token = kwargs.pop("token", None)
        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,
            "token": token,
            "local_files_only": local_files_only,
            "revision": revision,
        }

        config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
        orig_class_name = config["_class_name"]

        # The `orig_class_name`` can be:
        # `- *InpaintPipeline` (for inpaint-specific checkpoint)
        #  - or *Pipeline (for regular text-to-image checkpoint)
        to_replace = "InpaintPipeline" if "Inpaint" in config["_class_name"] else "Pipeline"

        if "controlnet" in kwargs:
            orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
        if "enable_pag" in kwargs:
            enable_pag = kwargs.pop("enable_pag")
            if enable_pag:
                orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)
        inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, orig_class_name)

        kwargs = {**load_config_kwargs, **kwargs}
        return inpainting_cls.from_pretrained(pretrained_model_or_path, **kwargs)

    @classmethod
    def from_pipe(cls, pipeline, **kwargs):
        r"""
        Instantiates a inpainting MindSpore 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
        additional memory.

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

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

        Examples:

        ```py
        >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting

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

        >>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
        >>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image)[0][0]
        ```
        """
        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)

        if "controlnet" in kwargs:
            if kwargs["controlnet"] is not None:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
                    inpainting_cls.__name__.replace("ControlNet", "").replace(
                        "InpaintPipeline", "ControlNetInpaintPipeline"
                    ),
                )
            else:
                inpainting_cls = _get_task_class(
                    AUTO_INPAINT_PIPELINES_MAPPING,
                    inpainting_cls.__name__.replace("ControlNetInpaintPipeline", "InpaintPipeline"),
                )

        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"),
                )

        # define expected module and optional kwargs given the pipeline signature
        expected_modules, optional_kwargs = inpainting_cls._get_signature_keys(inpainting_cls)

        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
        }

        missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(inpainting_kwargs.keys())

        if len(missing_modules) > 0:
            raise ValueError(
                f"Pipeline {inpainting_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
            )

        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

mindone.diffusers.AutoPipelineForInpainting.from_pipe(pipeline, **kwargs) classmethod

Instantiates a inpainting MindSpore 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 additional memory.

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

PARAMETER DESCRIPTION
pipeline

an instantiated DiffusionPipeline object

TYPE: `DiffusionPipeline`

>>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting

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

>>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
>>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 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
@classmethod
def from_pipe(cls, pipeline, **kwargs):
    r"""
    Instantiates a inpainting MindSpore 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
    additional memory.

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

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

    Examples:

    ```py
    >>> from mindone.diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting

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

    >>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
    >>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image)[0][0]
    ```
    """
    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)

    if "controlnet" in kwargs:
        if kwargs["controlnet"] is not None:
            inpainting_cls = _get_task_class(
                AUTO_INPAINT_PIPELINES_MAPPING,
                inpainting_cls.__name__.replace("ControlNet", "").replace(
                    "InpaintPipeline", "ControlNetInpaintPipeline"
                ),
            )
        else:
            inpainting_cls = _get_task_class(
                AUTO_INPAINT_PIPELINES_MAPPING,
                inpainting_cls.__name__.replace("ControlNetInpaintPipeline", "InpaintPipeline"),
            )

    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"),
            )

    # define expected module and optional kwargs given the pipeline signature
    expected_modules, optional_kwargs = inpainting_cls._get_signature_keys(inpainting_cls)

    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
    }

    missing_modules = set(expected_modules) - set(pipeline._optional_components) - set(inpainting_kwargs.keys())

    if len(missing_modules) > 0:
        raise ValueError(
            f"Pipeline {inpainting_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"  # noqa: E501
        )

    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

mindone.diffusers.AutoPipelineForInpainting.from_pretrained(pretrained_model_or_path, **kwargs) classmethod

Instantiates a inpainting MindSpore 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.

If a controlnet argument is passed, it will instantiate a [StableDiffusionControlNetInpaintPipeline] 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:

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:  # noqa: E501
- conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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.
PARAMETER DESCRIPTION
pretrained_model_or_path

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`].

TYPE: `str` or `os.PathLike`, *optional*

mindspore_dtype

Override the default mindspore.dtype and load the model with another dtype. If "auto" is passed, the dtype is automatically derived from the model's weights.

TYPE: `str` or `mindspore.dtype`, *optional*

force_download

Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.

TYPE: `bool`, *optional*, defaults to `False`

cache_dir

Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used.

TYPE: `Union[str, os.PathLike]`, *optional*

proxies

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.

TYPE: `Dict[str, str]`, *optional*

output_loading_info(`bool`,

Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.

TYPE: *optional*, defaults to `False`

local_files_only

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.

TYPE: `bool`, *optional*, defaults to `False`

token

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.

TYPE: `str` or *bool*, *optional*

revision

The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git.

TYPE: `str`, *optional*, defaults to `"main"`

custom_revision

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.

TYPE: `str`, *optional*, defaults to `"main"`

mirror

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.

TYPE: `str`, *optional*

max_memory

A dictionary device identifier for the maximum memory. Will default to the maximum memory available for each NPU and the available CPU RAM if unset.

TYPE: `Dict`, *optional*

use_safetensors

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.

TYPE: `bool`, *optional*, defaults to `None`

kwargs

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.

TYPE: remaining dictionary of keyword arguments, *optional* DEFAULT: {}

variant

Load weights from a specified variant filename such as "fp16" or "ema". This is ignored when loading from_flax.

TYPE: `str`, *optional*

To use private or gated models, log-in with huggingface-cli login.

Examples:

>>> from mindone.diffusers import AutoPipelineForInpainting

>>> pipeline = AutoPipelineForInpainting.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> image = pipeline(prompt, image=init_image, mask_image=mask_image)[0][0]
Source code in mindone/diffusers/pipelines/auto_pipeline.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
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
895
896
897
898
899
900
901
902
903
904
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
    r"""
    Instantiates a inpainting MindSpore 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.

    If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetInpaintPipeline`]
    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:

    ```
    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:  # noqa: E501
    - conv_in.weight: found shape [320, 4, 3, 3] in the checkpoint and [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:
        pretrained_model_or_path (`str` or `os.PathLike`, *optional*):
            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`].
        mindspore_dtype (`str` or `mindspore.dtype`, *optional*):
            Override the default `mindspore.dtype` and load the model with another dtype. If "auto" is passed, the
            dtype is automatically derived from the model's weights.
        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.

        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.
        token (`str` or *bool*, *optional*):
            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.
        max_memory (`Dict`, *optional*):
            A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
            each NPU and the available CPU RAM if unset.
        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`.

    <Tip>

    To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
    `huggingface-cli login`.

    </Tip>

    Examples:

    ```py
    >>> from mindone.diffusers import AutoPipelineForInpainting

    >>> pipeline = AutoPipelineForInpainting.from_pretrained("runwayml/stable-diffusion-v1-5")
    >>> image = pipeline(prompt, image=init_image, mask_image=mask_image)[0][0]
    ```
    """
    cache_dir = kwargs.pop("cache_dir", None)
    force_download = kwargs.pop("force_download", False)
    proxies = kwargs.pop("proxies", None)
    token = kwargs.pop("token", None)
    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,
        "token": token,
        "local_files_only": local_files_only,
        "revision": revision,
    }

    config = cls.load_config(pretrained_model_or_path, **load_config_kwargs)
    orig_class_name = config["_class_name"]

    # The `orig_class_name`` can be:
    # `- *InpaintPipeline` (for inpaint-specific checkpoint)
    #  - or *Pipeline (for regular text-to-image checkpoint)
    to_replace = "InpaintPipeline" if "Inpaint" in config["_class_name"] else "Pipeline"

    if "controlnet" in kwargs:
        orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
    if "enable_pag" in kwargs:
        enable_pag = kwargs.pop("enable_pag")
        if enable_pag:
            orig_class_name = orig_class_name.replace(to_replace, "PAG" + to_replace)
    inpainting_cls = _get_task_class(AUTO_INPAINT_PIPELINES_MAPPING, orig_class_name)

    kwargs = {**load_config_kwargs, **kwargs}
    return inpainting_cls.from_pretrained(pretrained_model_or_path, **kwargs)