Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Loading

A core premise of the diffusers library is to make diffusion models as accessible as possible. Accessibility is therefore achieved by providing an API to load complete diffusion pipelines as well as individual components with a single line of code.

In the following we explain in-detail how to easily load:

Loading pipelines

The DiffusionPipeline class is the easiest way to access any diffusion model that is available on the Hub. Let’s look at an example on how to download CompVis’ Latent Diffusion model.

from diffusers import DiffusionPipeline

repo_id = "CompVis/ldm-text2im-large-256"
ldm = DiffusionPipeline.from_pretrained(repo_id)

Here DiffusionPipeline automatically detects the correct pipeline (i.e. LDMTextToImagePipeline), downloads and caches all required configuration and weight files (if not already done so), and finally returns a pipeline instance, called ldm. The pipeline instance can then be called using LDMTextToImagePipeline.call() (i.e., ldm("image of a astronaut riding a horse")) for text-to-image generation.

Instead of using the generic DiffusionPipeline class for loading, you can also load the appropriate pipeline class directly. The code snippet above yields the same instance as when doing:

from diffusers import LDMTextToImagePipeline

repo_id = "CompVis/ldm-text2im-large-256"
ldm = LDMTextToImagePipeline.from_pretrained(repo_id)

Diffusion pipelines like LDMTextToImagePipeline often consist of multiple components. These components can be both parameterized models, such as "unet", "vqvae" and “bert”, tokenizers or schedulers. These components can interact in complex ways with each other when using the pipeline in inference, e.g. for LDMTextToImagePipeline or StableDiffusionPipeline the inference call is explained here. The purpose of the pipeline classes is to wrap the complexity of these diffusion systems and give the user an easy-to-use API while staying flexible for customization, as will be shown later.

Loading pipelines that require access request

Due to the capabilities of diffusion models to generate extremely realistic images, there is a certain danger that such models might be misused for unwanted applications, e.g. generating pornography or violent images. In order to minimize the possibility of such unsolicited use cases, some of the most powerful diffusion models require users to acknowledge a license before being able to use the model. If the user does not agree to the license, the pipeline cannot be downloaded. If you try to load runwayml/stable-diffusion-v1-5 the same way as done previously:

from diffusers import DiffusionPipeline

repo_id = "runwayml/stable-diffusion-v1-5"
stable_diffusion = DiffusionPipeline.from_pretrained(repo_id)

it will only work if you have both click-accepted the license on the model card and are logged into the Hugging Face Hub. Otherwise you will get an error message such as the following:

OSError: runwayml/stable-diffusion-v1-5 is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `use_auth_token` or log in with `huggingface-cli login`

Therefore, we need to make sure to click-accept the license. You can do this by simply visiting the model card and clicking on “Agree and access repository”:



Second, you need to login with your access token:

huggingface-cli login

before trying to load the model. Or alternatively, you can pass your access token directly via the flag use_auth_token. In this case you do not need to run huggingface-cli login before:

from diffusers import DiffusionPipeline

repo_id = "runwayml/stable-diffusion-v1-5"
stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, use_auth_token="<your-access-token>")

The final option to use pipelines that require access without having to rely on the Hugging Face Hub is to load the pipeline locally as explained in the next section.

Loading pipelines locally

If you prefer to have complete control over the pipeline and its corresponding files or, as said before, if you want to use pipelines that require an access request without having to be connected to the Hugging Face Hub, we recommend loading pipelines locally.

To load a diffusion pipeline locally, you first need to manually download the whole folder structure on your local disk and then pass a local path to the DiffusionPipeline.from_pretrained(). Let’s again look at an example for CompVis’ Latent Diffusion model.

First, you should make use of git-lfs to download the whole folder structure that has been uploaded to the model repository:

git lfs install
git clone https://huggingface.co/runwayml/stable-diffusion-v1-5

The command above will create a local folder called ./stable-diffusion-v1-5 on your disk. Now, all you have to do is to simply pass the local folder path to from_pretrained:

