Adapters (textual inversion, LoRA, hypernetworks) allow you to modify a diffusion model to generate images in a specific style without training or finetuning the entire model. The adapter weights are typically only a tiny fraction of the pretrained model’s which making them very portable. 🤗 Diffusers provides an easy-to-use LoaderMixin
API to load adapter weights.
🧪 The LoaderMixins
are highly experimental and prone to future changes. To use private or gated models, log-in with huggingface-cli login
.
( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] **kwargs )
Parameters
str
or os.PathLike
or dict
) —
Can be either:
google/ddpm-celebahq-256
) of a pretrained model hosted on
the Hub../my_model_directory
) containing the model weights saved
with ModelMixin.save_pretrained().Union[str, os.PathLike]
, optional) —
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used.
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.
bool
, optional, defaults to False
) —
Whether or not to resume downloading the model weights and configuration files. If set to False
, any
incompletely downloaded files are deleted.
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.
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.
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.
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.
str
, optional, defaults to ""
) —
The subfolder location of a model file within a larger model repository on the Hub or locally.
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.
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.
( 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
str
or os.PathLike
) —
Directory to save an attention processor to. Will be created if it doesn’t exist.
bool
, optional, defaults to True
) —
Whether the process calling this is the main process or not. Useful during distributed training and you
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.
Callable
) —
The function to use to save the state dictionary. Useful during distributed training when you need to
replace torch.save
with another method. Can be configured with the environment variable
DIFFUSERS_SAVE_MODE
.
Save an attention processor to a directory so that it can be reloaded using the load_attn_procs() method.
Load textual inversion tokens and embeddings to the tokenizer and text encoder.
( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[str, typing.List[str], NoneType] = None **kwargs )
Parameters
str
or os.PathLike
or List[str or os.PathLike]
or Dict
or List[Dict]
) —
Can be either one of the following or a list of them:
sd-concepts-library/low-poly-hd-logos-icons
) of a
pretrained model hosted on the Hub../my_text_inversion_directory/
) containing the textual
inversion weights../my_text_inversions.pt
) containing textual inversion weights.str
or List[str]
, optional) —
Override the token to use for the textual inversion weights. If pretrained_model_name_or_path
is a
list, then token
must also be a list of equal length.
str
, optional) —
Name of a custom weight file. This should be used when:
text_inv.bin
.Union[str, os.PathLike]
, optional) —
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used.
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.
bool
, optional, defaults to False
) —
Whether or not to resume downloading the model weights and configuration files. If set to False
, any
incompletely downloaded files are deleted.
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.
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.
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.
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.
str
, optional, defaults to ""
) —
The subfolder location of a model file within a larger model repository on the Hub or locally.
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.
Load textual inversion embeddings into the text encoder of StableDiffusionPipeline (both 🤗 Diffusers and Automatic1111 formats are supported).
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 download the vector first (for example 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")
(
prompt: typing.Union[str, typing.List[str]]
tokenizer: PreTrainedTokenizer
)
→
str
or list of str
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual inversion token or if the textual inversion token is a single vector, the input prompt is returned.
Load LoRA layers into UNet2DConditionModel and
CLIPTextModel
.
( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] **kwargs )
Parameters
str
or os.PathLike
or dict
) —
Can be either:
google/ddpm-celebahq-256
) of a pretrained model hosted on
the Hub../my_model_directory
) containing the model weights saved
with ModelMixin.save_pretrained().Union[str, os.PathLike]
, optional) —
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used.
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.
bool
, optional, defaults to False
) —
Whether or not to resume downloading the model weights and configuration files. If set to False
, any
incompletely downloaded files are deleted.
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.
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.
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.
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.
str
, optional, defaults to ""
) —
The subfolder location of a model file within a larger model repository on the Hub or locally.
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.
Load pretrained LoRA attention processor layers into UNet2DConditionModel and
CLIPTextModel
.
( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = 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
str
or os.PathLike
) —
Directory to save LoRA parameters to. Will be created if it doesn’t exist.
Dict[str, torch.nn.Module]
or Dict[str, torch.Tensor]
) —
State dict of the LoRA layers corresponding to the UNet.
Dict[str, torch.nn.Module] or
Dict[str, torch.Tensor]) -- State dict of the LoRA layers corresponding to the
text_encoder`. Must explicitly pass the text
encoder LoRA state dict because it comes 🤗 Transformers.
bool
, optional, defaults to True
) —
Whether the process calling this is the main process or not. Useful during distributed training and you
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.
Callable
) —
The function to use to save the state dictionary. Useful during distributed training when you need to
replace torch.save
with another method. Can be configured with the environment variable
DIFFUSERS_SAVE_MODE
.
Save the LoRA parameters corresponding to the UNet and text encoder.
Load model weights saved in the .ckpt
format into a DiffusionPipeline.
( pretrained_model_link_or_path **kwargs )
Parameters
str
or os.PathLike
, optional) —
Can be either:.ckpt
file (for example
"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"
) on the Hub.str
or torch.dtype
, optional) —
Override the default torch.dtype
and load the model with another dtype. If "auto"
is passed, the
dtype is automatically derived from the model’s weights.
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.
Union[str, os.PathLike]
, optional) —
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used.
bool
, optional, defaults to False
) —
Whether or not to resume downloading the model weights and configuration files. If set to False
, any
incompletely downloaded files are deleted.
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.
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.
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.
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.
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.
bool
, optional, defaults to False
) —
Whether to extract the EMA weights or not. Pass True
to extract the EMA weights which usually yield
higher quality images for inference. Non-EMA weights are usually better to continue finetuning.
bool
, optional, defaults to None
) —
Whether the attention computation should always be upcasted.
int
, optional, defaults to 512) —
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
str
, optional) —
The prediction type the model was trained on. Use 'epsilon'
for all Stable Diffusion v1 models and
the Stable Diffusion v2 base model. Use 'v_prediction'
for Stable Diffusion v2.
int
, optional, defaults to None
) —
The number of input channels. If None
, it will be automatically inferred.
str
, optional, defaults to "pndm"
) —
Type of scheduler to use. Should be one of ["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm", "ddim"]
.
bool
, optional, defaults to True
) —
Whether to load the safety checker or not.
CLIPTextModel
, optional, defaults to None
) —
An instance of
CLIP to use,
specifically the clip-vit-large-patch14
variant. If this parameter is None
, the function will load a new instance of [CLIP] by itself, if
needed.
CLIPTokenizer
, optional, defaults to None
) —
An instance of
CLIPTokenizer
to use. If this parameter is None
, the function will load a new instance of [CLIPTokenizer] by
itself, if needed.
__init__
method. See example below for more information.
Instantiate a DiffusionPipeline from pretrained pipeline weights saved in the .ckpt
format. The pipeline
is set in evaluation mode (model.eval()
) by default.
Examples:
>>> from diffusers import StableDiffusionPipeline
>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_single_file(
... "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_single_file("./v1-5-pruned-emaonly")
>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_single_file(
... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
... torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")