Diffusers documentation

Loaders

You are viewing v0.16.0 version. A newer version v0.27.2 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Loaders

There are many ways to train adapter neural networks for diffusion models, such as

Such adapter neural networks often only consist of a fraction of the number of weights compared to the pretrained model and as such are very portable. The Diffusers library offers an easy-to-use API to load such adapter neural networks via the loaders.py module.

Note: This module is still highly experimental and prone to future changes.

LoaderMixins

UNet2DConditionLoadersMixin

class diffusers.loaders.UNet2DConditionLoadersMixin

< >

( )

load_attn_procs

< >

( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] **kwargs )

Parameters

  • pretrained_model_name_or_path_or_dict (str or os.PathLike or dict) — 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/.
    • A torch state dict.
  • 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).
  • 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.

Load pretrained attention processor layers into UNet2DConditionModel. Attention processor layers have to be defined in cross_attention.py and be a torch.nn.Module class.

This function is experimental and might change in the future.

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

save_attn_procs

< >

( save_directory: typing.Union[str, os.PathLike] is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = False **kwargs )

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. Can be configured with the environment variable DIFFUSERS_SAVE_MODE.

Save an attention processor to a directory, so that it can be re-loaded using the load_attn_procs() method.

TextualInversionLoaderMixin

class diffusers.loaders.TextualInversionLoaderMixin

< >

( )

Mixin class for loading textual inversion tokens and embeddings to the tokenizer and text encoder.

load_textual_inversion

< >

( pretrained_model_name_or_path: typing.Union[str, typing.Dict[str, torch.Tensor]] token: typing.Optional[str] = None **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 should have an organization name, like "sd-concepts-library/low-poly-hd-logos-icons".
    • A path to a directory containing textual inversion weights, e.g. ./my_text_inversion_directory/.
  • weight_name (str, optional) — Name of a custom weight file. This should be used in two cases:

    • The saved textual inversion file is in diffusers format, but was saved under a specific weight name, such as text_inv.bin.
    • The saved textual inversion file is in the “Automatic1111” form.
  • 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).
  • 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.

Load textual inversion embeddings into the text encoder of stable diffusion pipelines. Both diffusers and Automatic1111 formats are supported (see example below).

This function is experimental and might change in the future.

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

Example:

To load a textual inversion embedding vector in diffusers format:

from diffusers import StableDiffusionPipeline
import torch

model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

To load a textual inversion embedding vector in Automatic1111 format, make sure to first download the vector,

e.g. from civitAI and then load the vector locally:

from diffusers import StableDiffusionPipeline
import torch

model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

maybe_convert_prompt

< >

( prompt: typing.Union[str, typing.List[str]] tokenizer: PreTrainedTokenizer ) str or list of str

Parameters

  • prompt (str or list of str) — The prompt or prompts to guide the image generation.
  • tokenizer (PreTrainedTokenizer) — The tokenizer responsible for encoding the prompt into input tokens.

Returns

str or list of str

The converted prompt

Maybe convert a prompt into a “multi vector”-compatible prompt. If the prompt includes a token that corresponds to a multi-vector textual inversion embedding, this function will process the prompt so that the special token is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.

LoraLoaderMixin

class diffusers.loaders.LoraLoaderMixin

< >

( )

Utility class for handling the loading LoRA layers into UNet (of class UNet2DConditionModel) and Text Encoder (of class CLIPTextModel).

This function is experimental and might change in the future.

load_attn_procs

< >

( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] **kwargs ) Dict[name, LoRAAttnProcessor]

Parameters

  • pretrained_model_name_or_path_or_dict (str or os.PathLike or dict) — 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/.
    • A torch state dict.
  • 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).
  • 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.

Returns

Dict[name, LoRAAttnProcessor]

Mapping between the module names and their corresponding LoRAAttnProcessor.

Load pretrained attention processor layers for CLIPTextModel.

This function is experimental and might change in the future.

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

load_lora_weights

< >

( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] **kwargs )

Parameters

  • pretrained_model_name_or_path_or_dict (str or os.PathLike or dict) — 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/.
    • A torch state dict.
  • 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).
  • 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.

Load pretrained attention processor layers (such as LoRA) into UNet2DConditionModel and CLIPTextModel).

This function is experimental and might change in the future.

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

save_lora_weights

< >

( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None text_encoder_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = False )

Parameters

  • save_directory (str or os.PathLike) — Directory to which to save. Will be created if it doesn’t exist.
  • unet_lora_layers (Dict[str, torch.nn.Module]) — State dict of the LoRA layers corresponding to the UNet. Specifying this helps to make the serialization process easier and cleaner.
  • text_encoder_lora_layers (Dict[str, torch.nn.Module]) — State dict of the LoRA layers corresponding to the text_encoder. Since the text_encoder comes from transformers, we cannot rejig it. That is why we have to explicitly pass the text encoder LoRA state dict.
  • 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. Can be configured with the environment variable DIFFUSERS_SAVE_MODE.

Save the LoRA parameters corresponding to the UNet and the text encoder.

FromCkptMixin

class diffusers.loaders.FromCkptMixin

< >

( )

This helper class allows to directly load .ckpt stable diffusion file_extension into the respective classes.

from_ckpt

< >

( pretrained_model_link_or_path **kwargs )

Parameters

  • pretrained_model_link_or_path (str or os.PathLike, optional) — Can be either:
    • A link to the .ckpt file on the Hub. Should be in the format "https://huggingface.co/<repo_id>/blob/main/<path_to_file>"
    • A path to a file containing all pipeline weights.
  • 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.
  • 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.
  • 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).
  • 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.
  • use_safetensors (bool, optional ) — If set to True, the pipeline will be loaded from safetensors weights. If set to None (the default). The pipeline will load using safetensors if the safetensors weights are available and if safetensors is installed. If the to False the pipeline will not use safetensors.
  • extract_ema (bool, optional, defaults to False) — Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights or not. Defaults to False. Pass True to extract the EMA weights. EMA weights usually yield higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.
  • upcast_attention (bool, optional, defaults to None) — Whether the attention computation should always be upcasted. This is necessary when running stable
  • image_size (int, optional, defaults to 512) — The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Diffusion v2 Base. Use 768 for Stable Diffusion v2.
  • prediction_type (str, optional) — The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable Diffusion v2 Base. Use 'v_prediction' for Stable Diffusion v2.
  • num_in_channels (int, optional, defaults to None) — The number of input channels. If None, it will be automatically inferred.
  • scheduler_type (str, optional, defaults to ‘pndm’) — Type of scheduler to use. Should be one of ["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm", "ddim"].
  • load_safety_checker (bool, optional, defaults to True) — Whether to load the safety checker or not. Defaults to True.
  • 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 saved in the original .ckpt format.

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

Examples:

>>> from diffusers import StableDiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_ckpt(
...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
... )

>>> # Download pipeline from local file
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
>>> pipeline = StableDiffusionPipeline.from_ckpt("./v1-5-pruned-emaonly")

>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_ckpt(
...     "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
...     torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")