from diffusers import DiffusionPipeline

repo_id = "./stable-diffusion-v1-5"
stable_diffusion = DiffusionPipeline.from_pretrained(repo_id)

If repo_id is a local path, as it is the case here, DiffusionPipeline.from_pretrained() will automatically detect it and therefore not try to download any files from the Hub. While we usually recommend to load weights directly from the Hub to be certain to stay up to date with the newest changes, loading pipelines locally should be preferred if one wants to stay anonymous, self-contained applications, etc…

Loading customized pipelines

Advanced users that want to load customized versions of diffusion pipelines can do so by swapping any of the default components, e.g. the scheduler, with other scheduler classes. A classical use case of this functionality is to swap the scheduler. Stable Diffusion v1-5 uses the PNDMScheduler by default which is generally not the most performant scheduler. Since the release of stable diffusion, multiple improved schedulers have been published. To use those, the user has to manually load their preferred scheduler and pass it into DiffusionPipeline.from_pretrained().

E.g. to use EulerDiscreteScheduler or DPMSolverMultistepScheduler to have a better quality vs. generation speed trade-off for inference, one could load them as follows:

from diffusers import DiffusionPipeline, EulerDiscreteScheduler, DPMSolverMultistepScheduler

repo_id = "runwayml/stable-diffusion-v1-5"

scheduler = EulerDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
# or
# scheduler = DPMSolverMultistepScheduler.from_pretrained(repo_id, subfolder="scheduler")

stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, scheduler=scheduler)

Three things are worth paying attention to here.

Not only the scheduler components can be customized for diffusion pipelines; in theory, all components of a pipeline can be customized. In practice, however, it often only makes sense to switch out a component that has compatible alternatives to what the pipeline expects. Many scheduler classes are compatible with each other as can be seen here. This is not always the case for other components, such as the "unet".

One special case that can also be customized is the "safety_checker" of stable diffusion. If you believe the safety checker doesn’t serve you any good, you can simply disable it by passing None:

from diffusers import DiffusionPipeline, EulerDiscreteScheduler, DPMSolverMultistepScheduler

stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, safety_checker=None)

Another common use case is to reuse the same components in multiple pipelines, e.g. the weights and configurations of "runwayml/stable-diffusion-v1-5" can be used for both StableDiffusionPipeline and StableDiffusionImg2ImgPipeline and we might not want to use the exact same weights into RAM twice. In this case, customizing all the input instances would help us to only load the weights into RAM once:

from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline

model_id = "runwayml/stable-diffusion-v1-5"
stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id)

components = stable_diffusion_txt2img.components

# weights are not reloaded into RAM
stable_diffusion_img2img = StableDiffusionImg2ImgPipeline(**components)

Note how the above code snippet makes use of DiffusionPipeline.components.

How does loading work?

As a class method, DiffusionPipeline.from_pretrained() is responsible for two things:

  • Download the latest version of the folder structure required to run the repo_id with diffusers and cache them. If the latest folder structure is available in the local cache, DiffusionPipeline.from_pretrained() will simply reuse the cache and not re-download the files.
  • Load the cached weights into the correct pipeline class – one of the officially supported pipeline classes - and return an instance of the class. The correct pipeline class is thereby retrieved from the model_index.json file.

The underlying folder structure of diffusion pipelines correspond 1-to-1 to their corresponding class instances, e.g. LDMTextToImagePipeline for CompVis/ldm-text2im-large-256 This can be understood better by looking at an example. Let’s print out pipeline class instance pipeline we just defined:

from diffusers import DiffusionPipeline

repo_id = "CompVis/ldm-text2im-large-256"
ldm = DiffusionPipeline.from_pretrained(repo_id)
print(ldm)

Output:

