LoRA is a fast and lightweight training method that inserts and trains a significantly smaller number of parameters instead of all the model parameters. This produces a smaller file (~100 MBs) and makes it easier to quickly train a model to learn a new concept. LoRA weights are typically loaded into the UNet, text encoder or both. There are two classes for loading LoRA weights:
LoraLoaderMixin
provides functions for loading and unloading, fusing and unfusing, enabling and disabling, and more functions for managing LoRA weights. This class can be used with any model.StableDiffusionXLLoraLoaderMixin
is a Stable Diffusion (SDXL) version of the LoraLoaderMixin
class for loading and saving LoRA weights. It can only be used with the SDXL model.To learn more about how to load LoRA weights, see the LoRA loading guide.
Load LoRA layers into UNet2DConditionModel and CLIPTextModel.
( adapter_names: typing.Union[typing.List[str], str] )
Delete an adapter’s LoRA layers from the UNet and text encoder(s).
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.delete_adapters("pixel")
( text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None )
Disable the text encoder’s LoRA layers.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.disable_lora_for_text_encoder()
( text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None )
Enables the text encoder’s LoRA layers.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.enable_lora_for_text_encoder()
( fuse_unet: bool = True fuse_text_encoder: bool = True lora_scale: float = 1.0 safe_fusing: bool = False )
Parameters
bool
, defaults to True
) — Whether to fuse the UNet LoRA parameters. bool
, defaults to True
) —
Whether to fuse the text encoder LoRA parameters. If the text encoder wasn’t monkey-patched with the
LoRA parameters then it won’t have any effect. float
, defaults to 1.0) —
Controls LoRA influence on the outputs. bool
, defaults to False
) —
Whether to check fused weights for NaN
values before fusing and if values are NaN
, then don’t fuse
them. Fuse the LoRA parameters with the original parameters in their corresponding blocks.
This is an experimental API.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.fuse_lora(lora_scale=0.7)
Get a list of currently active adapters.
Get a list of all currently available adapters for each component in the pipeline.
Example:
from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
).to("cuda")
pipeline.load_lora_weights(
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.get_list_adapters()
( state_dict network_alphas text_encoder prefix = None lora_scale = 1.0 low_cpu_mem_usage = None adapter_name = None _pipeline = None )
Parameters
dict
) —
A standard state dict containing the LoRA layer parameters. The key should be prefixed with an
additional text_encoder
to distinguish between UNet LoRA layers. Dict[str, float]
) —
See
LoRALinearLayer
for more details. CLIPTextModel
) —
The text encoder model to load the LoRA layers into. str
) —
Expected prefix of the text_encoder
in the state_dict
. float
) —
Scale of LoRALinearLayer
’s output before it is added with the output of the regular LoRA layer. bool
, optional, defaults to True
if torch version >= 1.9.0 else False
) —
Only load and not initialize the pretrained weights. This can speedup model loading and also tries to
not use more than 1x model size in CPU memory (including peak memory) while loading the model. Only
supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this argument to
True
will raise an error. str
, optional) —
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
default_{i}
where i is the total number of adapters being loaded. Load LoRA layers specified in state_dict
into text_encoder
.
( state_dict network_alphas unet low_cpu_mem_usage = None adapter_name = None _pipeline = None )
Parameters
dict
) —
A standard state dict containing the LoRA layer parameters. The keys can either be indexed directly
into the unet
or prefixed with an additional unet
, which can be used to distinguish between text
encoder LoRA layers. Dict[str, float]
) —
See
LoRALinearLayer
for more details. UNet2DConditionModel
) —
The UNet model to load the LoRA layers into. bool
, optional, defaults to True
if torch version >= 1.9.0 else False
) —
Only load and not initialize the pretrained weights. This can speedup model loading and also tries to
not use more than 1x model size in CPU memory (including peak memory) while loading the model. Only
supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this argument to
True
will raise an error. str
, optional) —
Name for referencing the loaded adapter model. If not specified, it will use default_{i}
where i
is
the total number of adapters being loaded. Load LoRA layers specified in state_dict
into unet
.
( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name = None **kwargs )
Parameters
str
or os.PathLike
or dict
) —
A string (model id of a pretrained model hosted on the Hub), a path to a directory containing the model
weights, or a torch state
dict. dict
, optional) —
See lora_state_dict(). str
, optional) —
Name for referencing the loaded adapter model. If not specified, it will use default_{i}
where i
is
the total number of adapters being loaded. Must have PEFT installed to use. Load LoRA weights specified in pretrained_model_name_or_path_or_dict
into self.unet
and
self.text_encoder
.
All kwargs are forwarded to self.lora_state_dict
.
See lora_state_dict() for more details on how the state dict is loaded.
See load_lora_into_unet() for more details on how the state dict is loaded into
self.unet
.
See load_lora_into_text_encoder() for more details on how the state dict is loaded
into self.text_encoder
.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16).to(
"cuda"
)
pipeline.load_lora_weights(
"Yntec/pineappleAnimeMix", weight_name="pineappleAnimeMix_pineapple10.1.safetensors", adapter_name="anime"
)
( 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.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. bool
, optional, defaults to True
if torch version >= 1.9.0 else False
) —
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
argument to True
will raise an error. 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. Return state dict and network alphas of the LoRA weights.
( 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 = True )
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 from 🤗 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 dict. Useful during distributed training when you need to replace
torch.save
with another method. Can be configured with the environment variable
DIFFUSERS_SAVE_MODE
. bool
, optional, defaults to True
) —
Whether to save the model using safetensors
or with pickle
. Save the UNet and text encoder LoRA parameters.
Example:
from diffusers import StableDiffusionXLPipeline
from peft.utils import get_peft_model_state_dict
import torch
pipeline = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.fuse_lora()
# get and save unet state dict
unet_state_dict = get_peft_model_state_dict(pipeline.unet, adapter_name="pixel")
pipeline.save_lora_weights("fused-model", unet_lora_layers=unet_state_dict)
pipeline.load_lora_weights("fused-model", weight_name="pytorch_lora_weights.safetensors")
( adapter_names: typing.Union[typing.List[str], str] text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None text_encoder_weights: typing.List[float] = None )
Parameters
List[str]
or str
) —
The adapter to activate. torch.nn.Module
, optional) —
The text encoder module to activate the adapter layers for. If None
, it will try to get the
text_encoder
attribute. List[float]
, optional) —
The weights to use for the text encoder. If None
, the weights are set to 1.0
for all the adapters. Set the currently active adapter for use in the text encoder.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.load_lora_weights(
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.set_adapters_for_text_encoder("pixel")
( adapter_names: typing.List[str] device: typing.Union[torch.device, str, int] )
Move a LoRA to a target device. Useful for offloading a LoRA to the CPU in case you want to load multiple adapters and free some GPU memory.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.set_lora_device(["pixel"], device="cuda")
( unfuse_unet: bool = True unfuse_text_encoder: bool = True )
Unfuse the LoRA parameters from the original parameters in their corresponding blocks.
This is an experimental API.
Example:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.fuse_lora(lora_scale=0.7)
pipeline.unfuse_lora()
Unload the LoRA parameters from a pipeline.
Examples:
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.unload_lora_weights()
This class overrides LoraLoaderMixin
with LoRA loading/saving code that’s specific to SDXL.
( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name: typing.Optional[str] = None **kwargs )
Parameters
str
or os.PathLike
or dict
) —
A string (model id of a pretrained model hosted on the Hub), a path to a directory containing the model
weights, or a torch state
dict. dict
, optional) —
See lora_state_dict(). str
, optional) —
Name for referencing the loaded adapter model. If not specified, it will use default_{i}
where i
is
the total number of adapters being loaded. Must have PEFT installed to use. Load LoRA weights specified in pretrained_model_name_or_path_or_dict
into self.unet
and
self.text_encoder
.
All kwargs are forwarded to self.lora_state_dict
.
See lora_state_dict() for more details on how the state dict is loaded.
See load_lora_into_unet() for more details on how the state dict is loaded into
self.unet
.
See load_lora_into_text_encoder() for more details on how the state dict is loaded
into self.text_encoder
.
Example:
from diffusers import StableDiffusionXLPipeline
import torch
pipeline = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
( 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, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None text_encoder_2_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = True )
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 from 🤗 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
. bool
, optional, defaults to True
) —
Whether to save the model using safetensors
or the traditional PyTorch way with pickle
. Save the LoRA parameters corresponding to the UNet and text encoder.