Skip to content

Commit 2fb459c

Browse files
authored
Merge branch 'main' into missing_kwargs_lora_pipeline_py
2 parents d5f6fa5 + e7e6d85 commit 2fb459c

File tree

17 files changed

+657
-114
lines changed

17 files changed

+657
-114
lines changed

src/diffusers/loaders/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ def text_encoder_attn_modules(text_encoder):
7070
"LoraLoaderMixin",
7171
"FluxLoraLoaderMixin",
7272
"CogVideoXLoraLoaderMixin",
73+
"CogView4LoraLoaderMixin",
7374
"Mochi1LoraLoaderMixin",
7475
"HunyuanVideoLoraLoaderMixin",
7576
"SanaLoraLoaderMixin",
@@ -103,6 +104,7 @@ def text_encoder_attn_modules(text_encoder):
103104
from .lora_pipeline import (
104105
AmusedLoraLoaderMixin,
105106
CogVideoXLoraLoaderMixin,
107+
CogView4LoraLoaderMixin,
106108
FluxLoraLoaderMixin,
107109
HunyuanVideoLoraLoaderMixin,
108110
LoraLoaderMixin,

src/diffusers/loaders/lora_pipeline.py

Lines changed: 305 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4450,6 +4450,311 @@ def unfuse_lora(self, components: List[str] = ["transformer"], **kwargs):
44504450
super().unfuse_lora(components=components, **kwargs)
44514451

44524452

4453+
class CogView4LoraLoaderMixin(LoraBaseMixin):
4454+
r"""
4455+
Load LoRA layers into [`WanTransformer3DModel`]. Specific to [`CogView4Pipeline`].
4456+
"""
4457+
4458+
_lora_loadable_modules = ["transformer"]
4459+
transformer_name = TRANSFORMER_NAME
4460+
4461+
@classmethod
4462+
@validate_hf_hub_args
4463+
# Copied from diffusers.loaders.lora_pipeline.CogVideoXLoraLoaderMixin.lora_state_dict
4464+
def lora_state_dict(
4465+
cls,
4466+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
4467+
**kwargs,
4468+
):
4469+
r"""
4470+
Return state dict for lora weights and the network alphas.
4471+
4472+
<Tip warning={true}>
4473+
4474+
We support loading A1111 formatted LoRA checkpoints in a limited capacity.
4475+
4476+
This function is experimental and might change in the future.
4477+
4478+
</Tip>
4479+
4480+
Parameters:
4481+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
4482+
Can be either:
4483+
4484+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
4485+
the Hub.
4486+
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
4487+
with [`ModelMixin.save_pretrained`].
4488+
- A [torch state
4489+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
4490+
4491+
cache_dir (`Union[str, os.PathLike]`, *optional*):
4492+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
4493+
is not used.
4494+
force_download (`bool`, *optional*, defaults to `False`):
4495+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
4496+
cached versions if they exist.
4497+
4498+
proxies (`Dict[str, str]`, *optional*):
4499+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
4500+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
4501+
local_files_only (`bool`, *optional*, defaults to `False`):
4502+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
4503+
won't be downloaded from the Hub.
4504+
token (`str` or *bool*, *optional*):
4505+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
4506+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
4507+
revision (`str`, *optional*, defaults to `"main"`):
4508+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
4509+
allowed by Git.
4510+
subfolder (`str`, *optional*, defaults to `""`):
4511+
The subfolder location of a model file within a larger model repository on the Hub or locally.
4512+
4513+
"""
4514+
# Load the main state dict first which has the LoRA layers for either of
4515+
# transformer and text encoder or both.
4516+
cache_dir = kwargs.pop("cache_dir", None)
4517+
force_download = kwargs.pop("force_download", False)
4518+
proxies = kwargs.pop("proxies", None)
4519+
local_files_only = kwargs.pop("local_files_only", None)
4520+
token = kwargs.pop("token", None)
4521+
revision = kwargs.pop("revision", None)
4522+
subfolder = kwargs.pop("subfolder", None)
4523+
weight_name = kwargs.pop("weight_name", None)
4524+
use_safetensors = kwargs.pop("use_safetensors", None)
4525+
4526+
allow_pickle = False
4527+
if use_safetensors is None:
4528+
use_safetensors = True
4529+
allow_pickle = True
4530+
4531+
user_agent = {
4532+
"file_type": "attn_procs_weights",
4533+
"framework": "pytorch",
4534+
}
4535+
4536+
state_dict = _fetch_state_dict(
4537+
pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict,
4538+
weight_name=weight_name,
4539+
use_safetensors=use_safetensors,
4540+
local_files_only=local_files_only,
4541+
cache_dir=cache_dir,
4542+
force_download=force_download,
4543+
proxies=proxies,
4544+
token=token,
4545+
revision=revision,
4546+
subfolder=subfolder,
4547+
user_agent=user_agent,
4548+
allow_pickle=allow_pickle,
4549+
)
4550+
4551+
is_dora_scale_present = any("dora_scale" in k for k in state_dict)
4552+
if is_dora_scale_present:
4553+
warn_msg = "It seems like you are using a DoRA checkpoint that is not compatible in Diffusers at the moment. So, we are going to filter out the keys associated to 'dora_scale` from the state dict. If you think this is a mistake please open an issue https://github.com/huggingface/diffusers/issues/new."
4554+
logger.warning(warn_msg)
4555+
state_dict = {k: v for k, v in state_dict.items() if "dora_scale" not in k}
4556+
4557+
return state_dict
4558+
4559+
# Copied from diffusers.loaders.lora_pipeline.CogVideoXLoraLoaderMixin.load_lora_weights
4560+
def load_lora_weights(
4561+
self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
4562+
):
4563+
"""
4564+
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.transformer` and
4565+
`self.text_encoder`. All kwargs are forwarded to `self.lora_state_dict`. See
4566+
[`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
4567+
See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_transformer`] for more details on how the state
4568+
dict is loaded into `self.transformer`.
4569+
4570+
Parameters:
4571+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
4572+
See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
4573+
adapter_name (`str`, *optional*):
4574+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
4575+
`default_{i}` where i is the total number of adapters being loaded.
4576+
low_cpu_mem_usage (`bool`, *optional*):
4577+
Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
4578+
weights.
4579+
kwargs (`dict`, *optional*):
4580+
See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`].
4581+
"""
4582+
if not USE_PEFT_BACKEND:
4583+
raise ValueError("PEFT backend is required for this method.")
4584+
4585+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT_LORA)
4586+
if low_cpu_mem_usage and is_peft_version("<", "0.13.0"):
4587+
raise ValueError(
4588+
"`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`."
4589+
)
4590+
4591+
# if a dict is passed, copy it instead of modifying it inplace
4592+
if isinstance(pretrained_model_name_or_path_or_dict, dict):
4593+
pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
4594+
4595+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
4596+
state_dict = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
4597+
4598+
is_correct_format = all("lora" in key for key in state_dict.keys())
4599+
if not is_correct_format:
4600+
raise ValueError("Invalid LoRA checkpoint.")
4601+
4602+
self.load_lora_into_transformer(
4603+
state_dict,
4604+
transformer=getattr(self, self.transformer_name) if not hasattr(self, "transformer") else self.transformer,
4605+
adapter_name=adapter_name,
4606+
_pipeline=self,
4607+
low_cpu_mem_usage=low_cpu_mem_usage,
4608+
)
4609+
4610+
@classmethod
4611+
# Copied from diffusers.loaders.lora_pipeline.SD3LoraLoaderMixin.load_lora_into_transformer with SD3Transformer2DModel->CogView4Transformer2DModel
4612+
def load_lora_into_transformer(
4613+
cls, state_dict, transformer, adapter_name=None, _pipeline=None, low_cpu_mem_usage=False
4614+
):
4615+
"""
4616+
This will load the LoRA layers specified in `state_dict` into `transformer`.
4617+
4618+
Parameters:
4619+
state_dict (`dict`):
4620+
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
4621+
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
4622+
encoder lora layers.
4623+
transformer (`CogView4Transformer2DModel`):
4624+
The Transformer model to load the LoRA layers into.
4625+
adapter_name (`str`, *optional*):
4626+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
4627+
`default_{i}` where i is the total number of adapters being loaded.
4628+
low_cpu_mem_usage (`bool`, *optional*):
4629+
Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
4630+
weights.
4631+
"""
4632+
if low_cpu_mem_usage and is_peft_version("<", "0.13.0"):
4633+
raise ValueError(
4634+
"`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`."
4635+
)
4636+
4637+
# Load the layers corresponding to transformer.
4638+
logger.info(f"Loading {cls.transformer_name}.")
4639+
transformer.load_lora_adapter(
4640+
state_dict,
4641+
network_alphas=None,
4642+
adapter_name=adapter_name,
4643+
_pipeline=_pipeline,
4644+
low_cpu_mem_usage=low_cpu_mem_usage,
4645+
)
4646+
4647+
@classmethod
4648+
# Copied from diffusers.loaders.lora_pipeline.CogVideoXLoraLoaderMixin.save_lora_weights
4649+
def save_lora_weights(
4650+
cls,
4651+
save_directory: Union[str, os.PathLike],
4652+
transformer_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
4653+
is_main_process: bool = True,
4654+
weight_name: str = None,
4655+
save_function: Callable = None,
4656+
safe_serialization: bool = True,
4657+
):
4658+
r"""
4659+
Save the LoRA parameters corresponding to the UNet and text encoder.
4660+
4661+
Arguments:
4662+
save_directory (`str` or `os.PathLike`):
4663+
Directory to save LoRA parameters to. Will be created if it doesn't exist.
4664+
transformer_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
4665+
State dict of the LoRA layers corresponding to the `transformer`.
4666+
is_main_process (`bool`, *optional*, defaults to `True`):
4667+
Whether the process calling this is the main process or not. Useful during distributed training and you
4668+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
4669+
process to avoid race conditions.
4670+
save_function (`Callable`):
4671+
The function to use to save the state dictionary. Useful during distributed training when you need to
4672+
replace `torch.save` with another method. Can be configured with the environment variable
4673+
`DIFFUSERS_SAVE_MODE`.
4674+
safe_serialization (`bool`, *optional*, defaults to `True`):
4675+
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
4676+
"""
4677+
state_dict = {}
4678+
4679+
if not transformer_lora_layers:
4680+
raise ValueError("You must pass `transformer_lora_layers`.")
4681+
4682+
if transformer_lora_layers:
4683+
state_dict.update(cls.pack_weights(transformer_lora_layers, cls.transformer_name))
4684+
4685+
# Save the model
4686+
cls.write_lora_layers(
4687+
state_dict=state_dict,
4688+
save_directory=save_directory,
4689+
is_main_process=is_main_process,
4690+
weight_name=weight_name,
4691+
save_function=save_function,
4692+
safe_serialization=safe_serialization,
4693+
)
4694+
4695+
# Copied from diffusers.loaders.lora_pipeline.CogVideoXLoraLoaderMixin.fuse_lora
4696+
def fuse_lora(
4697+
self,
4698+
components: List[str] = ["transformer"],
4699+
lora_scale: float = 1.0,
4700+
safe_fusing: bool = False,
4701+
adapter_names: Optional[List[str]] = None,
4702+
**kwargs,
4703+
):
4704+
r"""
4705+
Fuses the LoRA parameters into the original parameters of the corresponding blocks.
4706+
4707+
<Tip warning={true}>
4708+
4709+
This is an experimental API.
4710+
4711+
</Tip>
4712+
4713+
Args:
4714+
components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into.
4715+
lora_scale (`float`, defaults to 1.0):
4716+
Controls how much to influence the outputs with the LoRA parameters.
4717+
safe_fusing (`bool`, defaults to `False`):
4718+
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
4719+
adapter_names (`List[str]`, *optional*):
4720+
Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
4721+
4722+
Example:
4723+
4724+
```py
4725+
from diffusers import DiffusionPipeline
4726+
import torch
4727+
4728+
pipeline = DiffusionPipeline.from_pretrained(
4729+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
4730+
).to("cuda")
4731+
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
4732+
pipeline.fuse_lora(lora_scale=0.7)
4733+
```
4734+
"""
4735+
super().fuse_lora(
4736+
components=components, lora_scale=lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names
4737+
)
4738+
4739+
# Copied from diffusers.loaders.lora_pipeline.CogVideoXLoraLoaderMixin.unfuse_lora
4740+
def unfuse_lora(self, components: List[str] = ["transformer"], **kwargs):
4741+
r"""
4742+
Reverses the effect of
4743+
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).
4744+
4745+
<Tip warning={true}>
4746+
4747+
This is an experimental API.
4748+
4749+
</Tip>
4750+
4751+
Args:
4752+
components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
4753+
unfuse_transformer (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
4754+
"""
4755+
super().unfuse_lora(components=components)
4756+
4757+
44534758
class LoraLoaderMixin(StableDiffusionLoraLoaderMixin):
44544759
def __init__(self, *args, **kwargs):
44554760
deprecation_message = "LoraLoaderMixin is deprecated and this will be removed in a future version. Please use `StableDiffusionLoraLoaderMixin`, instead."

src/diffusers/loaders/peft.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
"SanaTransformer2DModel": lambda model_cls, weights: weights,
5555
"Lumina2Transformer2DModel": lambda model_cls, weights: weights,
5656
"WanTransformer3DModel": lambda model_cls, weights: weights,
57+
"CogView4Transformer2DModel": lambda model_cls, weights: weights,
5758
}
5859

5960

0 commit comments

Comments
 (0)