LDMTextToImagePipeline {
  "bert": [
    "latent_diffusion",
    "LDMBertModel"
  ],
  "scheduler": [
    "diffusers",
    "DDIMScheduler"
  ],
  "tokenizer": [
    "transformers",
    "BertTokenizer"
  ],
  "unet": [
    "diffusers",
    "UNet2DConditionModel"
  ],
  "vqvae": [
    "diffusers",
    "AutoencoderKL"
  ]
}

First, we see that the official pipeline is the LDMTextToImagePipeline, and second we see that the LDMTextToImagePipeline consists of 5 components:

Let’s now compare the pipeline instance to the folder structure of the model repository CompVis/ldm-text2im-large-256. Looking at the folder structure of CompVis/ldm-text2im-large-256 on the Hub, we can see it matches 1-to-1 the printed out instance of LDMTextToImagePipeline above:

.
├── bert
│   ├── config.json
│   └── pytorch_model.bin
├── model_index.json
├── scheduler
│   └── scheduler_config.json
├── tokenizer
│   ├── special_tokens_map.json
│   ├── tokenizer_config.json
│   └── vocab.txt
├── unet
│   ├── config.json
│   └── diffusion_pytorch_model.bin
└── vqvae
    ├── config.json
    └── diffusion_pytorch_model.bin

As we can see each attribute of the instance of LDMTextToImagePipeline has its configuration and possibly weights defined in a subfolder that is called exactly like the class attribute ("bert", "scheduler", "tokenizer", "unet", "vqvae"). Importantly, every pipeline expects a model_index.json file that tells the DiffusionPipeline both:

  • which pipeline class should be loaded, and
  • what sub-classes from which library are stored in which subfolders

In the case of CompVis/ldm-text2im-large-256 the model_index.json is therefore defined as follows:

{
  "_class_name": "LDMTextToImagePipeline",
  "_diffusers_version": "0.0.4",
  "bert": [
    "latent_diffusion",
    "LDMBertModel"
  ],
  "scheduler": [
    "diffusers",
    "DDIMScheduler"
  ],
  "tokenizer": [
    "transformers",
    "BertTokenizer"
  ],
  "unet": [
    "diffusers",
    "UNet2DConditionModel"
  ],
  "vqvae": [
    "diffusers",
    "AutoencoderKL"
  ]
}
  • _class_name tells DiffusionPipeline which pipeline class should be loaded.
  • _diffusers_version can be useful to know under which diffusers version this model was created.
  • Every component of the pipeline is then defined under the form:
"name" : [
  "library",
  "class"
]
  • The "name" field corresponds both to the name of the subfolder in which the configuration and weights are stored as well as the attribute name of the pipeline class (as can be seen here and here
  • The "library" field corresponds to the name of the library, e.g. diffusers or transformers from which the "class" should be loaded
  • The "class" field corresponds to the name of the class, e.g. BertTokenizer or UNet2DConditionModel

Loading models

Models as defined under src/diffusers/models can be loaded via the ModelMixin.from_pretrained() function. The API is very similar the DiffusionPipeline.from_pretrained() and works in the same way:

  • Download the latest version of the model weights and configuration with diffusers and cache them. If the latest files are available in the local cache, ModelMixin.from_pretrained() will simply reuse the cache and not re-download the files.
  • Load the cached weights into the defined model class - one of the existing model classes - and return an instance of the class.

In constrast to DiffusionPipeline.from_pretrained(), models rely on fewer files that usually don’t require a folder structure, but just a diffusion_pytorch_model.bin and config.json file.

Let’s look at an example:

from diffusers import UNet2DConditionModel

repo_id = "CompVis/ldm-text2im-large-256"
model = UNet2DConditionModel.from_pretrained(repo_id, subfolder="unet")

Note how we have to define the subfolder="unet" argument to tell ModelMixin.from_pretrained() that the model weights are located in a subfolder of the repository.

As explained in Loading customized pipelines, one can pass a loaded model to a diffusion pipeline, via DiffusionPipeline.from_pretrained():

from diffusers import DiffusionPipeline

repo_id = "CompVis/ldm-text2im-large-256"
ldm = DiffusionPipeline.from_pretrained(repo_id, unet=model)

If the model files can be found directly at the root level, which is usually only the case for some very simple diffusion models, such as google/ddpm-cifar10-32, we don’t need to pass a subfolder argument:

from diffusers import UNet2DModel

repo_id = "google/ddpm-cifar10-32"
model = UNet2DModel.from_pretrained(repo_id)

Loading schedulers

Schedulers rely on SchedulerMixin.from_pretrained(). Schedulers are not parameterized or trained, but instead purely defined by a configuration file. For consistency, we use the same method name as we do for models or pipelines, but no weights are loaded in this case.

In constrast to pipelines or models, loading schedulers does not consume any significant amount of memory and the same configuration file can often be used for a variety of different schedulers. For example, all of:

are compatible with StableDiffusionPipeline and therefore the same scheduler configuration file can be loaded in any of those classes:

from diffusers import StableDiffusionPipeline
from diffusers import (
    DDPMScheduler,
    DDIMScheduler,
    PNDMScheduler,
    LMSDiscreteScheduler,
    EulerDiscreteScheduler,
    EulerAncestralDiscreteScheduler,
    DPMSolverMultistepScheduler,
)

repo_id = "runwayml/stable-diffusion-v1-5"

ddpm = DDPMScheduler.from_pretrained(repo_id, subfolder="scheduler")
ddim = DDIMScheduler.from_pretrained(repo_id, subfolder="scheduler")
pndm = PNDMScheduler.from_pretrained(repo_id, subfolder="scheduler")
lms = LMSDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
euler_anc = EulerAncestralDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
euler = EulerDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
dpm = DPMSolverMultistepScheduler.from_pretrained(repo_id, subfolder="scheduler")

# replace `dpm` with any of `ddpm`, `ddim`, `pndm`, `lms`, `euler`, `euler_anc`
pipeline = StableDiffusionPipeline.from_pretrained(repo_id, scheduler=dpm)

API

class diffusers.ModelMixin

< >

( )

Base class for all models.

ModelMixin takes care of storing the configuration of the models and handles methods for loading, downloading and saving models.

  • config_name (str) — A filename under which the model should be stored when calling save_pretrained().

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] **kwargs )

Parameters

  • pretrained_model_name_or_path (str or os.PathLike, optional) — Can be either:

    • A string, the model id of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids should have an organization name, like google/ddpm-celebahq-256.
    • A path to a directory containing model weights saved using ~ModelMixin.save_config, e.g., ./my_model_directory/.
  • cache_dir (Union[str, os.PathLike], optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
  • torch_dtype (str or torch.dtype, optional) — Override the default torch.dtype and load the model under this dtype. If "auto" is passed the dtype will be 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.
  • resume_download (bool, optional, defaults to False) — Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists.
  • proxies (Dict[str, str], optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g., {'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 or not to only look at local files (i.e., do not try to download the model).
  • use_auth_token (str or bool, optional) — The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running diffusers-cli login (stored in ~/.huggingface).
  • 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, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.
  • subfolder (str, optional, defaults to "") — In case the relevant files are located inside a subfolder of the model repo (either remote in huggingface.co or downloaded locally), you can specify the folder name here.
  • mirror (str, optional) — Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. Please refer to the mirror site for more information.
  • device_map (str or Dict[str, Union[int, str, torch.device]], optional) — A map that specifies where each submodule should go. It doesn’t need to be refined to each parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the same device.

    To have Accelerate compute the most optimized device_map automatically, set device_map="auto". For more information about each option see designing a device map.

  • low_cpu_mem_usage (bool, optional, defaults to True if torch version >= 1.9.0 else False) — Speed up model loading by not initializing the weights and only loading the pre-trained weights. This also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch, setting this argument to True will raise an error.

Instantiate a pretrained pytorch model from a pre-trained model configuration.

The model is set in evaluation mode by default using model.eval() (Dropout modules are deactivated). To train the model, you should first set it back in training mode with model.train().

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

It is required to be logged in (huggingface-cli login) when you want to use private or gated models.

Activate the special “offline-mode” to use this method in a firewalled environment.

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] is_main_process: bool = True save_function: typing.Callable = <function save at 0x7f17e9e9a820> )

Parameters

  • save_directory (str or os.PathLike) — Directory to which to save. Will be created if it doesn’t exist.
  • is_main_process (bool, optional, defaults to True) — Whether the process calling this is the main process or not. Useful when in distributed training like TPUs and need to call this function on all processes. In this case, set is_main_process=True only on the main process to avoid race conditions.
  • save_function (Callable) — The function to use to save the state dictionary. Useful on distributed training like TPUs when one need to replace torch.save by another method.

Save a model and its configuration file to a directory, so that it can be re-loaded using the [from_pretrained()](/docs/diffusers/v0.9.0/en/using-diffusers/loading#diffusers.ModelMixin.from_pretrained) class method.

class diffusers.DiffusionPipeline

< >

( )

Base class for all models.

DiffusionPipeline takes care of storing all components (models, schedulers, processors) for diffusion pipelines and handles methods for loading, downloading and saving models as well as a few methods common to all pipelines to:

  • move all PyTorch modules to the device of your choice
  • enabling/disabling the progress bar for the denoising iteration

Class attributes:

  • config_name (str) — name of the config file that will store the class and module names of all components of the diffusion pipeline.
  • _optional_components (Liststr) — list of all components that are optional so they don’t have to be passed for the pipeline to function (should be overridden by subclasses).

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] **kwargs )

Parameters

  • pretrained_model_name_or_path (str or os.PathLike, optional) — Can be either:

    • A string, the repo id of a pretrained pipeline hosted inside a model repo on https://huggingface.co/ Valid repo ids have to be located under a user or organization name, like CompVis/ldm-text2im-large-256.
    • A path to a directory containing pipeline weights saved using save_pretrained(), e.g., ./my_pipeline_directory/.
  • torch_dtype (str or torch.dtype, optional) — Override the default torch.dtype and load the model under this dtype. If "auto" is passed the dtype will be automatically derived from the model’s weights.
  • custom_pipeline (str, optional) —

    This is an experimental feature and is likely to change in the future.

    Can be either:

    • A string, the repo id of a custom pipeline hosted inside a model repo on https://huggingface.co/. Valid repo ids have to be located under a user or organization name, like hf-internal-testing/diffusers-dummy-pipeline.

      It is required that the model repo has a file, called pipeline.py that defines the custom pipeline.

    • A string, the file name of a community pipeline hosted on GitHub under https://github.com/huggingface/diffusers/tree/main/examples/community. Valid file names have to match exactly the file name without .py located under the above link, e.g. clip_guided_stable_diffusion.

      Community pipelines are always loaded from the current main branch of GitHub.

    • A path to a directory containing a custom pipeline, e.g., ./my_pipeline_directory/.

      It is required that the directory has a file, called pipeline.py that defines the custom pipeline.

    For more information on how to load and create custom pipelines, please have a look at Loading and Adding Custom Pipelines

  • torch_dtype (str or torch.dtype, optional) —
  • 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.
  • resume_download (bool, optional, defaults to False) — Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists.
  • proxies (Dict[str, str], optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g., {'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 or not to only look at local files (i.e., do not try to download the model).
  • use_auth_token (str or bool, optional) — The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running huggingface-cli login (stored in ~/.huggingface).
  • 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, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.
  • mirror (str, optional) — Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. Please refer to the mirror site for more information. specify the folder name here.
  • device_map (str or Dict[str, Union[int, str, torch.device]], optional) — A map that specifies where each submodule should go. It doesn’t need to be refined to each parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the same device.

    To have Accelerate compute the most optimized device_map automatically, set device_map="auto". For more information about each option see designing a device map.

  • low_cpu_mem_usage (bool, optional, defaults to True if torch version >= 1.9.0 else False) — Speed up model loading by not initializing the weights and only loading the pre-trained weights. This also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch, setting this argument to True will raise an error.
  • kwargs (remaining dictionary of keyword arguments, optional) — Can be used to overwrite load - and saveable variables - i.e. the pipeline components - of the specific pipeline class. The overwritten components are then directly passed to the pipelines __init__ method. See example below for more information.

Instantiate a PyTorch diffusion pipeline from pre-trained pipeline weights.

The pipeline is set in evaluation mode by default using model.eval() (Dropout modules are deactivated).

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

It is required to be logged in (huggingface-cli login) when you want to use private or gated models, e.g. "runwayml/stable-diffusion-v1-5"

Activate the special “offline-mode” to use this method in a firewalled environment.

Examples:

>>> from diffusers import DiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

>>> # Download pipeline that requires an authorization token
>>> # For more information on access tokens, please refer to this section
>>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
>>> pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

>>> # Use a different scheduler
>>> from diffusers import LMSDiscreteScheduler

>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.scheduler = scheduler

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] )

Parameters

  • save_directory (str or os.PathLike) — Directory to which to save. Will be created if it doesn’t exist.

Save all variables of the pipeline that can be saved and loaded as well as the pipelines configuration file to a directory. A pipeline variable can be saved and loaded if its class implements both a save and loading method. The pipeline can easily be re-loaded using the [from_pretrained()](/docs/diffusers/v0.9.0/en/using-diffusers/loading#diffusers.DiffusionPipeline.from_pretrained) class method.

class diffusers.FlaxModelMixin

< >

( )

Base class for all flax models.

FlaxModelMixin takes care of storing the configuration of the models and handles methods for loading, downloading and saving models.

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] dtype: dtype = <class 'jax.numpy.float32'> *model_args **kwargs )

Parameters

  • pretrained_model_name_or_path (str or os.PathLike) — Can be either:

    • A string, the model id of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids are namespaced under a user or organization name, like runwayml/stable-diffusion-v1-5.
    • A path to a directory containing model weights saved using save_pretrained(), e.g., ./my_model_directory/.
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype.

    Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters.

    If you wish to change the dtype of the model parameters, see ~ModelMixin.to_fp16 and ~ModelMixin.to_bf16.

  • model_args (sequence of positional arguments, optional) — All remaining positional arguments will be passed to the underlying model’s __init__ method.
  • cache_dir (Union[str, os.PathLike], optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
  • 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.
  • resume_download (bool, optional, defaults to False) — Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists.
  • proxies (Dict[str, str], optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g., {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.
  • local_files_only(bool, optional, defaults to False) — Whether or not to only look at local files (i.e., do not try to download the model).
  • 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, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.
  • from_pt (bool, optional, defaults to False) — Load the model weights from a PyTorch checkpoint save file.
  • kwargs (remaining dictionary of keyword arguments, optional) — Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., output_attentions=True). Behaves differently depending on whether a config is provided or automatically loaded:

    • If a configuration is provided with config, **kwargs will be directly passed to the underlying model’s __init__ method (we assume all relevant updates to the configuration have already been done)
    • If a configuration is not provided, kwargs will be first passed to the configuration class initialization function (from_config()). Each key of kwargs that corresponds to a configuration attribute will be used to override said attribute with the supplied kwargs value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s __init__ function.

Instantiate a pretrained flax model from a pre-trained model configuration.

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

Examples:

>>> from diffusers import FlaxUNet2DConditionModel

>>> # Download model and configuration from huggingface.co and cache.
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] is_main_process: bool = True )

Parameters

  • save_directory (str or os.PathLike) — Directory to which to save. Will be created if it doesn’t exist.
  • params (Union[Dict, FrozenDict]) — A PyTree of model parameters.
  • is_main_process (bool, optional, defaults to True) — Whether the process calling this is the main process or not. Useful when in distributed training like TPUs and need to call this function on all processes. In this case, set is_main_process=True only on the main process to avoid race conditions.

Save a model and its configuration file to a directory, so that it can be re-loaded using the [from_pretrained()](/docs/diffusers/v0.9.0/en/using-diffusers/loading#diffusers.FlaxModelMixin.from_pretrained) class method

class diffusers.FlaxDiffusionPipeline

< >

( )

Base class for all models.

FlaxDiffusionPipeline takes care of storing all components (models, schedulers, processors) for diffusion pipelines and handles methods for loading, downloading and saving models as well as a few methods common to all pipelines to:

  • enabling/disabling the progress bar for the denoising iteration

Class attributes:

  • config_name (str) — name of the config file that will store the class and module names of all components of the diffusion pipeline.

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] **kwargs )

Parameters

  • pretrained_model_name_or_path (str or os.PathLike, optional) — Can be either:

    • A string, the repo id of a pretrained pipeline hosted inside a model repo on https://huggingface.co/ Valid repo ids have to be located under a user or organization name, like CompVis/ldm-text2im-large-256.
    • A path to a directory containing pipeline weights saved using save_pretrained(), e.g., ./my_pipeline_directory/.
  • dtype (str or jnp.dtype, optional) — Override the default jnp.dtype and load the model under this dtype. If "auto" is passed the dtype will be 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.
  • resume_download (bool, optional, defaults to False) — Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists.
  • proxies (Dict[str, str], optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g., {'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 or not to only look at local files (i.e., do not try to download the model).
  • use_auth_token (str or bool, optional) — The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running huggingface-cli login (stored in ~/.huggingface).
  • 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, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.
  • mirror (str, optional) — Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. Please refer to the mirror site for more information. specify the folder name here.
  • kwargs (remaining dictionary of keyword arguments, optional) — Can be used to overwrite load - and saveable variables - i.e. the pipeline components - of the specific pipeline class. The overwritten components are then directly passed to the pipelines __init__ method. See example below for more information.

Instantiate a Flax diffusion pipeline from pre-trained pipeline weights.

The pipeline is set in evaluation mode by default using model.eval() (Dropout modules are deactivated).

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

It is required to be logged in (huggingface-cli login) when you want to use private or gated models, e.g. "runwayml/stable-diffusion-v1-5"

Activate the special “offline-mode” to use this method in a firewalled environment.

Examples:

>>> from diffusers import FlaxDiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> # Requires to be logged in to Hugging Face hub,
>>> # see more in [the documentation](https://huggingface.co/docs/hub/security-tokens)
>>> pipeline, params = FlaxDiffusionPipeline.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     revision="bf16",
...     dtype=jnp.bfloat16,
... )

>>> # Download pipeline, but use a different scheduler
>>> from diffusers import FlaxDPMSolverMultistepScheduler

>>> model_id = "runwayml/stable-diffusion-v1-5"
>>> sched, sched_state = FlaxDPMSolverMultistepScheduler.from_pretrained(
...     model_id,
...     subfolder="scheduler",
... )

>>> dpm_pipe, dpm_params = FlaxStableDiffusionPipeline.from_pretrained(
...     model_id, revision="bf16", dtype=jnp.bfloat16, scheduler=dpmpp
... )
>>> dpm_params["scheduler"] = dpmpp_state

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] )

Parameters

  • save_directory (str or os.PathLike) — Directory to which to save. Will be created if it doesn’t exist.

Save all variables of the pipeline that can be saved and loaded as well as the pipelines configuration file to a directory. A pipeline variable can be saved and loaded if its class implements both a save and loading method. The pipeline can easily be re-loaded using the [from_pretrained()](/docs/diffusers/v0.9.0/en/using-diffusers/loading#diffusers.FlaxDiffusionPipeline.from_pretrained) class method.