Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.pyAdded+17
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/dynamic_modules_utils.pyAdded+507
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/export_utils.pyAdded+209
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/hub_utils.pyAdded+573
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/import_utils.pyAdded+962
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/loading_utils.pyAdded+210
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/logging.pyAdded+340
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/model_card_template.mdAdded+24
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/outputs.pyAdded+138
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/peft_utils.pyAdded+376
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/pil_utils.pyAdded+67
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/remote_utils.pyAdded+425
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/source_code_parsing_utils.pyAdded+52
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/state_dict_utils.pyAdded+366
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/testing_utils.pyAdded+1601
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/torch_utils.pyAdded+334
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/typing_utils.pyAdded+91
- exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/versions.pyAdded+117
- exp_code/1_benchmark/diffusers-WanS2V/tests/__init__.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/conftest.pyAdded+48
- exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/custom_pipeline/pipeline.pyAdded+102
- exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/custom_pipeline/what_ever.pyAdded+103
- exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/elise_format0.midAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/__init__.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/test_group_offloading.pyAdded+364
- exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/test_hooks.pyAdded+377
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/__init__.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_auraflow.pyAdded+137
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_cogvideox.pyAdded+174
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_cogview4.pyAdded+189
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_flux.pyAdded+1054
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_hunyuanvideo.pyAdded+264
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_ltx_video.pyAdded+148
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_lumina2.pyAdded+173
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_mochi.pyAdded+143
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_qwenimage.pyAdded+130
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sana.pyAdded+139
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sd.pyAdded+769
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sd3.pyAdded+191
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sdxl.pyAdded+681
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_wan.pyAdded+144
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_wanvace.pyAdded+217
- exp_code/1_benchmark/diffusers-WanS2V/tests/lora/utils.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/__init__.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/__init__.pyAdded
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_asymmetric_autoencoder_kl.pyAdded+276
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_cosmos.pyAdded+86
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_dc.pyAdded+87
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_hunyuan_video.pyAdded+210
- exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_kl.pyAdded+468
1234567891011121314151617# This file is autogenerated by the command `make fix-copies`, do not edit.from ..utils import DummyObject, requires_backends
class SpectrogramDiffusionPipeline(metaclass=DummyObject): _backends = ["transformers", "torch", "note_seq"]
def __init__(self, *args, **kwargs): requires_backends(self, ["transformers", "torch", "note_seq"])
@classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, ["transformers", "torch", "note_seq"])
@classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["transformers", "torch", "note_seq"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507# coding=utf-8# Copyright 2025 The HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Utilities to dynamically load objects from the Hub."""
import importlibimport inspectimport jsonimport osimport reimport shutilimport sysimport threadingfrom pathlib import Pathfrom types import ModuleTypefrom typing import Dict, Optional, Unionfrom urllib import request
from huggingface_hub import hf_hub_download, model_infofrom huggingface_hub.utils import RevisionNotFoundError, validate_hf_hub_argsfrom packaging import version
from .. import __version__from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, loggingfrom .constants import DIFFUSERS_DISABLE_REMOTE_CODE
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
# See https://huggingface.co/datasets/diffusers/community-pipelines-mirrorCOMMUNITY_PIPELINES_MIRROR_ID = "diffusers/community-pipelines-mirror"TIME_OUT_REMOTE_CODE = int(os.getenv("DIFFUSERS_TIMEOUT_REMOTE_CODE", 15))_HF_REMOTE_CODE_LOCK = threading.Lock()
def get_diffusers_versions(): url = "https://pypi.org/pypi/diffusers/json" releases = json.loads(request.urlopen(url).read())["releases"].keys() return sorted(releases, key=lambda x: version.Version(x))
def init_hf_modules(): """ Creates the cache directory for modules with an init, and adds it to the Python path. """ # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return
sys.path.append(HF_MODULES_CACHE) os.makedirs(HF_MODULES_CACHE, exist_ok=True) init_path = Path(HF_MODULES_CACHE) / "__init__.py" if not init_path.exists(): init_path.touch()
def create_dynamic_module(name: Union[str, os.PathLike]): """ Creates a dynamic module in the cache directory for modules. """ init_hf_modules() dynamic_module_path = Path(HF_MODULES_CACHE) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent) os.makedirs(dynamic_module_path, exist_ok=True) init_path = dynamic_module_path / "__init__.py" if not init_path.exists(): init_path.touch()
def get_relative_imports(module_file): """ Get the list of modules that are relatively imported in a module file.
Args: module_file (`str` or `os.PathLike`): The module file to inspect. """ with open(module_file, "r", encoding="utf-8") as f: content = f.read()
# Imports of the form `import .xxx` relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE) # Imports of the form `from .xxx import yyy` relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE) # Unique-ify return list(set(relative_imports))
def get_relative_import_files(module_file): """ Get the list of all files that are needed for a given module. Note that this function recurses through the relative imports (if a imports b and b imports c, it will return module files for b and c).
Args: module_file (`str` or `os.PathLike`): The module file to inspect. """ no_change = False files_to_check = [module_file] all_relative_imports = []
# Let's recurse through all relative imports while not no_change: new_imports = [] for f in files_to_check: new_imports.extend(get_relative_imports(f))
module_path = Path(module_file).parent new_import_files = [str(module_path / m) for m in new_imports] new_import_files = [f for f in new_import_files if f not in all_relative_imports] files_to_check = [f"{f}.py" for f in new_import_files]
no_change = len(new_import_files) == 0 all_relative_imports.extend(files_to_check)
return all_relative_imports
def check_imports(filename): """ Check if the current Python environment contains all the libraries that are imported in a file. """ with open(filename, "r", encoding="utf-8") as f: content = f.read()
# Imports of the form `import xxx` imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE) # Imports of the form `from xxx import yyy` imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE) # Only keep the top-level module imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
# Unique-ify and test we got them all imports = list(set(imports)) missing_packages = [] for imp in imports: try: importlib.import_module(imp) except ImportError: missing_packages.append(imp)
if len(missing_packages) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`" )
return get_relative_imports(filename)
def resolve_trust_remote_code(trust_remote_code, model_name, has_remote_code): trust_remote_code = trust_remote_code and not DIFFUSERS_DISABLE_REMOTE_CODE if DIFFUSERS_DISABLE_REMOTE_CODE: logger.warning( "Downloading remote code is disabled globally via the DIFFUSERS_DISABLE_REMOTE_CODE environment variable. Ignoring `trust_remote_code`." )
if has_remote_code and not trust_remote_code: error_msg = f"The repository for {model_name} contains custom code. " error_msg += ( "Downloading remote code is disabled globally via the DIFFUSERS_DISABLE_REMOTE_CODE environment variable." if DIFFUSERS_DISABLE_REMOTE_CODE else "Pass `trust_remote_code=True` to allow loading remote code modules." ) raise ValueError(error_msg)
elif has_remote_code and trust_remote_code: logger.warning( f"`trust_remote_code` is enabled. Downloading code from {model_name}. Please ensure you trust the contents of this repository" )
return trust_remote_code
def get_class_in_module(class_name, module_path, force_reload=False): """ Import a module on the cache directory for modules and extract a class from it. """ name = os.path.normpath(module_path) if name.endswith(".py"): name = name[:-3] name = name.replace(os.path.sep, ".") module_file: Path = Path(HF_MODULES_CACHE) / module_path
with _HF_REMOTE_CODE_LOCK: if force_reload: sys.modules.pop(name, None) importlib.invalidate_caches() cached_module: Optional[ModuleType] = sys.modules.get(name) module_spec = importlib.util.spec_from_file_location(name, location=module_file)
module: ModuleType if cached_module is None: module = importlib.util.module_from_spec(module_spec) # insert it into sys.modules before any loading begins sys.modules[name] = module else: module = cached_module
module_spec.loader.exec_module(module)
if class_name is None: return find_pipeline_class(module)
return getattr(module, class_name)
def find_pipeline_class(loaded_module): """ Retrieve pipeline class that inherits from `DiffusionPipeline`. Note that there has to be exactly one class inheriting from `DiffusionPipeline`. """ from ..pipelines import DiffusionPipeline
cls_members = dict(inspect.getmembers(loaded_module, inspect.isclass))
pipeline_class = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls, DiffusionPipeline) and cls.__module__.split(".")[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:" f" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in" f" {loaded_module}." ) pipeline_class = cls
return pipeline_class
@validate_hf_hub_argsdef get_cached_module_file( pretrained_model_name_or_path: Union[str, os.PathLike], module_file: str, cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, proxies: Optional[Dict[str, str]] = None, token: Optional[Union[bool, str]] = None, revision: Optional[str] = None, local_files_only: bool = False,): """ Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached Transformers module.
Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either:
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a configuration file saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
module_file (`str`): The name of the module file containing the class to look for. cache_dir (`str` or `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 to (re-)download the configuration files and override the cached versions if they exist. 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. 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 `transformers-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. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, will only try to load the tokenizer configuration from local files.
<Tip>
You may pass a token in `token` if you are not logged in (`hf auth login`) and want to use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
Returns: `str`: The path to the module inside the cache. """ # Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
module_file_or_url = os.path.join(pretrained_model_name_or_path, module_file)
if os.path.isfile(module_file_or_url): resolved_module_file = module_file_or_url submodule = "local" elif pretrained_model_name_or_path.count("/") == 0: available_versions = get_diffusers_versions() # cut ".dev0" latest_version = "v" + ".".join(__version__.split(".")[:3])
# retrieve github version that matches if revision is None: revision = latest_version if latest_version[1:] in available_versions else "main" logger.info(f"Defaulting to latest_version: {revision}.") elif revision in available_versions: revision = f"v{revision}" elif revision == "main": revision = revision else: raise ValueError( f"`custom_revision`: {revision} does not exist. Please make sure to choose one of" f" {', '.join(available_versions + ['main'])}." )
try: resolved_module_file = hf_hub_download( repo_id=COMMUNITY_PIPELINES_MIRROR_ID, repo_type="dataset", filename=f"{revision}/{pretrained_model_name_or_path}.py", cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, ) submodule = "git" module_file = pretrained_model_name_or_path + ".py" except RevisionNotFoundError as e: raise EnvironmentError( f"Revision '{revision}' not found in the community pipelines mirror. Check available revisions on" " https://huggingface.co/datasets/diffusers/community-pipelines-mirror/tree/main." " If you don't find the revision you are looking for, please open an issue on https://github.com/huggingface/diffusers/issues." ) from e except EnvironmentError: logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.") raise else: try: # Load from URL or cache if already cached resolved_module_file = hf_hub_download( pretrained_model_name_or_path, module_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, ) submodule = os.path.join("local", "--".join(pretrained_model_name_or_path.split("/"))) except EnvironmentError: logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.") raise
# Check we have all the requirements in our environment modules_needed = check_imports(resolved_module_file)
# Now we move the module inside our cached dynamic modules. full_submodule = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(full_submodule) submodule_path = Path(HF_MODULES_CACHE) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copyfile(resolved_module_file, submodule_path / module_file) for module_needed in modules_needed: if len(module_needed.split(".")) == 2: module_needed = "/".join(module_needed.split(".")) module_folder = module_needed.split("/")[0] if not os.path.exists(submodule_path / module_folder): os.makedirs(submodule_path / module_folder) module_needed = f"{module_needed}.py" shutil.copyfile(os.path.join(pretrained_model_name_or_path, module_needed), submodule_path / module_needed) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. commit_hash = model_info(pretrained_model_name_or_path, revision=revision, token=token).sha
# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. submodule_path = submodule_path / commit_hash full_submodule = full_submodule + os.path.sep + commit_hash create_dynamic_module(full_submodule)
if not (submodule_path / module_file).exists(): if len(module_file.split("/")) == 2: module_folder = module_file.split("/")[0] if not os.path.exists(submodule_path / module_folder): os.makedirs(submodule_path / module_folder) shutil.copyfile(resolved_module_file, submodule_path / module_file)
# Make sure we also have every file with relative for module_needed in modules_needed: if len(module_needed.split(".")) == 2: module_needed = "/".join(module_needed.split(".")) if not (submodule_path / module_needed).exists(): get_cached_module_file( pretrained_model_name_or_path, f"{module_needed}.py", cache_dir=cache_dir, force_download=force_download, proxies=proxies, token=token, revision=revision, local_files_only=local_files_only, ) return os.path.join(full_submodule, module_file)
@validate_hf_hub_argsdef get_class_from_dynamic_module( pretrained_model_name_or_path: Union[str, os.PathLike], module_file: str, class_name: Optional[str] = None, cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, proxies: Optional[Dict[str, str]] = None, token: Optional[Union[bool, str]] = None, revision: Optional[str] = None, local_files_only: bool = False, **kwargs,): """ Extracts a class from a module file, present in the local folder or repository of a model.
<Tip warning={true}>
Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should therefore only be called on trusted repos.
</Tip>
Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either:
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a configuration file saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
module_file (`str`): The name of the module file containing the class to look for. class_name (`str`): The name of the class to import in the module. cache_dir (`str` or `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 to (re-)download the configuration files and override the cached versions if they exist. 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. 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 `transformers-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. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, will only try to load the tokenizer configuration from local files.
<Tip>
You may pass a token in `token` if you are not logged in (`hf auth login`) and want to use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
Returns: `type`: The class, dynamically imported from the module.
Examples:
```python # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this # module. cls = get_class_from_dynamic_module("sgugger/my-bert-model", "modeling.py", "MyBertModel") ```""" # And lastly we get the class inside our newly created module final_module = get_cached_module_file( pretrained_model_name_or_path, module_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, token=token, revision=revision, local_files_only=local_files_only, ) return get_class_in_module(class_name, final_module)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209import ioimport randomimport structimport tempfilefrom contextlib import contextmanagerfrom typing import List, Optional, Union
import numpy as npimport PIL.Imageimport PIL.ImageOps
from .import_utils import BACKENDS_MAPPING, is_imageio_available, is_opencv_availablefrom .logging import get_logger
global_rng = random.Random()
logger = get_logger(__name__)
@contextmanagerdef buffered_writer(raw_f): f = io.BufferedWriter(raw_f) yield f f.flush()
def export_to_gif(image: List[PIL.Image.Image], output_gif_path: str = None, fps: int = 10) -> str: if output_gif_path is None: output_gif_path = tempfile.NamedTemporaryFile(suffix=".gif").name
image[0].save( output_gif_path, save_all=True, append_images=image[1:], optimize=False, duration=1000 // fps, loop=0, ) return output_gif_path
def export_to_ply(mesh, output_ply_path: str = None): """ Write a PLY file for a mesh. """ if output_ply_path is None: output_ply_path = tempfile.NamedTemporaryFile(suffix=".ply").name
coords = mesh.verts.detach().cpu().numpy() faces = mesh.faces.cpu().numpy() rgb = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1)
with buffered_writer(open(output_ply_path, "wb")) as f: f.write(b"ply\n") f.write(b"format binary_little_endian 1.0\n") f.write(bytes(f"element vertex {len(coords)}\n", "ascii")) f.write(b"property float x\n") f.write(b"property float y\n") f.write(b"property float z\n") if rgb is not None: f.write(b"property uchar red\n") f.write(b"property uchar green\n") f.write(b"property uchar blue\n") if faces is not None: f.write(bytes(f"element face {len(faces)}\n", "ascii")) f.write(b"property list uchar int vertex_index\n") f.write(b"end_header\n")
if rgb is not None: rgb = (rgb * 255.499).round().astype(int) vertices = [ (*coord, *rgb) for coord, rgb in zip( coords.tolist(), rgb.tolist(), ) ] format = struct.Struct("<3f3B") for item in vertices: f.write(format.pack(*item)) else: format = struct.Struct("<3f") for vertex in coords.tolist(): f.write(format.pack(*vertex))
if faces is not None: format = struct.Struct("<B3I") for tri in faces.tolist(): f.write(format.pack(len(tri), *tri))
return output_ply_path
def export_to_obj(mesh, output_obj_path: str = None): if output_obj_path is None: output_obj_path = tempfile.NamedTemporaryFile(suffix=".obj").name
verts = mesh.verts.detach().cpu().numpy() faces = mesh.faces.cpu().numpy()
vertex_colors = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1) vertices = [ "{} {} {} {} {} {}".format(*coord, *color) for coord, color in zip(verts.tolist(), vertex_colors.tolist()) ]
faces = ["f {} {} {}".format(str(tri[0] + 1), str(tri[1] + 1), str(tri[2] + 1)) for tri in faces.tolist()]
combined_data = ["v " + vertex for vertex in vertices] + faces
with open(output_obj_path, "w") as f: f.writelines("\n".join(combined_data))
def _legacy_export_to_video( video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 10): if is_opencv_available(): import cv2 else: raise ImportError(BACKENDS_MAPPING["opencv"][1].format("export_to_video")) if output_video_path is None: output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name
if isinstance(video_frames[0], np.ndarray): video_frames = [(frame * 255).astype(np.uint8) for frame in video_frames]
elif isinstance(video_frames[0], PIL.Image.Image): video_frames = [np.array(frame) for frame in video_frames]
fourcc = cv2.VideoWriter_fourcc(*"mp4v") h, w, c = video_frames[0].shape video_writer = cv2.VideoWriter(output_video_path, fourcc, fps=fps, frameSize=(w, h)) for i in range(len(video_frames)): img = cv2.cvtColor(video_frames[i], cv2.COLOR_RGB2BGR) video_writer.write(img)
return output_video_path
def export_to_video( video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 10, quality: float = 5.0, bitrate: Optional[int] = None, macro_block_size: Optional[int] = 16,) -> str: """ quality: Video output quality. Default is 5. Uses variable bit rate. Highest quality is 10, lowest is 0. Set to None to prevent variable bitrate flags to FFMPEG so you can manually specify them using output_params instead. Specifying a fixed bitrate using `bitrate` disables this parameter.
bitrate: Set a constant bitrate for the video encoding. Default is None causing `quality` parameter to be used instead. Better quality videos with smaller file sizes will result from using the `quality` variable bitrate parameter rather than specifying a fixed bitrate with this parameter.
macro_block_size: Size constraint for video. Width and height, must be divisible by this number. If not divisible by this number imageio will tell ffmpeg to scale the image up to the next closest size divisible by this number. Most codecs are compatible with a macroblock size of 16 (default), some can go smaller (4, 8). To disable this automatic feature set it to None or 1, however be warned many players can't decode videos that are odd in size and some codecs will produce poor results or fail. See https://en.wikipedia.org/wiki/Macroblock. """ # TODO: Dhruv. Remove by Diffusers release 0.33.0 # Added to prevent breaking existing code if not is_imageio_available(): logger.warning( ( "It is recommended to use `export_to_video` with `imageio` and `imageio-ffmpeg` as a backend. \n" "These libraries are not present in your environment. Attempting to use legacy OpenCV backend to export video. \n" "Support for the OpenCV backend will be deprecated in a future Diffusers version" ) ) return _legacy_export_to_video(video_frames, output_video_path, fps)
if is_imageio_available(): import imageio else: raise ImportError(BACKENDS_MAPPING["imageio"][1].format("export_to_video"))
try: imageio.plugins.ffmpeg.get_exe() except AttributeError: raise AttributeError( ( "Found an existing imageio backend in your environment. Attempting to export video with imageio. \n" "Unable to find a compatible ffmpeg installation in your environment to use with imageio. Please install via `pip install imageio-ffmpeg" ) )
if output_video_path is None: output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name
if isinstance(video_frames[0], np.ndarray): video_frames = [(frame * 255).astype(np.uint8) for frame in video_frames]
elif isinstance(video_frames[0], PIL.Image.Image): video_frames = [np.array(frame) for frame in video_frames]
with imageio.get_writer( output_video_path, fps=fps, quality=quality, bitrate=bitrate, macro_block_size=macro_block_size ) as writer: for frame in video_frames: writer.append_data(frame)
return output_video_path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573# coding=utf-8# Copyright 2025 The HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import jsonimport osimport reimport sysimport tempfileimport warningsfrom pathlib import Pathfrom typing import Dict, List, Optional, Unionfrom uuid import uuid4
from huggingface_hub import ( DDUFEntry, ModelCard, ModelCardData, create_repo, hf_hub_download, model_info, snapshot_download, upload_folder,)from huggingface_hub.constants import HF_HUB_DISABLE_TELEMETRY, HF_HUB_OFFLINEfrom huggingface_hub.file_download import REGEX_COMMIT_HASHfrom huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, validate_hf_hub_args,)from packaging import versionfrom requests import HTTPError
from .. import __version__from .constants import ( DEPRECATED_REVISION_ARGS, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME,)from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available,)from .logging import get_logger
logger = get_logger(__name__)
MODEL_CARD_TEMPLATE_PATH = Path(__file__).parent / "model_card_template.md"SESSION_ID = uuid4().hex
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str: """ Formats a user-agent string with basic info about a request. """ ua = f"diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}" if HF_HUB_DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += f"; torch/{_torch_version}" if is_flax_available(): ua += f"; jax/{_jax_version}" ua += f"; flax/{_flax_version}" if is_onnx_available(): ua += f"; onnxruntime/{_onnxruntime_version}" # CI will set this value to True if os.environ.get("DIFFUSERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(user_agent, dict): ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items()) elif isinstance(user_agent, str): ua += "; " + user_agent return ua
def load_or_create_model_card( repo_id_or_path: str = None, token: Optional[str] = None, is_pipeline: bool = False, from_training: bool = False, model_description: Optional[str] = None, base_model: str = None, prompt: Optional[str] = None, license: Optional[str] = None, widget: Optional[List[dict]] = None, inference: Optional[bool] = None,) -> ModelCard: """ Loads or creates a model card.
Args: repo_id_or_path (`str`): The repo id (e.g., "runwayml/stable-diffusion-v1-5") or local path where to look for the model card. token (`str`, *optional*): Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more details. is_pipeline (`bool`): Boolean to indicate if we're adding tag to a [`DiffusionPipeline`]. from_training: (`bool`): Boolean flag to denote if the model card is being created from a training script. model_description (`str`, *optional*): Model description to add to the model card. Helpful when using `load_or_create_model_card` from a training script. base_model (`str`): Base model identifier (e.g., "stabilityai/stable-diffusion-xl-base-1.0"). Useful for DreamBooth-like training. prompt (`str`, *optional*): Prompt used for training. Useful for DreamBooth-like training. license: (`str`, *optional*): License of the output artifact. Helpful when using `load_or_create_model_card` from a training script. widget (`List[dict]`, *optional*): Widget to accompany a gallery template. inference: (`bool`, optional): Whether to turn on inference widget. Helpful when using `load_or_create_model_card` from a training script. """ if not is_jinja_available(): raise ValueError( "Modelcard rendering is based on Jinja templates." " Please make sure to have `jinja` installed before using `load_or_create_model_card`." " To install it, please run `pip install Jinja2`." )
try: # Check if the model card is present on the remote repo model_card = ModelCard.load(repo_id_or_path, token=token) except (EntryNotFoundError, RepositoryNotFoundError): # Otherwise create a model card from template if from_training: model_card = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block license=license, library_name="diffusers", inference=inference, base_model=base_model, instance_prompt=prompt, widget=widget, ), template_path=MODEL_CARD_TEMPLATE_PATH, model_description=model_description, ) else: card_data = ModelCardData() component = "pipeline" if is_pipeline else "model" if model_description is None: model_description = f"This is the model card of a 🧨 diffusers {component} that has been pushed on the Hub. This model card has been automatically generated." model_card = ModelCard.from_template(card_data, model_description=model_description)
return model_card
def populate_model_card(model_card: ModelCard, tags: Union[str, List[str]] = None) -> ModelCard: """Populates the `model_card` with library name and optional tags.""" if model_card.data.library_name is None: model_card.data.library_name = "diffusers"
if tags is not None: if isinstance(tags, str): tags = [tags] if model_card.data.tags is None: model_card.data.tags = [] for tag in tags: model_card.data.tags.append(tag)
return model_card
def extract_commit_hash(resolved_file: Optional[str], commit_hash: Optional[str] = None): """ Extracts the commit hash from a resolved filename toward a cache file. """ if resolved_file is None or commit_hash is not None: return commit_hash resolved_file = str(Path(resolved_file).as_posix()) search = re.search(r"snapshots/([^/]+)/", resolved_file) if search is None: return None commit_hash = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(commit_hash) else None
def _add_variant(weights_name: str, variant: Optional[str] = None) -> str: if variant is not None: splits = weights_name.split(".") splits = splits[:-1] + [variant] + splits[-1:] weights_name = ".".join(splits)
return weights_name
@validate_hf_hub_argsdef _get_model_file( pretrained_model_name_or_path: Union[str, Path], *, weights_name: str, subfolder: Optional[str] = None, cache_dir: Optional[str] = None, force_download: bool = False, proxies: Optional[Dict] = None, local_files_only: bool = False, token: Optional[str] = None, user_agent: Optional[Union[Dict, str]] = None, revision: Optional[str] = None, commit_hash: Optional[str] = None, dduf_entries: Optional[Dict[str, DDUFEntry]] = None,): pretrained_model_name_or_path = str(pretrained_model_name_or_path)
if dduf_entries: if subfolder is not None: raise ValueError( "DDUF file only allow for 1 level of directory (e.g transformer/model1/model.safetentors is not allowed). " "Please check the DDUF structure" ) model_file = ( weights_name if pretrained_model_name_or_path == "" else "/".join([pretrained_model_name_or_path, weights_name]) ) if model_file in dduf_entries: return model_file else: raise EnvironmentError(f"Error no file named {weights_name} found in archive {dduf_entries.keys()}.") elif os.path.isfile(pretrained_model_name_or_path): return pretrained_model_name_or_path elif os.path.isdir(pretrained_model_name_or_path): if os.path.isfile(os.path.join(pretrained_model_name_or_path, weights_name)): # Load from a PyTorch checkpoint model_file = os.path.join(pretrained_model_name_or_path, weights_name) return model_file elif subfolder is not None and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, weights_name) ): model_file = os.path.join(pretrained_model_name_or_path, subfolder, weights_name) return model_file else: raise EnvironmentError( f"Error no file named {weights_name} found in directory {pretrained_model_name_or_path}." ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(__version__).base_version) >= version.parse("0.22.0") ): try: model_file = hf_hub_download( pretrained_model_name_or_path, filename=_add_variant(weights_name, revision), cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, subfolder=subfolder, revision=revision or commit_hash, ) warnings.warn( f"Loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'` is deprecated. Loading instead from `revision='main'` with `variant={revision}`. Loading model variants via `revision='{revision}'` will be removed in diffusers v1. Please use `variant='{revision}'` instead.", FutureWarning, ) return model_file except: # noqa: E722 warnings.warn( f"You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant='{revision}'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(weights_name, revision)} file in the 'main' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title '{pretrained_model_name_or_path} is missing {_add_variant(weights_name, revision)}' so that the correct variant file can be added.", FutureWarning, ) try: # 2. Load model file as usual model_file = hf_hub_download( pretrained_model_name_or_path, filename=weights_name, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, subfolder=subfolder, revision=revision or commit_hash, ) return model_file
except RepositoryNotFoundError as e: raise EnvironmentError( f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier " "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a " "token having permission to this repo with `token` or log in with `hf auth login`." ) from e except RevisionNotFoundError as e: raise EnvironmentError( f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for " "this model name. Check the model page at " f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions." ) from e except EntryNotFoundError as e: raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named {weights_name}." ) from e except HTTPError as e: raise EnvironmentError( f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{e}" ) from e except ValueError as e: raise EnvironmentError( f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it" f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a" f" directory containing a file named {weights_name} or" " \nCheckout your internet connection or see how to run the library in" " offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'." ) from e except EnvironmentError as e: raise EnvironmentError( f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from " "'https://huggingface.co/models', make sure you don't have a local directory with the same name. " f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory " f"containing a file named {weights_name}" ) from e
def _get_checkpoint_shard_files( pretrained_model_name_or_path, index_filename, cache_dir=None, proxies=None, local_files_only=False, token=None, user_agent=None, revision=None, subfolder="", dduf_entries: Optional[Dict[str, DDUFEntry]] = None,): """ For a given model:
- download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the Hub - returns the list of paths to all the shards, as well as some metadata.
For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub). """ if dduf_entries: if index_filename not in dduf_entries: raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.") else: if not os.path.isfile(index_filename): raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.")
if dduf_entries: index = json.loads(dduf_entries[index_filename].read_text()) else: with open(index_filename, "r") as f: index = json.loads(f.read())
original_shard_filenames = sorted(set(index["weight_map"].values())) sharded_metadata = index["metadata"] sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys()) sharded_metadata["weight_map"] = index["weight_map"].copy() shards_path = os.path.join(pretrained_model_name_or_path, subfolder)
# First, let's deal with local folder. if os.path.isdir(pretrained_model_name_or_path) or dduf_entries: shard_filenames = [os.path.join(shards_path, f) for f in original_shard_filenames] for shard_file in shard_filenames: if dduf_entries: if shard_file not in dduf_entries: raise FileNotFoundError( f"{shards_path} does not appear to have a file named {shard_file} which is " "required according to the checkpoint index." ) else: if not os.path.exists(shard_file): raise FileNotFoundError( f"{shards_path} does not appear to have a file named {shard_file} which is " "required according to the checkpoint index." ) return shard_filenames, sharded_metadata
# At this stage pretrained_model_name_or_path is a model identifier on the Hub allow_patterns = original_shard_filenames if subfolder is not None: allow_patterns = [os.path.join(subfolder, p) for p in allow_patterns]
ignore_patterns = ["*.json", "*.md"]
# If the repo doesn't have the required shards, error out early even before downloading anything. if not local_files_only: model_files_info = model_info(pretrained_model_name_or_path, revision=revision, token=token) for shard_file in original_shard_filenames: shard_file_present = any(shard_file in k.rfilename for k in model_files_info.siblings) if not shard_file_present: raise EnvironmentError( f"{shards_path} does not appear to have a file named {shard_file} which is " "required according to the checkpoint index." )
try: # Load from URL cached_folder = snapshot_download( pretrained_model_name_or_path, cache_dir=cache_dir, proxies=proxies, local_files_only=local_files_only, token=token, revision=revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, user_agent=user_agent, ) if subfolder is not None: cached_folder = os.path.join(cached_folder, subfolder)
# We have already dealt with RepositoryNotFoundError and RevisionNotFoundError when getting the index, so # we don't have to catch them here. We have also dealt with EntryNotFoundError. except HTTPError as e: raise EnvironmentError( f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load {pretrained_model_name_or_path}. You should try" " again after checking your internet connection." ) from e
cached_filenames = [os.path.join(cached_folder, f) for f in original_shard_filenames] for cached_file in cached_filenames: if not os.path.isfile(cached_file): raise EnvironmentError( f"{cached_folder} does not have a file named {cached_file} which is required according to the checkpoint index." )
return cached_filenames, sharded_metadata
def _check_legacy_sharding_variant_format(folder: str = None, filenames: List[str] = None, variant: str = None): if filenames and folder: raise ValueError("Both `filenames` and `folder` cannot be provided.") if not filenames: filenames = [] for _, _, files in os.walk(folder): for file in files: filenames.append(os.path.basename(file)) transformers_index_format = r"\d{5}-of-\d{5}" variant_file_re = re.compile(rf".*-{transformers_index_format}\.{variant}\.[a-z]+$") return any(variant_file_re.match(f) is not None for f in filenames)
class PushToHubMixin: """ A Mixin to push a model, scheduler, or pipeline to the Hugging Face Hub. """
def _upload_folder( self, working_dir: Union[str, os.PathLike], repo_id: str, token: Optional[str] = None, commit_message: Optional[str] = None, create_pr: bool = False, subfolder: Optional[str] = None, ): """ Uploads all files in `working_dir` to `repo_id`. """ if commit_message is None: if "Model" in self.__class__.__name__: commit_message = "Upload model" elif "Scheduler" in self.__class__.__name__: commit_message = "Upload scheduler" else: commit_message = f"Upload {self.__class__.__name__}"
logger.info(f"Uploading the files of {working_dir} to {repo_id}.") return upload_folder( repo_id=repo_id, folder_path=working_dir, token=token, commit_message=commit_message, create_pr=create_pr, path_in_repo=subfolder, )
def push_to_hub( self, repo_id: str, commit_message: Optional[str] = None, private: Optional[bool] = None, token: Optional[str] = None, create_pr: bool = False, safe_serialization: bool = True, variant: Optional[str] = None, subfolder: Optional[str] = None, ) -> str: """ Upload model, scheduler, or pipeline files to the 🤗 Hugging Face Hub.
Parameters: repo_id (`str`): The name of the repository you want to push your model, scheduler, or pipeline files to. It should contain your organization name when pushing to an organization. `repo_id` can also be a path to a local directory. commit_message (`str`, *optional*): Message to commit while pushing. Default to `"Upload {object}"`. private (`bool`, *optional*): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. token (`str`, *optional*): The token to use as HTTP bearer authorization for remote files. The token generated when running `hf auth login` (stored in `~/.huggingface`). create_pr (`bool`, *optional*, defaults to `False`): Whether or not to create a PR with the uploaded files or directly commit. safe_serialization (`bool`, *optional*, defaults to `True`): Whether or not to convert the model weights to the `safetensors` format. variant (`str`, *optional*): If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
Examples:
```python from diffusers import UNet2DConditionModel
unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")
# Push the `unet` to your namespace with the name "my-finetuned-unet". unet.push_to_hub("my-finetuned-unet")
# Push the `unet` to an organization with the name "my-finetuned-unet". unet.push_to_hub("your-org/my-finetuned-unet") ``` """ repo_id = create_repo(repo_id, private=private, token=token, exist_ok=True).repo_id
# Create a new empty model card and eventually tag it if not subfolder: model_card = load_or_create_model_card(repo_id, token=token) model_card = populate_model_card(model_card)
# Save all files. save_kwargs = {"safe_serialization": safe_serialization} if "Scheduler" not in self.__class__.__name__: save_kwargs.update({"variant": variant})
with tempfile.TemporaryDirectory() as tmpdir: self.save_pretrained(tmpdir, **save_kwargs)
# Update model card if needed: if not subfolder: model_card.save(os.path.join(tmpdir, "README.md"))
return self._upload_folder( tmpdir, repo_id, token=token, commit_message=commit_message, create_pr=create_pr, subfolder=subfolder, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Import utilities: Utilities related to imports and our lazy inits."""
import importlib.utilimport inspectimport operator as opimport osimport sysfrom collections import OrderedDict, defaultdictfrom itertools import chainfrom types import ModuleTypefrom typing import Any, Tuple, Union
from huggingface_hub.utils import is_jinja_available # noqa: F401from packaging.version import Version, parse
from . import logging
# The package importlib_metadata is in a different place, depending on the python version.if sys.version_info < (3, 8): import importlib_metadataelse: import importlib.metadata as importlib_metadatatry: _package_map = importlib_metadata.packages_distributions() # load-once to avoid expensive callsexcept Exception: _package_map = None
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
USE_TF = os.environ.get("USE_TF", "AUTO").upper()USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()USE_SAFETENSORS = os.environ.get("USE_SAFETENSORS", "AUTO").upper()DIFFUSERS_SLOW_IMPORT = os.environ.get("DIFFUSERS_SLOW_IMPORT", "FALSE").upper()DIFFUSERS_SLOW_IMPORT = DIFFUSERS_SLOW_IMPORT in ENV_VARS_TRUE_VALUES
STR_OPERATION_TO_FUNC = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}
_is_google_colab = "google.colab" in sys.modules or any(k.startswith("COLAB_") for k in os.environ)
def _is_package_available(pkg_name: str, get_dist_name: bool = False) -> Tuple[bool, str]: global _package_map pkg_exists = importlib.util.find_spec(pkg_name) is not None pkg_version = "N/A"
if pkg_exists: if _package_map is None: _package_map = defaultdict(list) try: # Fallback for Python < 3.10 for dist in importlib_metadata.distributions(): _top_level_declared = (dist.read_text("top_level.txt") or "").split() # Infer top-level package names from file structure _inferred_opt_names = { f.parts[0] if len(f.parts) > 1 else inspect.getmodulename(f) for f in (dist.files or []) } - {None} _top_level_inferred = filter(lambda name: "." not in name, _inferred_opt_names) for pkg in _top_level_declared or _top_level_inferred: _package_map[pkg].append(dist.metadata["Name"]) except Exception as _: pass try: if get_dist_name and pkg_name in _package_map and _package_map[pkg_name]: if len(_package_map[pkg_name]) > 1: logger.warning( f"Multiple distributions found for package {pkg_name}. Picked distribution: {_package_map[pkg_name][0]}" ) pkg_name = _package_map[pkg_name][0] pkg_version = importlib_metadata.version(pkg_name) logger.debug(f"Successfully imported {pkg_name} version {pkg_version}") except (ImportError, importlib_metadata.PackageNotFoundError): pkg_exists = False
return pkg_exists, pkg_version
if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES: _torch_available, _torch_version = _is_package_available("torch")
else: logger.info("Disabling PyTorch because USE_TORCH is set") _torch_available = False _torch_version = "N/A"
_jax_version = "N/A"_flax_version = "N/A"if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES: _flax_available = importlib.util.find_spec("jax") is not None and importlib.util.find_spec("flax") is not None if _flax_available: try: _jax_version = importlib_metadata.version("jax") _flax_version = importlib_metadata.version("flax") logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.") except importlib_metadata.PackageNotFoundError: _flax_available = Falseelse: _flax_available = False
if USE_SAFETENSORS in ENV_VARS_TRUE_AND_AUTO_VALUES: _safetensors_available, _safetensors_version = _is_package_available("safetensors")
else: logger.info("Disabling Safetensors because USE_SAFETENSORS is set") _safetensors_available = False
_onnxruntime_version = "N/A"_onnx_available = importlib.util.find_spec("onnxruntime") is not Noneif _onnx_available: candidates = ( "onnxruntime", "onnxruntime-cann", "onnxruntime-directml", "ort_nightly_directml", "onnxruntime-gpu", "ort_nightly_gpu", "onnxruntime-migraphx", "onnxruntime-openvino", "onnxruntime-qnn", "onnxruntime-rocm", "onnxruntime-training", "onnxruntime-vitisai", ) _onnxruntime_version = None # For the metadata, we have to look for both onnxruntime and onnxruntime-x for pkg in candidates: try: _onnxruntime_version = importlib_metadata.version(pkg) break except importlib_metadata.PackageNotFoundError: pass _onnx_available = _onnxruntime_version is not None if _onnx_available: logger.debug(f"Successfully imported onnxruntime version {_onnxruntime_version}")
# (sayakpaul): importlib.util.find_spec("opencv-python") returns None even when it's installed.# _opencv_available = importlib.util.find_spec("opencv-python") is not Nonetry: candidates = ( "opencv-python", "opencv-contrib-python", "opencv-python-headless", "opencv-contrib-python-headless", ) _opencv_version = None for pkg in candidates: try: _opencv_version = importlib_metadata.version(pkg) break except importlib_metadata.PackageNotFoundError: pass _opencv_available = _opencv_version is not None if _opencv_available: logger.debug(f"Successfully imported cv2 version {_opencv_version}")except importlib_metadata.PackageNotFoundError: _opencv_available = False
_bs4_available = importlib.util.find_spec("bs4") is not Nonetry: # importlib metadata under different name _bs4_version = importlib_metadata.version("beautifulsoup4") logger.debug(f"Successfully imported ftfy version {_bs4_version}")except importlib_metadata.PackageNotFoundError: _bs4_available = False
_invisible_watermark_available = importlib.util.find_spec("imwatermark") is not Nonetry: _invisible_watermark_version = importlib_metadata.version("invisible-watermark") logger.debug(f"Successfully imported invisible-watermark version {_invisible_watermark_version}")except importlib_metadata.PackageNotFoundError: _invisible_watermark_available = False
_torch_xla_available, _torch_xla_version = _is_package_available("torch_xla")_torch_npu_available, _torch_npu_version = _is_package_available("torch_npu")_transformers_available, _transformers_version = _is_package_available("transformers")_hf_hub_available, _hf_hub_version = _is_package_available("huggingface_hub")_kernels_available, _kernels_version = _is_package_available("kernels")_inflect_available, _inflect_version = _is_package_available("inflect")_unidecode_available, _unidecode_version = _is_package_available("unidecode")_k_diffusion_available, _k_diffusion_version = _is_package_available("k_diffusion")_note_seq_available, _note_seq_version = _is_package_available("note_seq")_wandb_available, _wandb_version = _is_package_available("wandb")_tensorboard_available, _tensorboard_version = _is_package_available("tensorboard")_compel_available, _compel_version = _is_package_available("compel")_sentencepiece_available, _sentencepiece_version = _is_package_available("sentencepiece")_torchsde_available, _torchsde_version = _is_package_available("torchsde")_peft_available, _peft_version = _is_package_available("peft")_torchvision_available, _torchvision_version = _is_package_available("torchvision")_matplotlib_available, _matplotlib_version = _is_package_available("matplotlib")_timm_available, _timm_version = _is_package_available("timm")_bitsandbytes_available, _bitsandbytes_version = _is_package_available("bitsandbytes")_imageio_available, _imageio_version = _is_package_available("imageio")_ftfy_available, _ftfy_version = _is_package_available("ftfy")_scipy_available, _scipy_version = _is_package_available("scipy")_librosa_available, _librosa_version = _is_package_available("librosa")_accelerate_available, _accelerate_version = _is_package_available("accelerate")_xformers_available, _xformers_version = _is_package_available("xformers")_gguf_available, _gguf_version = _is_package_available("gguf")_torchao_available, _torchao_version = _is_package_available("torchao")_bitsandbytes_available, _bitsandbytes_version = _is_package_available("bitsandbytes")_optimum_quanto_available, _optimum_quanto_version = _is_package_available("optimum", get_dist_name=True)_pytorch_retinaface_available, _pytorch_retinaface_version = _is_package_available("pytorch_retinaface")_better_profanity_available, _better_profanity_version = _is_package_available("better_profanity")_nltk_available, _nltk_version = _is_package_available("nltk")_cosmos_guardrail_available, _cosmos_guardrail_version = _is_package_available("cosmos_guardrail")_sageattention_available, _sageattention_version = _is_package_available("sageattention")_flash_attn_available, _flash_attn_version = _is_package_available("flash_attn")_flash_attn_3_available, _flash_attn_3_version = _is_package_available("flash_attn_3")_kornia_available, _kornia_version = _is_package_available("kornia")
def is_torch_available(): return _torch_available
def is_torch_xla_available(): return _torch_xla_available
def is_torch_npu_available(): return _torch_npu_available
def is_flax_available(): return _flax_available
def is_transformers_available(): return _transformers_available
def is_inflect_available(): return _inflect_available
def is_unidecode_available(): return _unidecode_available
def is_onnx_available(): return _onnx_available
def is_opencv_available(): return _opencv_available
def is_scipy_available(): return _scipy_available
def is_librosa_available(): return _librosa_available
def is_xformers_available(): return _xformers_available
def is_accelerate_available(): return _accelerate_available
def is_kernels_available(): return _kernels_available
def is_k_diffusion_available(): return _k_diffusion_available
def is_note_seq_available(): return _note_seq_available
def is_wandb_available(): return _wandb_available
def is_tensorboard_available(): return _tensorboard_available
def is_compel_available(): return _compel_available
def is_ftfy_available(): return _ftfy_available
def is_bs4_available(): return _bs4_available
def is_torchsde_available(): return _torchsde_available
def is_invisible_watermark_available(): return _invisible_watermark_available
def is_peft_available(): return _peft_available
def is_torchvision_available(): return _torchvision_available
def is_matplotlib_available(): return _matplotlib_available
def is_safetensors_available(): return _safetensors_available
def is_bitsandbytes_available(): return _bitsandbytes_available
def is_google_colab(): return _is_google_colab
def is_sentencepiece_available(): return _sentencepiece_available
def is_imageio_available(): return _imageio_available
def is_gguf_available(): return _gguf_available
def is_torchao_available(): return _torchao_available
def is_optimum_quanto_available(): return _optimum_quanto_available
def is_timm_available(): return _timm_available
def is_pytorch_retinaface_available(): return _pytorch_retinaface_available
def is_better_profanity_available(): return _better_profanity_available
def is_nltk_available(): return _nltk_available
def is_cosmos_guardrail_available(): return _cosmos_guardrail_available
def is_hpu_available(): return all(importlib.util.find_spec(lib) for lib in ("habana_frameworks", "habana_frameworks.torch"))
def is_sageattention_available(): return _sageattention_available
def is_flash_attn_available(): return _flash_attn_available
def is_flash_attn_3_available(): return _flash_attn_3_available
def is_kornia_available(): return _kornia_available
# docstyle-ignoreFLAX_IMPORT_ERROR = """{0} requires the FLAX library but it was not found in your environment. Checkout the instructions on theinstallation page: https://github.com/google/flax and follow the ones that match your environment."""
# docstyle-ignoreINFLECT_IMPORT_ERROR = """{0} requires the inflect library but it was not found in your environment. You can install it with pip: `pip installinflect`"""
# docstyle-ignorePYTORCH_IMPORT_ERROR = """{0} requires the PyTorch library but it was not found in your environment. Checkout the instructions on theinstallation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment."""
# docstyle-ignoreONNX_IMPORT_ERROR = """{0} requires the onnxruntime library but it was not found in your environment. You can install it with pip: `pipinstall onnxruntime`"""
# docstyle-ignoreOPENCV_IMPORT_ERROR = """{0} requires the OpenCV library but it was not found in your environment. You can install it with pip: `pipinstall opencv-python`"""
# docstyle-ignoreSCIPY_IMPORT_ERROR = """{0} requires the scipy library but it was not found in your environment. You can install it with pip: `pip installscipy`"""
# docstyle-ignoreLIBROSA_IMPORT_ERROR = """{0} requires the librosa library but it was not found in your environment. Checkout the instructions on theinstallation page: https://librosa.org/doc/latest/install.html and follow the ones that match your environment."""
# docstyle-ignoreTRANSFORMERS_IMPORT_ERROR = """{0} requires the transformers library but it was not found in your environment. You can install it with pip: `pipinstall transformers`"""
# docstyle-ignoreUNIDECODE_IMPORT_ERROR = """{0} requires the unidecode library but it was not found in your environment. You can install it with pip: `pip installUnidecode`"""
# docstyle-ignoreK_DIFFUSION_IMPORT_ERROR = """{0} requires the k-diffusion library but it was not found in your environment. You can install it with pip: `pipinstall k-diffusion`"""
# docstyle-ignoreNOTE_SEQ_IMPORT_ERROR = """{0} requires the note-seq library but it was not found in your environment. You can install it with pip: `pipinstall note-seq`"""
# docstyle-ignoreWANDB_IMPORT_ERROR = """{0} requires the wandb library but it was not found in your environment. You can install it with pip: `pipinstall wandb`"""
# docstyle-ignoreTENSORBOARD_IMPORT_ERROR = """{0} requires the tensorboard library but it was not found in your environment. You can install it with pip: `pipinstall tensorboard`"""
# docstyle-ignoreCOMPEL_IMPORT_ERROR = """{0} requires the compel library but it was not found in your environment. You can install it with pip: `pip install compel`"""
# docstyle-ignoreBS4_IMPORT_ERROR = """{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation."""
# docstyle-ignoreFTFY_IMPORT_ERROR = """{0} requires the ftfy library but it was not found in your environment. Checkout the instructions on theinstallation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the onesthat match your environment. Please note that you may need to restart your runtime after installation."""
# docstyle-ignoreTORCHSDE_IMPORT_ERROR = """{0} requires the torchsde library but it was not found in your environment. You can install it with pip: `pip install torchsde`"""
# docstyle-ignoreINVISIBLE_WATERMARK_IMPORT_ERROR = """{0} requires the invisible-watermark library but it was not found in your environment. You can install it with pip: `pip install invisible-watermark>=0.2.0`"""
# docstyle-ignorePEFT_IMPORT_ERROR = """{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install peft`"""
# docstyle-ignoreSAFETENSORS_IMPORT_ERROR = """{0} requires the safetensors library but it was not found in your environment. You can install it with pip: `pip install safetensors`"""
# docstyle-ignoreSENTENCEPIECE_IMPORT_ERROR = """{0} requires the sentencepiece library but it was not found in your environment. You can install it with pip: `pip install sentencepiece`"""
# docstyle-ignoreBITSANDBYTES_IMPORT_ERROR = """{0} requires the bitsandbytes library but it was not found in your environment. You can install it with pip: `pip install bitsandbytes`"""
# docstyle-ignoreIMAGEIO_IMPORT_ERROR = """{0} requires the imageio library and ffmpeg but it was not found in your environment. You can install it with pip: `pip install imageio imageio-ffmpeg`"""
# docstyle-ignoreGGUF_IMPORT_ERROR = """{0} requires the gguf library but it was not found in your environment. You can install it with pip: `pip install gguf`"""
TORCHAO_IMPORT_ERROR = """{0} requires the torchao library but it was not found in your environment. You can install it with pip: `pip installtorchao`"""
QUANTO_IMPORT_ERROR = """{0} requires the optimum-quanto library but it was not found in your environment. You can install it with pip: `pipinstall optimum-quanto`"""
# docstyle-ignorePYTORCH_RETINAFACE_IMPORT_ERROR = """{0} requires the pytorch_retinaface library but it was not found in your environment. You can install it with pip: `pip install pytorch_retinaface`"""
# docstyle-ignoreBETTER_PROFANITY_IMPORT_ERROR = """{0} requires the better_profanity library but it was not found in your environment. You can install it with pip: `pip install better_profanity`"""
# docstyle-ignoreNLTK_IMPORT_ERROR = """{0} requires the nltk library but it was not found in your environment. You can install it with pip: `pip install nltk`"""
BACKENDS_MAPPING = OrderedDict( [ ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)), ("flax", (is_flax_available, FLAX_IMPORT_ERROR)), ("inflect", (is_inflect_available, INFLECT_IMPORT_ERROR)), ("onnx", (is_onnx_available, ONNX_IMPORT_ERROR)), ("opencv", (is_opencv_available, OPENCV_IMPORT_ERROR)), ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)), ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)), ("transformers", (is_transformers_available, TRANSFORMERS_IMPORT_ERROR)), ("unidecode", (is_unidecode_available, UNIDECODE_IMPORT_ERROR)), ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)), ("k_diffusion", (is_k_diffusion_available, K_DIFFUSION_IMPORT_ERROR)), ("note_seq", (is_note_seq_available, NOTE_SEQ_IMPORT_ERROR)), ("wandb", (is_wandb_available, WANDB_IMPORT_ERROR)), ("tensorboard", (is_tensorboard_available, TENSORBOARD_IMPORT_ERROR)), ("compel", (is_compel_available, COMPEL_IMPORT_ERROR)), ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)), ("torchsde", (is_torchsde_available, TORCHSDE_IMPORT_ERROR)), ("invisible_watermark", (is_invisible_watermark_available, INVISIBLE_WATERMARK_IMPORT_ERROR)), ("peft", (is_peft_available, PEFT_IMPORT_ERROR)), ("safetensors", (is_safetensors_available, SAFETENSORS_IMPORT_ERROR)), ("bitsandbytes", (is_bitsandbytes_available, BITSANDBYTES_IMPORT_ERROR)), ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)), ("imageio", (is_imageio_available, IMAGEIO_IMPORT_ERROR)), ("gguf", (is_gguf_available, GGUF_IMPORT_ERROR)), ("torchao", (is_torchao_available, TORCHAO_IMPORT_ERROR)), ("quanto", (is_optimum_quanto_available, QUANTO_IMPORT_ERROR)), ("pytorch_retinaface", (is_pytorch_retinaface_available, PYTORCH_RETINAFACE_IMPORT_ERROR)), ("better_profanity", (is_better_profanity_available, BETTER_PROFANITY_IMPORT_ERROR)), ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)), ])
def requires_backends(obj, backends): if not isinstance(backends, (list, tuple)): backends = [backends]
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__ checks = (BACKENDS_MAPPING[backend] for backend in backends) failed = [msg.format(name) for available, msg in checks if not available()] if failed: raise ImportError("".join(failed))
if name in [ "VersatileDiffusionTextToImagePipeline", "VersatileDiffusionPipeline", "VersatileDiffusionDualGuidedPipeline", "StableDiffusionImageVariationPipeline", "UnCLIPPipeline", ] and is_transformers_version("<", "4.25.0"): raise ImportError( f"You need to install `transformers>=4.25` in order to use {name}: \n```\n pip install" " --upgrade transformers \n```" )
if name in ["StableDiffusionDepth2ImgPipeline", "StableDiffusionPix2PixZeroPipeline"] and is_transformers_version( "<", "4.26.0" ): raise ImportError( f"You need to install `transformers>=4.26` in order to use {name}: \n```\n pip install" " --upgrade transformers \n```" )
class DummyObject(type): """ Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by `requires_backend` each time a user tries to access any method of that class. """
def __getattr__(cls, key): if key.startswith("_") and key not in ["_load_connected_pipes", "_is_onnx"]: return super().__getattr__(cls, key) requires_backends(cls, cls._backends)
# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L319def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str): """ Compares a library version to some requirement using a given operation.
Args: library_or_version (`str` or `packaging.version.Version`): A library name or a version to check. operation (`str`): A string representation of an operator, such as `">"` or `"<="`. requirement_version (`str`): The version to compare the library version against """ if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}, received {operation}") operation = STR_OPERATION_TO_FUNC[operation] if isinstance(library_or_version, str): library_or_version = parse(importlib_metadata.version(library_or_version)) return operation(library_or_version, parse(requirement_version))
# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L338def is_torch_version(operation: str, version: str): """ Compares the current PyTorch version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A string version of PyTorch """ return compare_versions(parse(_torch_version), operation, version)
def is_torch_xla_version(operation: str, version: str): """ Compares the current torch_xla version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A string version of torch_xla """ if not is_torch_xla_available: return False return compare_versions(parse(_torch_xla_version), operation, version)
def is_transformers_version(operation: str, version: str): """ Compares the current Transformers version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _transformers_available: return False return compare_versions(parse(_transformers_version), operation, version)
def is_hf_hub_version(operation: str, version: str): """ Compares the current Hugging Face Hub version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _hf_hub_available: return False return compare_versions(parse(_hf_hub_version), operation, version)
def is_accelerate_version(operation: str, version: str): """ Compares the current Accelerate version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _accelerate_available: return False return compare_versions(parse(_accelerate_version), operation, version)
def is_peft_version(operation: str, version: str): """ Compares the current PEFT version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _peft_available: return False return compare_versions(parse(_peft_version), operation, version)
def is_bitsandbytes_version(operation: str, version: str): """ Args: Compares the current bitsandbytes version to a given reference with an operation. operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _bitsandbytes_available: return False return compare_versions(parse(_bitsandbytes_version), operation, version)
def is_gguf_version(operation: str, version: str): """ Compares the current Accelerate version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _gguf_available: return False return compare_versions(parse(_gguf_version), operation, version)
def is_torchao_version(operation: str, version: str): """ Compares the current torchao version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _torchao_available: return False return compare_versions(parse(_torchao_version), operation, version)
def is_k_diffusion_version(operation: str, version: str): """ Compares the current k-diffusion version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _k_diffusion_available: return False return compare_versions(parse(_k_diffusion_version), operation, version)
def is_optimum_quanto_version(operation: str, version: str): """ Compares the current Accelerate version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _optimum_quanto_available: return False return compare_versions(parse(_optimum_quanto_version), operation, version)
def is_xformers_version(operation: str, version: str): """ Compares the current xformers version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _xformers_available: return False return compare_versions(parse(_xformers_version), operation, version)
def is_sageattention_version(operation: str, version: str): """ Compares the current sageattention version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _sageattention_available: return False return compare_versions(parse(_sageattention_version), operation, version)
def is_flash_attn_version(operation: str, version: str): """ Compares the current flash-attention version to a given reference with an operation.
Args: operation (`str`): A string representation of an operator, such as `">"` or `"<="` version (`str`): A version string """ if not _flash_attn_available: return False return compare_versions(parse(_flash_attn_version), operation, version)
def get_objects_from_module(module): """ Returns a dict of object names and values in a module, while skipping private/internal objects
Args: module (ModuleType): Module to extract the objects from.
Returns: dict: Dictionary of object names and corresponding values """
objects = {} for name in dir(module): if name.startswith("_"): continue objects[name] = getattr(module, name)
return objects
class OptionalDependencyNotAvailable(BaseException): """ An error indicating that an optional dependency of Diffusers was not found in the environment. """
class _LazyModule(ModuleType): """ Module class that surfaces all objects but only performs associated imports when the objects are requested. """
# Very heavily inspired by optuna.integration._IntegrationModule # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): super().__init__(name) self._modules = set(import_structure.keys()) self._class_to_module = {} for key, values in import_structure.items(): for value in values: self._class_to_module[value] = key # Needed for autocompletion in an IDE self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) self.__file__ = module_file self.__spec__ = module_spec self.__path__ = [os.path.dirname(module_file)] self._objects = {} if extra_objects is None else extra_objects self._name = name self._import_structure = import_structure
# Needed for autocompletion in an IDE def __dir__(self): result = super().__dir__() # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. for attr in self.__all__: if attr not in result: result.append(attr) return result
def __getattr__(self, name: str) -> Any: if name in self._objects: return self._objects[name] if name in self._modules: value = self._get_module(name) elif name in self._class_to_module.keys(): module = self._get_module(self._class_to_module[name]) value = getattr(module, name) else: raise AttributeError(f"module {self.__name__} has no attribute {name}")
setattr(self, name, value) return value
def _get_module(self, module_name: str): try: return importlib.import_module("." + module_name, self.__name__) except Exception as e: raise RuntimeError( f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" f" traceback):\n{e}" ) from e
def __reduce__(self): return (self.__class__, (self._name, self.__file__, self._import_structure))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210import osimport tempfilefrom typing import Any, Callable, List, Optional, Tuple, Unionfrom urllib.parse import unquote, urlparse
import librosaimport numpyimport PIL.Imageimport PIL.ImageOpsimport requests
from .constants import DIFFUSERS_REQUEST_TIMEOUTfrom .import_utils import BACKENDS_MAPPING, is_imageio_available
def load_image( image: Union[str, PIL.Image.Image], convert_method: Optional[Callable[[PIL.Image.Image], PIL.Image.Image]] = None) -> PIL.Image.Image: """ Loads `image` to a PIL Image.
Args: image (`str` or `PIL.Image.Image`): The image to convert to the PIL Image format. convert_method (Callable[[PIL.Image.Image], PIL.Image.Image], *optional*): A conversion method to apply to the image after loading it. When set to `None` the image will be converted "RGB".
Returns: `PIL.Image.Image`: A PIL Image. """ if isinstance(image, str): if image.startswith("http://") or image.startswith("https://"): image = PIL.Image.open(requests.get(image, stream=True, timeout=DIFFUSERS_REQUEST_TIMEOUT).raw) elif os.path.isfile(image): image = PIL.Image.open(image) else: raise ValueError( f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {image} is not a valid path." ) elif isinstance(image, PIL.Image.Image): image = image else: raise ValueError( "Incorrect format used for the image. Should be a URL linking to an image, a local path, or a PIL image." )
image = PIL.ImageOps.exif_transpose(image)
if convert_method is not None: image = convert_method(image) else: image = image.convert("RGB")
return image
def load_video( video: str, convert_method: Optional[Callable[[List[PIL.Image.Image]], List[PIL.Image.Image]]] = None,) -> List[PIL.Image.Image]: """ Loads `video` to a list of PIL Image.
Args: video (`str`): A URL or Path to a video to convert to a list of PIL Image format. convert_method (Callable[[List[PIL.Image.Image]], List[PIL.Image.Image]], *optional*): A conversion method to apply to the video after loading it. When set to `None` the images will be converted to "RGB".
Returns: `List[PIL.Image.Image]`: The video as a list of PIL images. """ is_url = video.startswith("http://") or video.startswith("https://") is_file = os.path.isfile(video) was_tempfile_created = False
if not (is_url or is_file): raise ValueError( f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {video} is not a valid path." )
if is_url: response = requests.get(video, stream=True) if response.status_code != 200: raise ValueError(f"Failed to download video. Status code: {response.status_code}")
parsed_url = urlparse(video) file_name = os.path.basename(unquote(parsed_url.path))
suffix = os.path.splitext(file_name)[1] or ".mp4" video_path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False).name
was_tempfile_created = True
video_data = response.iter_content(chunk_size=8192) with open(video_path, "wb") as f: for chunk in video_data: f.write(chunk)
video = video_path
pil_images = [] if video.endswith(".gif"): gif = PIL.Image.open(video) try: while True: pil_images.append(gif.copy()) gif.seek(gif.tell() + 1) except EOFError: pass
else: if is_imageio_available(): import imageio else: raise ImportError(BACKENDS_MAPPING["imageio"][1].format("load_video"))
try: imageio.plugins.ffmpeg.get_exe() except AttributeError: raise AttributeError( "`Unable to find an ffmpeg installation on your machine. Please install via `pip install imageio-ffmpeg" )
with imageio.get_reader(video) as reader: # Read all frames for frame in reader: pil_images.append(PIL.Image.fromarray(frame))
if was_tempfile_created: os.remove(video_path)
if convert_method is not None: pil_images = convert_method(pil_images)
return pil_images
def load_audio( audio: Union[str, numpy.ndarray], convert_method: Optional[Callable[[numpy.ndarray], numpy.ndarray]] = None) -> numpy.ndarray: """ Loads `audio` to a numpy array.
Args: audio (`str` or `numpy.ndarray`): The audio to convert to the numpy array format. convert_method (Callable[[numpy.ndarray], numpy.ndarray], *optional*): A conversion method to apply to the audio after loading it. When set to `None` the audio will be converted to a specific format.
Returns: `numpy.ndarray`: A Librosa audio object. `int`: The sample rate of the audio. """ if isinstance(audio, str): if audio.startswith("http://") or audio.startswith("https://"): audio = PIL.Image.open(requests.get(audio, stream=True, timeout=DIFFUSERS_REQUEST_TIMEOUT).raw) elif os.path.isfile(audio): audio, sample_rate = librosa.load(audio, sr=16000) else: raise ValueError( f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {audio} is not a valid path." ) elif isinstance(audio, numpy.ndarray): audio = audio else: raise ValueError( "Incorrect format used for the audio. Should be a URL linking to an audio, a local path, or a PIL audio." )
# audio = PIL.ImageOps.exif_transpose(audio)
if convert_method is not None: audio = convert_method(audio) else: audio = audio.convert("RGB")
return audio, sample_rate
# Taken from `transformers`.def get_module_from_name(module, tensor_name: str) -> Tuple[Any, str]: if "." in tensor_name: splits = tensor_name.split(".") for split in splits[:-1]: new_module = getattr(module, split) if new_module is None: raise ValueError(f"{module} has no attribute {split}.") module = new_module tensor_name = splits[-1] return module, tensor_name
def get_submodule_by_name(root_module, module_path: str): current = root_module parts = module_path.split(".") for part in parts: if part.isdigit(): idx = int(part) current = current[idx] # e.g., for nn.ModuleList or nn.Sequential else: current = getattr(current, part) return current123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340# coding=utf-8# Copyright 2025 Optuna, Hugging Face## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Logging utilities."""
import loggingimport osimport sysimport threadingfrom logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA)from typing import Dict, Optional
from tqdm import auto as tqdm_lib
_lock = threading.Lock()_default_handler: Optional[logging.Handler] = None
log_levels = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL,}
_default_log_level = logging.WARNING
_tqdm_active = True
def _get_default_logging_level() -> int: """ If DIFFUSERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is not - fall back to `_default_log_level` """ env_level_str = os.getenv("DIFFUSERS_VERBOSITY", None) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"Unknown option DIFFUSERS_VERBOSITY={env_level_str}, has to be one of: {', '.join(log_levels.keys())}" ) return _default_log_level
def _get_library_name() -> str: return __name__.split(".")[0]
def _get_library_root_logger() -> logging.Logger: return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None: global _default_handler
with _lock: if _default_handler: # This library has already configured the library root logger. return _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
if sys.stderr: # only if sys.stderr exists, e.g. when not using pythonw in windows _default_handler.flush = sys.stderr.flush
# Apply our default configuration to the library root logger. library_root_logger = _get_library_root_logger() library_root_logger.addHandler(_default_handler) library_root_logger.setLevel(_get_default_logging_level()) library_root_logger.propagate = False
def _reset_library_root_logger() -> None: global _default_handler
with _lock: if not _default_handler: return
library_root_logger = _get_library_root_logger() library_root_logger.removeHandler(_default_handler) library_root_logger.setLevel(logging.NOTSET) _default_handler = None
def get_log_levels_dict() -> Dict[str, int]: return log_levels
def get_logger(name: Optional[str] = None) -> logging.Logger: """ Return a logger with the specified name.
This function is not supposed to be directly accessed unless you are writing a custom diffusers module. """
if name is None: name = _get_library_name()
_configure_library_root_logger() return logging.getLogger(name)
def get_verbosity() -> int: """ Return the current level for the 🤗 Diffusers' root logger as an `int`.
Returns: `int`: Logging level integers which can be one of:
- `50`: `diffusers.logging.CRITICAL` or `diffusers.logging.FATAL` - `40`: `diffusers.logging.ERROR` - `30`: `diffusers.logging.WARNING` or `diffusers.logging.WARN` - `20`: `diffusers.logging.INFO` - `10`: `diffusers.logging.DEBUG`
"""
_configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel()
def set_verbosity(verbosity: int) -> None: """ Set the verbosity level for the 🤗 Diffusers' root logger.
Args: verbosity (`int`): Logging level which can be one of:
- `diffusers.logging.CRITICAL` or `diffusers.logging.FATAL` - `diffusers.logging.ERROR` - `diffusers.logging.WARNING` or `diffusers.logging.WARN` - `diffusers.logging.INFO` - `diffusers.logging.DEBUG` """
_configure_library_root_logger() _get_library_root_logger().setLevel(verbosity)
def set_verbosity_info() -> None: """Set the verbosity to the `INFO` level.""" return set_verbosity(INFO)
def set_verbosity_warning() -> None: """Set the verbosity to the `WARNING` level.""" return set_verbosity(WARNING)
def set_verbosity_debug() -> None: """Set the verbosity to the `DEBUG` level.""" return set_verbosity(DEBUG)
def set_verbosity_error() -> None: """Set the verbosity to the `ERROR` level.""" return set_verbosity(ERROR)
def disable_default_handler() -> None: """Disable the default handler of the 🤗 Diffusers' root logger."""
_configure_library_root_logger()
assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler)
def enable_default_handler() -> None: """Enable the default handler of the 🤗 Diffusers' root logger."""
_configure_library_root_logger()
assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler)
def add_handler(handler: logging.Handler) -> None: """adds a handler to the HuggingFace Diffusers' root logger."""
_configure_library_root_logger()
assert handler is not None _get_library_root_logger().addHandler(handler)
def remove_handler(handler: logging.Handler) -> None: """removes given handler from the HuggingFace Diffusers' root logger."""
_configure_library_root_logger()
assert handler is not None and handler in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(handler)
def disable_propagation() -> None: """ Disable propagation of the library log outputs. Note that log propagation is disabled by default. """
_configure_library_root_logger() _get_library_root_logger().propagate = False
def enable_propagation() -> None: """ Enable propagation of the library log outputs. Please disable the HuggingFace Diffusers' default handler to prevent double logging if the root logger has been configured. """
_configure_library_root_logger() _get_library_root_logger().propagate = True
def enable_explicit_format() -> None: """ Enable explicit formatting for every 🤗 Diffusers' logger. The explicit formatter is as follows: ``` [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE ``` All handlers currently bound to the root logger are affected by this method. """ handlers = _get_library_root_logger().handlers
for handler in handlers: formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s") handler.setFormatter(formatter)
def reset_format() -> None: """ Resets the formatting for 🤗 Diffusers' loggers.
All handlers currently bound to the root logger are affected by this method. """ handlers = _get_library_root_logger().handlers
for handler in handlers: handler.setFormatter(None)
def warning_advice(self, *args, **kwargs) -> None: """ This method is identical to `logger.warning()`, but if env var DIFFUSERS_NO_ADVISORY_WARNINGS=1 is set, this warning will not be printed """ no_advisory_warnings = os.getenv("DIFFUSERS_NO_ADVISORY_WARNINGS", False) if no_advisory_warnings: return self.warning(*args, **kwargs)
logging.Logger.warning_advice = warning_advice
class EmptyTqdm: """Dummy tqdm which doesn't do anything."""
def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self._iterator = args[0] if args else None
def __iter__(self): return iter(self._iterator)
def __getattr__(self, _): """Return empty function."""
def empty_fn(*args, **kwargs): # pylint: disable=unused-argument return
return empty_fn
def __enter__(self): return self
def __exit__(self, type_, value, traceback): return
class _tqdm_cls: def __call__(self, *args, **kwargs): if _tqdm_active: return tqdm_lib.tqdm(*args, **kwargs) else: return EmptyTqdm(*args, **kwargs)
def set_lock(self, *args, **kwargs): self._lock = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*args, **kwargs)
def get_lock(self): if _tqdm_active: return tqdm_lib.tqdm.get_lock()
tqdm = _tqdm_cls()
def is_progress_bar_enabled() -> bool: """Return a boolean indicating whether tqdm progress bars are enabled.""" global _tqdm_active return bool(_tqdm_active)
def enable_progress_bar() -> None: """Enable tqdm progress bar.""" global _tqdm_active _tqdm_active = True
def disable_progress_bar() -> None: """Disable tqdm progress bar.""" global _tqdm_active _tqdm_active = False123456789101112131415161718192021222324---{{ card_data }}---
<!-- This model card has been generated automatically according to the information the training script had access to. Youshould probably proofread and complete it, then remove this comment. -->
{{ model_description }}
## Intended uses & limitations
#### How to use
```python# TODO: add an example code snippet for running this diffusion pipeline```
#### Limitations and bias
[TODO: provide examples of latent issues and potential remediations]
## Training details
[TODO: describe the data used to train the model]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Generic utilities"""
from collections import OrderedDictfrom dataclasses import fields, is_dataclassfrom typing import Any, Tuple
import numpy as np
from .import_utils import is_torch_available, is_torch_version
def is_tensor(x) -> bool: """ Tests if `x` is a `torch.Tensor` or `np.ndarray`. """ if is_torch_available(): import torch
if isinstance(x, torch.Tensor): return True
return isinstance(x, np.ndarray)
class BaseOutput(OrderedDict): """ Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular Python dictionary.
<Tip warning={true}>
You can't unpack a [`BaseOutput`] directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple first.
</Tip> """
def __init_subclass__(cls) -> None: """Register subclasses as pytree nodes.
This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with `static_graph=True` with modules that output `ModelOutput` subclasses. """ if is_torch_available(): import torch.utils._pytree
if is_torch_version("<", "2.2"): torch.utils._pytree._register_pytree_node( cls, torch.utils._pytree._dict_flatten, lambda values, context: cls(**torch.utils._pytree._dict_unflatten(values, context)), ) else: torch.utils._pytree.register_pytree_node( cls, torch.utils._pytree._dict_flatten, lambda values, context: cls(**torch.utils._pytree._dict_unflatten(values, context)), serialized_type_name=f"{cls.__module__}.{cls.__name__}", )
def __post_init__(self) -> None: class_fields = fields(self)
# Safety and consistency checks if not len(class_fields): raise ValueError(f"{self.__class__.__name__} has no fields.")
first_field = getattr(self, class_fields[0].name) other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])
if other_fields_are_none and isinstance(first_field, dict): for key, value in first_field.items(): self[key] = value else: for field in class_fields: v = getattr(self, field.name) if v is not None: self[field.name] = v
def __delitem__(self, *args, **kwargs): raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
def setdefault(self, *args, **kwargs): raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
def pop(self, *args, **kwargs): raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
def update(self, *args, **kwargs): raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
def __getitem__(self, k: Any) -> Any: if isinstance(k, str): inner_dict = dict(self.items()) return inner_dict[k] else: return self.to_tuple()[k]
def __setattr__(self, name: Any, value: Any) -> None: if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(name, value) super().__setattr__(name, value)
def __setitem__(self, key, value): # Will raise a KeyException if needed super().__setitem__(key, value) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(key, value)
def __reduce__(self): if not is_dataclass(self): return super().__reduce__() callable, _args, *remaining = super().__reduce__() args = tuple(getattr(self, field.name) for field in fields(self)) return callable, args, *remaining
def to_tuple(self) -> Tuple[Any, ...]: """ Convert self to a tuple containing all the attributes/keys that are not `None`. """ return tuple(self[k] for k in self.keys())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""PEFT utilities: Utilities related to peft library"""
import collectionsimport importlibfrom typing import Optional
from packaging import version
from . import loggingfrom .import_utils import is_peft_available, is_peft_version, is_torch_availablefrom .torch_utils import empty_device_cache
logger = logging.get_logger(__name__)
if is_torch_available(): import torch
def recurse_remove_peft_layers(model): r""" Recursively replace all instances of `LoraLayer` with corresponding new layers in `model`. """ from peft.tuners.tuners_utils import BaseTunerLayer
has_base_layer_pattern = False for module in model.modules(): if isinstance(module, BaseTunerLayer): has_base_layer_pattern = hasattr(module, "base_layer") break
if has_base_layer_pattern: from peft.utils import _get_submodules
key_list = [key for key, _ in model.named_modules() if "lora" not in key] for key in key_list: try: parent, target, target_name = _get_submodules(model, key) except AttributeError: continue if hasattr(target, "base_layer"): setattr(parent, target_name, target.get_base_layer()) else: # This is for backwards compatibility with PEFT <= 0.6.2. # TODO can be removed once that PEFT version is no longer supported. from peft.tuners.lora import LoraLayer
for name, module in model.named_children(): if len(list(module.children())) > 0: ## compound module, go inside it recurse_remove_peft_layers(module)
module_replaced = False
if isinstance(module, LoraLayer) and isinstance(module, torch.nn.Linear): new_module = torch.nn.Linear( module.in_features, module.out_features, bias=module.bias is not None, ).to(module.weight.device) new_module.weight = module.weight if module.bias is not None: new_module.bias = module.bias
module_replaced = True elif isinstance(module, LoraLayer) and isinstance(module, torch.nn.Conv2d): new_module = torch.nn.Conv2d( module.in_channels, module.out_channels, module.kernel_size, module.stride, module.padding, module.dilation, module.groups, ).to(module.weight.device)
new_module.weight = module.weight if module.bias is not None: new_module.bias = module.bias
module_replaced = True
if module_replaced: setattr(model, name, new_module) del module
empty_device_cache() return model
def scale_lora_layers(model, weight): """ Adjust the weightage given to the LoRA layers of the model.
Args: model (`torch.nn.Module`): The model to scale. weight (`float`): The weight to be given to the LoRA layers. """ from peft.tuners.tuners_utils import BaseTunerLayer
if weight == 1.0: return
for module in model.modules(): if isinstance(module, BaseTunerLayer): module.scale_layer(weight)
def unscale_lora_layers(model, weight: Optional[float] = None): """ Removes the previously passed weight given to the LoRA layers of the model.
Args: model (`torch.nn.Module`): The model to scale. weight (`float`, *optional*): The weight to be given to the LoRA layers. If no scale is passed the scale of the lora layer will be re-initialized to the correct value. If 0.0 is passed, we will re-initialize the scale with the correct value. """ from peft.tuners.tuners_utils import BaseTunerLayer
if weight is None or weight == 1.0: return
for module in model.modules(): if isinstance(module, BaseTunerLayer): if weight != 0: module.unscale_layer(weight) else: for adapter_name in module.active_adapters: # if weight == 0 unscale should re-set the scale to the original value. module.set_scale(adapter_name, 1.0)
def get_peft_kwargs( rank_dict, network_alpha_dict, peft_state_dict, is_unet=True, model_state_dict=None, adapter_name=None): rank_pattern = {} alpha_pattern = {} r = lora_alpha = list(rank_dict.values())[0]
if len(set(rank_dict.values())) > 1: # get the rank occurring the most number of times r = collections.Counter(rank_dict.values()).most_common()[0][0]
# for modules with rank different from the most occurring rank, add it to the `rank_pattern` rank_pattern = dict(filter(lambda x: x[1] != r, rank_dict.items())) rank_pattern = {k.split(".lora_B.")[0]: v for k, v in rank_pattern.items()}
if network_alpha_dict is not None and len(network_alpha_dict) > 0: if len(set(network_alpha_dict.values())) > 1: # get the alpha occurring the most number of times lora_alpha = collections.Counter(network_alpha_dict.values()).most_common()[0][0]
# for modules with alpha different from the most occurring alpha, add it to the `alpha_pattern` alpha_pattern = dict(filter(lambda x: x[1] != lora_alpha, network_alpha_dict.items())) if is_unet: alpha_pattern = { ".".join(k.split(".lora_A.")[0].split(".")).replace(".alpha", ""): v for k, v in alpha_pattern.items() } else: alpha_pattern = {".".join(k.split(".down.")[0].split(".")[:-1]): v for k, v in alpha_pattern.items()} else: lora_alpha = set(network_alpha_dict.values()).pop()
target_modules = list({name.split(".lora")[0] for name in peft_state_dict.keys()}) use_dora = any("lora_magnitude_vector" in k for k in peft_state_dict) # for now we know that the "bias" keys are only associated with `lora_B`. lora_bias = any("lora_B" in k and k.endswith(".bias") for k in peft_state_dict)
lora_config_kwargs = { "r": r, "lora_alpha": lora_alpha, "rank_pattern": rank_pattern, "alpha_pattern": alpha_pattern, "target_modules": target_modules, "use_dora": use_dora, "lora_bias": lora_bias, }
return lora_config_kwargs
def get_adapter_name(model): from peft.tuners.tuners_utils import BaseTunerLayer
for module in model.modules(): if isinstance(module, BaseTunerLayer): return f"default_{len(module.r)}" return "default_0"
def set_adapter_layers(model, enabled=True): from peft.tuners.tuners_utils import BaseTunerLayer
for module in model.modules(): if isinstance(module, BaseTunerLayer): # The recent version of PEFT needs to call `enable_adapters` instead if hasattr(module, "enable_adapters"): module.enable_adapters(enabled=enabled) else: module.disable_adapters = not enabled
def delete_adapter_layers(model, adapter_name): from peft.tuners.tuners_utils import BaseTunerLayer
for module in model.modules(): if isinstance(module, BaseTunerLayer): if hasattr(module, "delete_adapter"): module.delete_adapter(adapter_name) else: raise ValueError( "The version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1" )
# For transformers integration - we need to pop the adapter from the config if getattr(model, "_hf_peft_config_loaded", False) and hasattr(model, "peft_config"): model.peft_config.pop(adapter_name, None) # In case all adapters are deleted, we need to delete the config # and make sure to set the flag to False if len(model.peft_config) == 0: del model.peft_config model._hf_peft_config_loaded = None
def set_weights_and_activate_adapters(model, adapter_names, weights): from peft.tuners.tuners_utils import BaseTunerLayer
def get_module_weight(weight_for_adapter, module_name): if not isinstance(weight_for_adapter, dict): # If weight_for_adapter is a single number, always return it. return weight_for_adapter
for layer_name, weight_ in weight_for_adapter.items(): if layer_name in module_name: return weight_
parts = module_name.split(".") # e.g. key = "down_blocks.1.attentions.0" key = f"{parts[0]}.{parts[1]}.attentions.{parts[3]}" block_weight = weight_for_adapter.get(key, 1.0)
return block_weight
for module_name, module in model.named_modules(): if isinstance(module, BaseTunerLayer): # For backward compatibility with previous PEFT versions, set multiple active adapters if hasattr(module, "set_adapter"): module.set_adapter(adapter_names) else: module.active_adapter = adapter_names
# Set the scaling weight for each adapter for this module for adapter_name, weight in zip(adapter_names, weights): module.set_scale(adapter_name, get_module_weight(weight, module_name))
def check_peft_version(min_version: str) -> None: r""" Checks if the version of PEFT is compatible.
Args: version (`str`): The version of PEFT to check against. """ if not is_peft_available(): raise ValueError("PEFT is not installed. Please install it with `pip install peft`")
is_peft_version_compatible = version.parse(importlib.metadata.version("peft")) > version.parse(min_version)
if not is_peft_version_compatible: raise ValueError( f"The version of PEFT you are using is not compatible, please use a version that is greater" f" than {min_version}" )
def _create_lora_config( state_dict, network_alphas, metadata, rank_pattern_dict, is_unet=True, model_state_dict=None, adapter_name=None): from peft import LoraConfig
if metadata is not None: lora_config_kwargs = metadata else: lora_config_kwargs = get_peft_kwargs( rank_pattern_dict, network_alpha_dict=network_alphas, peft_state_dict=state_dict, is_unet=is_unet, model_state_dict=model_state_dict, adapter_name=adapter_name, )
_maybe_raise_error_for_ambiguous_keys(lora_config_kwargs)
# Version checks for DoRA and lora_bias if "use_dora" in lora_config_kwargs and lora_config_kwargs["use_dora"]: if is_peft_version("<", "0.9.0"): raise ValueError("DoRA requires PEFT >= 0.9.0. Please upgrade.")
if "lora_bias" in lora_config_kwargs and lora_config_kwargs["lora_bias"]: if is_peft_version("<=", "0.13.2"): raise ValueError("lora_bias requires PEFT >= 0.14.0. Please upgrade.")
try: return LoraConfig(**lora_config_kwargs) except TypeError as e: raise TypeError("`LoraConfig` class could not be instantiated.") from e
def _maybe_raise_error_for_ambiguous_keys(config): rank_pattern = config["rank_pattern"].copy() target_modules = config["target_modules"]
for key in list(rank_pattern.keys()): # try to detect ambiguity # `target_modules` can also be a str, in which case this loop would loop # over the chars of the str. The technically correct way to match LoRA keys # in PEFT is to use LoraModel._check_target_module_exists (lora_config, key). # But this cuts it for now. exact_matches = [mod for mod in target_modules if mod == key] substring_matches = [mod for mod in target_modules if key in mod and mod != key]
if exact_matches and substring_matches: if is_peft_version("<", "0.14.1"): raise ValueError( "There are ambiguous keys present in this LoRA. To load it, please update your `peft` installation - `pip install -U peft`." )
def _maybe_warn_for_unhandled_keys(incompatible_keys, adapter_name): warn_msg = "" if incompatible_keys is not None: # Check only for unexpected keys. unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None) if unexpected_keys: lora_unexpected_keys = [k for k in unexpected_keys if "lora_" in k and adapter_name in k] if lora_unexpected_keys: warn_msg = ( f"Loading adapter weights from state_dict led to unexpected keys found in the model:" f" {', '.join(lora_unexpected_keys)}. " )
# Filter missing keys specific to the current adapter. missing_keys = getattr(incompatible_keys, "missing_keys", None) if missing_keys: lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k] if lora_missing_keys: warn_msg += ( f"Loading adapter weights from state_dict led to missing keys in the model:" f" {', '.join(lora_missing_keys)}." )
if warn_msg: logger.warning(warn_msg)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from typing import List
import PIL.Imageimport PIL.ImageOpsfrom packaging import versionfrom PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"): PIL_INTERPOLATION = { "linear": PIL.Image.Resampling.BILINEAR, "bilinear": PIL.Image.Resampling.BILINEAR, "bicubic": PIL.Image.Resampling.BICUBIC, "lanczos": PIL.Image.Resampling.LANCZOS, "nearest": PIL.Image.Resampling.NEAREST, }else: PIL_INTERPOLATION = { "linear": PIL.Image.LINEAR, "bilinear": PIL.Image.BILINEAR, "bicubic": PIL.Image.BICUBIC, "lanczos": PIL.Image.LANCZOS, "nearest": PIL.Image.NEAREST, }
def pt_to_pil(images): """ Convert a torch image to a PIL image. """ images = (images / 2 + 0.5).clamp(0, 1) images = images.cpu().permute(0, 2, 3, 1).float().numpy() images = numpy_to_pil(images) return images
def numpy_to_pil(images): """ Convert a numpy image or a batch of images to a PIL image. """ if images.ndim == 3: images = images[None, ...] images = (images * 255).round().astype("uint8") if images.shape[-1] == 1: # special case for grayscale (single channel) images pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images] else: pil_images = [Image.fromarray(image) for image in images]
return pil_images
def make_image_grid(images: List[PIL.Image.Image], rows: int, cols: int, resize: int = None) -> PIL.Image.Image: """ Prepares a single grid of images. Useful for visualization purposes. """ assert len(images) == rows * cols
if resize is not None: images = [img.resize((resize, resize)) for img in images]
w, h = images[0].size grid = Image.new("RGB", size=(cols * w, rows * h))
for i, img in enumerate(images): grid.paste(img, box=(i % cols * w, i // cols * h)) return grid123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import ioimport jsonfrom typing import List, Literal, Optional, Union, cast
import requests
from .deprecation_utils import deprecatefrom .import_utils import is_safetensors_available, is_torch_available
if is_torch_available(): import torch
from ..image_processor import VaeImageProcessor from ..video_processor import VideoProcessor
if is_safetensors_available(): import safetensors.torch
DTYPE_MAP = { "float16": torch.float16, "float32": torch.float32, "bfloat16": torch.bfloat16, "uint8": torch.uint8, }
from PIL import Image
def detect_image_type(data: bytes) -> str: if data.startswith(b"\xff\xd8"): return "jpeg" elif data.startswith(b"\x89PNG\r\n\x1a\n"): return "png" elif data.startswith(b"GIF87a") or data.startswith(b"GIF89a"): return "gif" elif data.startswith(b"BM"): return "bmp" return "unknown"
def check_inputs_decode( endpoint: str, tensor: "torch.Tensor", processor: Optional[Union["VaeImageProcessor", "VideoProcessor"]] = None, do_scaling: bool = True, scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None, output_type: Literal["mp4", "pil", "pt"] = "pil", return_type: Literal["mp4", "pil", "pt"] = "pil", image_format: Literal["png", "jpg"] = "jpg", partial_postprocess: bool = False, input_tensor_type: Literal["binary"] = "binary", output_tensor_type: Literal["binary"] = "binary", height: Optional[int] = None, width: Optional[int] = None,): if tensor.ndim == 3 and height is None and width is None: raise ValueError("`height` and `width` required for packed latents.") if ( output_type == "pt" and return_type == "pil" and not partial_postprocess and not isinstance(processor, (VaeImageProcessor, VideoProcessor)) ): raise ValueError("`processor` is required.") if do_scaling and scaling_factor is None: deprecate( "do_scaling", "1.0.0", "`do_scaling` is deprecated, pass `scaling_factor` and `shift_factor` if required.", standard_warn=False, )
def postprocess_decode( response: requests.Response, processor: Optional[Union["VaeImageProcessor", "VideoProcessor"]] = None, output_type: Literal["mp4", "pil", "pt"] = "pil", return_type: Literal["mp4", "pil", "pt"] = "pil", partial_postprocess: bool = False,): if output_type == "pt" or (output_type == "pil" and processor is not None): output_tensor = response.content parameters = response.headers shape = json.loads(parameters["shape"]) dtype = parameters["dtype"] torch_dtype = DTYPE_MAP[dtype] output_tensor = torch.frombuffer(bytearray(output_tensor), dtype=torch_dtype).reshape(shape) if output_type == "pt": if partial_postprocess: if return_type == "pil": output = [Image.fromarray(image.numpy()) for image in output_tensor] if len(output) == 1: output = output[0] elif return_type == "pt": output = output_tensor else: if processor is None or return_type == "pt": output = output_tensor else: if isinstance(processor, VideoProcessor): output = cast( List[Image.Image], processor.postprocess_video(output_tensor, output_type="pil")[0], ) else: output = cast( Image.Image, processor.postprocess(output_tensor, output_type="pil")[0], ) elif output_type == "pil" and return_type == "pil" and processor is None: output = Image.open(io.BytesIO(response.content)).convert("RGB") detected_format = detect_image_type(response.content) output.format = detected_format elif output_type == "pil" and processor is not None: if return_type == "pil": output = [ Image.fromarray(image) for image in (output_tensor.permute(0, 2, 3, 1).float().numpy() * 255).round().astype("uint8") ] elif return_type == "pt": output = output_tensor elif output_type == "mp4" and return_type == "mp4": output = response.content return output
def prepare_decode( tensor: "torch.Tensor", processor: Optional[Union["VaeImageProcessor", "VideoProcessor"]] = None, do_scaling: bool = True, scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None, output_type: Literal["mp4", "pil", "pt"] = "pil", image_format: Literal["png", "jpg"] = "jpg", partial_postprocess: bool = False, height: Optional[int] = None, width: Optional[int] = None,): headers = {} parameters = { "image_format": image_format, "output_type": output_type, "partial_postprocess": partial_postprocess, "shape": list(tensor.shape), "dtype": str(tensor.dtype).split(".")[-1], } if do_scaling and scaling_factor is not None: parameters["scaling_factor"] = scaling_factor if do_scaling and shift_factor is not None: parameters["shift_factor"] = shift_factor if do_scaling and scaling_factor is None: parameters["do_scaling"] = do_scaling elif do_scaling and scaling_factor is None and shift_factor is None: parameters["do_scaling"] = do_scaling if height is not None and width is not None: parameters["height"] = height parameters["width"] = width headers["Content-Type"] = "tensor/binary" headers["Accept"] = "tensor/binary" if output_type == "pil" and image_format == "jpg" and processor is None: headers["Accept"] = "image/jpeg" elif output_type == "pil" and image_format == "png" and processor is None: headers["Accept"] = "image/png" elif output_type == "mp4": headers["Accept"] = "text/plain" tensor_data = safetensors.torch._tobytes(tensor, "tensor") return {"data": tensor_data, "params": parameters, "headers": headers}
def remote_decode( endpoint: str, tensor: "torch.Tensor", processor: Optional[Union["VaeImageProcessor", "VideoProcessor"]] = None, do_scaling: bool = True, scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None, output_type: Literal["mp4", "pil", "pt"] = "pil", return_type: Literal["mp4", "pil", "pt"] = "pil", image_format: Literal["png", "jpg"] = "jpg", partial_postprocess: bool = False, input_tensor_type: Literal["binary"] = "binary", output_tensor_type: Literal["binary"] = "binary", height: Optional[int] = None, width: Optional[int] = None,) -> Union[Image.Image, List[Image.Image], bytes, "torch.Tensor"]: """ Hugging Face Hybrid Inference that allow running VAE decode remotely.
Args: endpoint (`str`): Endpoint for Remote Decode. tensor (`torch.Tensor`): Tensor to be decoded. processor (`VaeImageProcessor` or `VideoProcessor`, *optional*): Used with `return_type="pt"`, and `return_type="pil"` for Video models. do_scaling (`bool`, default `True`, *optional*): **DEPRECATED**. **pass `scaling_factor`/`shift_factor` instead.** **still set do_scaling=None/do_scaling=False for no scaling until option is removed** When `True` scaling e.g. `latents / self.vae.config.scaling_factor` is applied remotely. If `False`, input must be passed with scaling applied. scaling_factor (`float`, *optional*): Scaling is applied when passed e.g. [`latents / self.vae.config.scaling_factor`](https://github.com/huggingface/diffusers/blob/7007febae5cff000d4df9059d9cf35133e8b2ca9/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py#L1083C37-L1083C77). - SD v1: 0.18215 - SD XL: 0.13025 - Flux: 0.3611 If `None`, input must be passed with scaling applied. shift_factor (`float`, *optional*): Shift is applied when passed e.g. `latents + self.vae.config.shift_factor`. - Flux: 0.1159 If `None`, input must be passed with scaling applied. output_type (`"mp4"` or `"pil"` or `"pt", default `"pil"): **Endpoint** output type. Subject to change. Report feedback on preferred type.
`"mp4": Supported by video models. Endpoint returns `bytes` of video. `"pil"`: Supported by image and video models. Image models: Endpoint returns `bytes` of an image in `image_format`. Video models: Endpoint returns `torch.Tensor` with partial `postprocessing` applied. Requires `processor` as a flag (any `None` value will work). `"pt"`: Support by image and video models. Endpoint returns `torch.Tensor`. With `partial_postprocess=True` the tensor is postprocessed `uint8` image tensor.
Recommendations: `"pt"` with `partial_postprocess=True` is the smallest transfer for full quality. `"pt"` with `partial_postprocess=False` is the most compatible with third party code. `"pil"` with `image_format="jpg"` is the smallest transfer overall.
return_type (`"mp4"` or `"pil"` or `"pt", default `"pil"): **Function** return type.
`"mp4": Function returns `bytes` of video. `"pil"`: Function returns `PIL.Image.Image`. With `output_type="pil" no further processing is applied. With `output_type="pt" a `PIL.Image.Image` is created. `partial_postprocess=False` `processor` is required. `partial_postprocess=True` `processor` is **not** required. `"pt"`: Function returns `torch.Tensor`. `processor` is **not** required. `partial_postprocess=False` tensor is `float16` or `bfloat16`, without denormalization. `partial_postprocess=True` tensor is `uint8`, denormalized.
image_format (`"png"` or `"jpg"`, default `jpg`): Used with `output_type="pil"`. Endpoint returns `jpg` or `png`.
partial_postprocess (`bool`, default `False`): Used with `output_type="pt"`. `partial_postprocess=False` tensor is `float16` or `bfloat16`, without denormalization. `partial_postprocess=True` tensor is `uint8`, denormalized.
input_tensor_type (`"binary"`, default `"binary"`): Tensor transfer type.
output_tensor_type (`"binary"`, default `"binary"`): Tensor transfer type.
height (`int`, **optional**): Required for `"packed"` latents.
width (`int`, **optional**): Required for `"packed"` latents.
Returns: output (`Image.Image` or `List[Image.Image]` or `bytes` or `torch.Tensor`). """ if input_tensor_type == "base64": deprecate( "input_tensor_type='base64'", "1.0.0", "input_tensor_type='base64' is deprecated. Using `binary`.", standard_warn=False, ) input_tensor_type = "binary" if output_tensor_type == "base64": deprecate( "output_tensor_type='base64'", "1.0.0", "output_tensor_type='base64' is deprecated. Using `binary`.", standard_warn=False, ) output_tensor_type = "binary" check_inputs_decode( endpoint, tensor, processor, do_scaling, scaling_factor, shift_factor, output_type, return_type, image_format, partial_postprocess, input_tensor_type, output_tensor_type, height, width, ) kwargs = prepare_decode( tensor=tensor, processor=processor, do_scaling=do_scaling, scaling_factor=scaling_factor, shift_factor=shift_factor, output_type=output_type, image_format=image_format, partial_postprocess=partial_postprocess, height=height, width=width, ) response = requests.post(endpoint, **kwargs) if not response.ok: raise RuntimeError(response.json()) output = postprocess_decode( response=response, processor=processor, output_type=output_type, return_type=return_type, partial_postprocess=partial_postprocess, ) return output
def check_inputs_encode( endpoint: str, image: Union["torch.Tensor", Image.Image], scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None,): pass
def postprocess_encode( response: requests.Response,): output_tensor = response.content parameters = response.headers shape = json.loads(parameters["shape"]) dtype = parameters["dtype"] torch_dtype = DTYPE_MAP[dtype] output_tensor = torch.frombuffer(bytearray(output_tensor), dtype=torch_dtype).reshape(shape) return output_tensor
def prepare_encode( image: Union["torch.Tensor", Image.Image], scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None,): headers = {} parameters = {} if scaling_factor is not None: parameters["scaling_factor"] = scaling_factor if shift_factor is not None: parameters["shift_factor"] = shift_factor if isinstance(image, torch.Tensor): data = safetensors.torch._tobytes(image.contiguous(), "tensor") parameters["shape"] = list(image.shape) parameters["dtype"] = str(image.dtype).split(".")[-1] else: buffer = io.BytesIO() image.save(buffer, format="PNG") data = buffer.getvalue() return {"data": data, "params": parameters, "headers": headers}
def remote_encode( endpoint: str, image: Union["torch.Tensor", Image.Image], scaling_factor: Optional[float] = None, shift_factor: Optional[float] = None,) -> "torch.Tensor": """ Hugging Face Hybrid Inference that allow running VAE encode remotely.
Args: endpoint (`str`): Endpoint for Remote Decode. image (`torch.Tensor` or `PIL.Image.Image`): Image to be encoded. scaling_factor (`float`, *optional*): Scaling is applied when passed e.g. [`latents * self.vae.config.scaling_factor`]. - SD v1: 0.18215 - SD XL: 0.13025 - Flux: 0.3611 If `None`, input must be passed with scaling applied. shift_factor (`float`, *optional*): Shift is applied when passed e.g. `latents - self.vae.config.shift_factor`. - Flux: 0.1159 If `None`, input must be passed with scaling applied.
Returns: output (`torch.Tensor`). """ check_inputs_encode( endpoint, image, scaling_factor, shift_factor, ) kwargs = prepare_encode( image=image, scaling_factor=scaling_factor, shift_factor=shift_factor, ) response = requests.post(endpoint, **kwargs) if not response.ok: raise RuntimeError(response.json()) output = postprocess_encode( response=response, ) return output12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import astimport importlibimport inspectimport textwrap
class ReturnNameVisitor(ast.NodeVisitor): """Thanks to ChatGPT for pairing."""
def __init__(self): self.return_names = []
def visit_Return(self, node): # Check if the return value is a tuple. if isinstance(node.value, ast.Tuple): for elt in node.value.elts: if isinstance(elt, ast.Name): self.return_names.append(elt.id) else: try: self.return_names.append(ast.unparse(elt)) except Exception: self.return_names.append(str(elt)) else: if isinstance(node.value, ast.Name): self.return_names.append(node.value.id) else: try: self.return_names.append(ast.unparse(node.value)) except Exception: self.return_names.append(str(node.value)) self.generic_visit(node)
def _determine_parent_module(self, cls): from diffusers import DiffusionPipeline from diffusers.models.modeling_utils import ModelMixin
if issubclass(cls, DiffusionPipeline): return "pipelines" elif issubclass(cls, ModelMixin): return "models" else: raise NotImplementedError
def get_ast_tree(self, cls, attribute_name="encode_prompt"): parent_module_name = self._determine_parent_module(cls) main_module = importlib.import_module(f"diffusers.{parent_module_name}") current_cls_module = getattr(main_module, cls.__name__) source_code = inspect.getsource(getattr(current_cls_module, attribute_name)) source_code = textwrap.dedent(source_code) tree = ast.parse(source_code) return tree123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""State dict utilities: utility methods for converting state dicts easily"""
import enumimport json
from .import_utils import is_torch_availablefrom .logging import get_logger
if is_torch_available(): import torch
logger = get_logger(__name__)
class StateDictType(enum.Enum): """ The mode to use when converting state dicts. """
DIFFUSERS_OLD = "diffusers_old" KOHYA_SS = "kohya_ss" PEFT = "peft" DIFFUSERS = "diffusers"
# We need to define a proper mapping for Unet since it uses different output keys than text encoder# e.g. to_q_lora -> q_proj / to_qUNET_TO_DIFFUSERS = { ".to_out_lora.up": ".to_out.0.lora_B", ".to_out_lora.down": ".to_out.0.lora_A", ".to_q_lora.down": ".to_q.lora_A", ".to_q_lora.up": ".to_q.lora_B", ".to_k_lora.down": ".to_k.lora_A", ".to_k_lora.up": ".to_k.lora_B", ".to_v_lora.down": ".to_v.lora_A", ".to_v_lora.up": ".to_v.lora_B", ".lora.up": ".lora_B", ".lora.down": ".lora_A", ".to_out.lora_magnitude_vector": ".to_out.0.lora_magnitude_vector",}
DIFFUSERS_TO_PEFT = { ".q_proj.lora_linear_layer.up": ".q_proj.lora_B", ".q_proj.lora_linear_layer.down": ".q_proj.lora_A", ".k_proj.lora_linear_layer.up": ".k_proj.lora_B", ".k_proj.lora_linear_layer.down": ".k_proj.lora_A", ".v_proj.lora_linear_layer.up": ".v_proj.lora_B", ".v_proj.lora_linear_layer.down": ".v_proj.lora_A", ".out_proj.lora_linear_layer.up": ".out_proj.lora_B", ".out_proj.lora_linear_layer.down": ".out_proj.lora_A", ".lora_linear_layer.up": ".lora_B", ".lora_linear_layer.down": ".lora_A", "text_projection.lora.down.weight": "text_projection.lora_A.weight", "text_projection.lora.up.weight": "text_projection.lora_B.weight",}
DIFFUSERS_OLD_TO_PEFT = { ".to_q_lora.up": ".q_proj.lora_B", ".to_q_lora.down": ".q_proj.lora_A", ".to_k_lora.up": ".k_proj.lora_B", ".to_k_lora.down": ".k_proj.lora_A", ".to_v_lora.up": ".v_proj.lora_B", ".to_v_lora.down": ".v_proj.lora_A", ".to_out_lora.up": ".out_proj.lora_B", ".to_out_lora.down": ".out_proj.lora_A", ".lora_linear_layer.up": ".lora_B", ".lora_linear_layer.down": ".lora_A",}
PEFT_TO_DIFFUSERS = { ".q_proj.lora_B": ".q_proj.lora_linear_layer.up", ".q_proj.lora_A": ".q_proj.lora_linear_layer.down", ".k_proj.lora_B": ".k_proj.lora_linear_layer.up", ".k_proj.lora_A": ".k_proj.lora_linear_layer.down", ".v_proj.lora_B": ".v_proj.lora_linear_layer.up", ".v_proj.lora_A": ".v_proj.lora_linear_layer.down", ".out_proj.lora_B": ".out_proj.lora_linear_layer.up", ".out_proj.lora_A": ".out_proj.lora_linear_layer.down", "to_k.lora_A": "to_k.lora.down", "to_k.lora_B": "to_k.lora.up", "to_q.lora_A": "to_q.lora.down", "to_q.lora_B": "to_q.lora.up", "to_v.lora_A": "to_v.lora.down", "to_v.lora_B": "to_v.lora.up", "to_out.0.lora_A": "to_out.0.lora.down", "to_out.0.lora_B": "to_out.0.lora.up",}
DIFFUSERS_OLD_TO_DIFFUSERS = { ".to_q_lora.up": ".q_proj.lora_linear_layer.up", ".to_q_lora.down": ".q_proj.lora_linear_layer.down", ".to_k_lora.up": ".k_proj.lora_linear_layer.up", ".to_k_lora.down": ".k_proj.lora_linear_layer.down", ".to_v_lora.up": ".v_proj.lora_linear_layer.up", ".to_v_lora.down": ".v_proj.lora_linear_layer.down", ".to_out_lora.up": ".out_proj.lora_linear_layer.up", ".to_out_lora.down": ".out_proj.lora_linear_layer.down", ".to_k.lora_magnitude_vector": ".k_proj.lora_magnitude_vector", ".to_v.lora_magnitude_vector": ".v_proj.lora_magnitude_vector", ".to_q.lora_magnitude_vector": ".q_proj.lora_magnitude_vector", ".to_out.lora_magnitude_vector": ".out_proj.lora_magnitude_vector",}
PEFT_TO_KOHYA_SS = { "lora_A": "lora_down", "lora_B": "lora_up", # This is not a comprehensive dict as kohya format requires replacing `.` with `_` in keys, # adding prefixes and adding alpha values # Check `convert_state_dict_to_kohya` for more}
PEFT_STATE_DICT_MAPPINGS = { StateDictType.DIFFUSERS_OLD: DIFFUSERS_OLD_TO_PEFT, StateDictType.DIFFUSERS: DIFFUSERS_TO_PEFT,}
DIFFUSERS_STATE_DICT_MAPPINGS = { StateDictType.DIFFUSERS_OLD: DIFFUSERS_OLD_TO_DIFFUSERS, StateDictType.PEFT: PEFT_TO_DIFFUSERS,}
KOHYA_STATE_DICT_MAPPINGS = {StateDictType.PEFT: PEFT_TO_KOHYA_SS}
KEYS_TO_ALWAYS_REPLACE = { ".processor.": ".",}
def convert_state_dict(state_dict, mapping): r""" Simply iterates over the state dict and replaces the patterns in `mapping` with the corresponding values.
Args: state_dict (`dict[str, torch.Tensor]`): The state dict to convert. mapping (`dict[str, str]`): The mapping to use for conversion, the mapping should be a dictionary with the following structure: - key: the pattern to replace - value: the pattern to replace with
Returns: converted_state_dict (`dict`) The converted state dict. """ converted_state_dict = {} for k, v in state_dict.items(): # First, filter out the keys that we always want to replace for pattern in KEYS_TO_ALWAYS_REPLACE.keys(): if pattern in k: new_pattern = KEYS_TO_ALWAYS_REPLACE[pattern] k = k.replace(pattern, new_pattern)
for pattern in mapping.keys(): if pattern in k: new_pattern = mapping[pattern] k = k.replace(pattern, new_pattern) break converted_state_dict[k] = v return converted_state_dict
def convert_state_dict_to_peft(state_dict, original_type=None, **kwargs): r""" Converts a state dict to the PEFT format The state dict can be from previous diffusers format (`OLD_DIFFUSERS`), or new diffusers format (`DIFFUSERS`). The method only supports the conversion from diffusers old/new to PEFT for now.
Args: state_dict (`dict[str, torch.Tensor]`): The state dict to convert. original_type (`StateDictType`, *optional*): The original type of the state dict, if not provided, the method will try to infer it automatically. """ if original_type is None: # Old diffusers to PEFT if any("to_out_lora" in k for k in state_dict.keys()): original_type = StateDictType.DIFFUSERS_OLD elif any("lora_linear_layer" in k for k in state_dict.keys()): original_type = StateDictType.DIFFUSERS else: raise ValueError("Could not automatically infer state dict type")
if original_type not in PEFT_STATE_DICT_MAPPINGS.keys(): raise ValueError(f"Original type {original_type} is not supported")
mapping = PEFT_STATE_DICT_MAPPINGS[original_type] return convert_state_dict(state_dict, mapping)
def convert_state_dict_to_diffusers(state_dict, original_type=None, **kwargs): r""" Converts a state dict to new diffusers format. The state dict can be from previous diffusers format (`OLD_DIFFUSERS`), or PEFT format (`PEFT`) or new diffusers format (`DIFFUSERS`). In the last case the method will return the state dict as is.
The method only supports the conversion from diffusers old, PEFT to diffusers new for now.
Args: state_dict (`dict[str, torch.Tensor]`): The state dict to convert. original_type (`StateDictType`, *optional*): The original type of the state dict, if not provided, the method will try to infer it automatically. kwargs (`dict`, *args*): Additional arguments to pass to the method.
- **adapter_name**: For example, in case of PEFT, some keys will be prepended with the adapter name, therefore needs a special handling. By default PEFT also takes care of that in `get_peft_model_state_dict` method: https://github.com/huggingface/peft/blob/ba0477f2985b1ba311b83459d29895c809404e99/src/peft/utils/save_and_load.py#L92 but we add it here in case we don't want to rely on that method. """ peft_adapter_name = kwargs.pop("adapter_name", None) if peft_adapter_name is not None: peft_adapter_name = "." + peft_adapter_name else: peft_adapter_name = ""
if original_type is None: # Old diffusers to PEFT if any("to_out_lora" in k for k in state_dict.keys()): original_type = StateDictType.DIFFUSERS_OLD elif any(f".lora_A{peft_adapter_name}.weight" in k for k in state_dict.keys()): original_type = StateDictType.PEFT elif any("lora_linear_layer" in k for k in state_dict.keys()): # nothing to do return state_dict else: raise ValueError("Could not automatically infer state dict type")
if original_type not in DIFFUSERS_STATE_DICT_MAPPINGS.keys(): raise ValueError(f"Original type {original_type} is not supported")
mapping = DIFFUSERS_STATE_DICT_MAPPINGS[original_type] return convert_state_dict(state_dict, mapping)
def convert_unet_state_dict_to_peft(state_dict): r""" Converts a state dict from UNet format to diffusers format - i.e. by removing some keys """ mapping = UNET_TO_DIFFUSERS return convert_state_dict(state_dict, mapping)
def convert_all_state_dict_to_peft(state_dict): r""" Attempts to first `convert_state_dict_to_peft`, and if it doesn't detect `lora_linear_layer` for a valid `DIFFUSERS` LoRA for example, attempts to exclusively convert the Unet `convert_unet_state_dict_to_peft` """ try: peft_dict = convert_state_dict_to_peft(state_dict) except Exception as e: if str(e) == "Could not automatically infer state dict type": peft_dict = convert_unet_state_dict_to_peft(state_dict) else: raise
if not any("lora_A" in key or "lora_B" in key for key in peft_dict.keys()): raise ValueError("Your LoRA was not converted to PEFT")
return peft_dict
def convert_state_dict_to_kohya(state_dict, original_type=None, **kwargs): r""" Converts a `PEFT` state dict to `Kohya` format that can be used in AUTOMATIC1111, ComfyUI, SD.Next, InvokeAI, etc. The method only supports the conversion from PEFT to Kohya for now.
Args: state_dict (`dict[str, torch.Tensor]`): The state dict to convert. original_type (`StateDictType`, *optional*): The original type of the state dict, if not provided, the method will try to infer it automatically. kwargs (`dict`, *args*): Additional arguments to pass to the method.
- **adapter_name**: For example, in case of PEFT, some keys will be prepended with the adapter name, therefore needs a special handling. By default PEFT also takes care of that in `get_peft_model_state_dict` method: https://github.com/huggingface/peft/blob/ba0477f2985b1ba311b83459d29895c809404e99/src/peft/utils/save_and_load.py#L92 but we add it here in case we don't want to rely on that method. """ try: import torch except ImportError: logger.error("Converting PEFT state dicts to Kohya requires torch to be installed.") raise
peft_adapter_name = kwargs.pop("adapter_name", None) if peft_adapter_name is not None: peft_adapter_name = "." + peft_adapter_name else: peft_adapter_name = ""
if original_type is None: if any(f".lora_A{peft_adapter_name}.weight" in k for k in state_dict.keys()): original_type = StateDictType.PEFT
if original_type not in KOHYA_STATE_DICT_MAPPINGS.keys(): raise ValueError(f"Original type {original_type} is not supported")
# Use the convert_state_dict function with the appropriate mapping kohya_ss_partial_state_dict = convert_state_dict(state_dict, KOHYA_STATE_DICT_MAPPINGS[StateDictType.PEFT]) kohya_ss_state_dict = {}
# Additional logic for replacing header, alpha parameters `.` with `_` in all keys for kohya_key, weight in kohya_ss_partial_state_dict.items(): if "text_encoder_2." in kohya_key: kohya_key = kohya_key.replace("text_encoder_2.", "lora_te2.") elif "text_encoder." in kohya_key: kohya_key = kohya_key.replace("text_encoder.", "lora_te1.") elif "unet" in kohya_key: kohya_key = kohya_key.replace("unet", "lora_unet") elif "lora_magnitude_vector" in kohya_key: kohya_key = kohya_key.replace("lora_magnitude_vector", "dora_scale")
kohya_key = kohya_key.replace(".", "_", kohya_key.count(".") - 2) kohya_key = kohya_key.replace(peft_adapter_name, "") # Kohya doesn't take names kohya_ss_state_dict[kohya_key] = weight if "lora_down" in kohya_key: alpha_key = f"{kohya_key.split('.')[0]}.alpha" kohya_ss_state_dict[alpha_key] = torch.tensor(len(weight))
return kohya_ss_state_dict
def state_dict_all_zero(state_dict, filter_str=None): if filter_str is not None: if isinstance(filter_str, str): filter_str = [filter_str] state_dict = {k: v for k, v in state_dict.items() if any(f in k for f in filter_str)}
return all(torch.all(param == 0).item() for param in state_dict.values())
def _load_sft_state_dict_metadata(model_file: str): import safetensors.torch
from ..loaders.lora_base import LORA_ADAPTER_METADATA_KEY
with safetensors.torch.safe_open(model_file, framework="pt", device="cpu") as f: metadata = f.metadata() or {}
metadata.pop("format", None) if metadata: raw = metadata.get(LORA_ADAPTER_METADATA_KEY) return json.loads(raw) if raw else None else: return None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601import functoolsimport globimport importlibimport importlib.metadataimport inspectimport ioimport loggingimport multiprocessingimport osimport randomimport reimport structimport sysimport tempfileimport timeimport unittestimport urllib.parsefrom collections import UserDictfrom contextlib import contextmanagerfrom io import BytesIO, StringIOfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple, Union
import numpy as npimport PIL.Imageimport PIL.ImageOpsimport requestsfrom numpy.linalg import normfrom packaging import version
from .constants import DIFFUSERS_REQUEST_TIMEOUTfrom .import_utils import ( BACKENDS_MAPPING, is_accelerate_available, is_bitsandbytes_available, is_compel_available, is_flax_available, is_gguf_available, is_kernels_available, is_note_seq_available, is_onnx_available, is_opencv_available, is_optimum_quanto_available, is_peft_available, is_timm_available, is_torch_available, is_torch_version, is_torchao_available, is_torchsde_available, is_transformers_available,)from .logging import get_logger
if is_torch_available(): import torch
IS_ROCM_SYSTEM = torch.version.hip is not None IS_CUDA_SYSTEM = torch.version.cuda is not None IS_XPU_SYSTEM = getattr(torch.version, "xpu", None) is not Noneelse: IS_ROCM_SYSTEM = False IS_CUDA_SYSTEM = False IS_XPU_SYSTEM = False
global_rng = random.Random()
logger = get_logger(__name__)logger.warning( "diffusers.utils.testing_utils' is deprecated and will be removed in a future version. " "Determinism and device backend utilities have been moved to `diffusers.utils.torch_utils`. ")_required_peft_version = is_peft_available() and version.parse( version.parse(importlib.metadata.version("peft")).base_version) > version.parse("0.5")_required_transformers_version = is_transformers_available() and version.parse( version.parse(importlib.metadata.version("transformers")).base_version) > version.parse("4.33")
USE_PEFT_BACKEND = _required_peft_version and _required_transformers_versionBIG_GPU_MEMORY = int(os.getenv("BIG_GPU_MEMORY", 40))
if is_torch_available(): import torch
# Set a backend environment variable for any extra module import required for a custom accelerator if "DIFFUSERS_TEST_BACKEND" in os.environ: backend = os.environ["DIFFUSERS_TEST_BACKEND"] try: _ = importlib.import_module(backend) except ModuleNotFoundError as e: raise ModuleNotFoundError( f"Failed to import `DIFFUSERS_TEST_BACKEND` '{backend}'! This should be the name of an installed module \ to enable a specified backend.):\n{e}" ) from e
if "DIFFUSERS_TEST_DEVICE" in os.environ: torch_device = os.environ["DIFFUSERS_TEST_DEVICE"] try: # try creating device to see if provided device is valid _ = torch.device(torch_device) except RuntimeError as e: raise RuntimeError( f"Unknown testing device specified by environment variable `DIFFUSERS_TEST_DEVICE`: {torch_device}" ) from e logger.info(f"torch_device overrode to {torch_device}") else: if torch.cuda.is_available(): torch_device = "cuda" elif torch.xpu.is_available(): torch_device = "xpu" else: torch_device = "cpu" is_torch_higher_equal_than_1_12 = version.parse( version.parse(torch.__version__).base_version ) >= version.parse("1.12")
if is_torch_higher_equal_than_1_12: # Some builds of torch 1.12 don't have the mps backend registered. See #892 for more details mps_backend_registered = hasattr(torch.backends, "mps") torch_device = "mps" if (mps_backend_registered and torch.backends.mps.is_available()) else torch_device
from .torch_utils import get_torch_cuda_device_capability
def torch_all_close(a, b, *args, **kwargs): if not is_torch_available(): raise ValueError("PyTorch needs to be installed to use this function.") if not torch.allclose(a, b, *args, **kwargs): assert False, f"Max diff is absolute {(a - b).abs().max()}. Diff tensor is {(a - b).abs()}." return True
def numpy_cosine_similarity_distance(a, b): similarity = np.dot(a, b) / (norm(a) * norm(b)) distance = 1.0 - similarity.mean()
return distance
def check_if_dicts_are_equal(dict1, dict2): dict1, dict2 = dict1.copy(), dict2.copy()
for key, value in dict1.items(): if isinstance(value, set): dict1[key] = sorted(value) for key, value in dict2.items(): if isinstance(value, set): dict2[key] = sorted(value)
for key in dict1: if key not in dict2: return False if dict1[key] != dict2[key]: return False
for key in dict2: if key not in dict1: return False
return True
def print_tensor_test( tensor, limit_to_slices=None, max_torch_print=None, filename="test_corrections.txt", expected_tensor_name="expected_slice",): if max_torch_print: torch.set_printoptions(threshold=10_000)
test_name = os.environ.get("PYTEST_CURRENT_TEST") if not torch.is_tensor(tensor): tensor = torch.from_numpy(tensor) if limit_to_slices: tensor = tensor[0, -3:, -3:, -1]
tensor_str = str(tensor.detach().cpu().flatten().to(torch.float32)).replace("\n", "") # format is usually: # expected_slice = np.array([-0.5713, -0.3018, -0.9814, 0.04663, -0.879, 0.76, -1.734, 0.1044, 1.161]) output_str = tensor_str.replace("tensor", f"{expected_tensor_name} = np.array") test_file, test_class, test_fn = test_name.split("::") test_fn = test_fn.split()[0] with open(filename, "a") as f: print("::".join([test_file, test_class, test_fn, output_str]), file=f)
def get_tests_dir(append_path=None): """ Args: append_path: optional path to append to the tests dir path Return: The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is joined after the `tests` dir the former is provided. """ # this function caller's __file__ caller__file__ = inspect.stack()[1][1] tests_dir = os.path.abspath(os.path.dirname(caller__file__))
while not tests_dir.endswith("tests"): tests_dir = os.path.dirname(tests_dir)
if append_path: return Path(tests_dir, append_path).as_posix() else: return tests_dir
# Taken from the following PR:# https://github.com/huggingface/accelerate/pull/1964def str_to_bool(value) -> int: """ Converts a string representation of truth to `True` (1) or `False` (0). True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; """ value = value.lower() if value in ("y", "yes", "t", "true", "on", "1"): return 1 elif value in ("n", "no", "f", "false", "off", "0"): return 0 else: raise ValueError(f"invalid truth value {value}")
def parse_flag_from_env(key, default=False): try: value = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _value = default else: # KEY is set, convert it to True or False. try: _value = str_to_bool(value) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no.") return _value
_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False)_run_nightly_tests = parse_flag_from_env("RUN_NIGHTLY", default=False)_run_compile_tests = parse_flag_from_env("RUN_COMPILE", default=False)
def floats_tensor(shape, scale=1.0, rng=None, name=None): """Creates a random float32 tensor""" if rng is None: rng = global_rng
total_dims = 1 for dim in shape: total_dims *= dim
values = [] for _ in range(total_dims): values.append(rng.random() * scale)
return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous()
def slow(test_case): """ Decorator marking a test as slow.
Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.
""" return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case)
def nightly(test_case): """ Decorator marking a test that runs nightly in the diffusers CI.
Slow tests are skipped by default. Set the RUN_NIGHTLY environment variable to a truthy value to run them.
""" return unittest.skipUnless(_run_nightly_tests, "test is nightly")(test_case)
def is_torch_compile(test_case): """ Decorator marking a test that runs compile tests in the diffusers CI.
Compile tests are skipped by default. Set the RUN_COMPILE environment variable to a truthy value to run them.
""" return unittest.skipUnless(_run_compile_tests, "test is torch compile")(test_case)
def require_torch(test_case): """ Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed. """ return unittest.skipUnless(is_torch_available(), "test requires PyTorch")(test_case)
def require_torch_2(test_case): """ Decorator marking a test that requires PyTorch 2. These tests are skipped when it isn't installed. """ return unittest.skipUnless(is_torch_available() and is_torch_version(">=", "2.0.0"), "test requires PyTorch 2")( test_case )
def require_torch_version_greater_equal(torch_version): """Decorator marking a test that requires torch with a specific version or greater."""
def decorator(test_case): correct_torch_version = is_torch_available() and is_torch_version(">=", torch_version) return unittest.skipUnless( correct_torch_version, f"test requires torch with the version greater than or equal to {torch_version}" )(test_case)
return decorator
def require_torch_version_greater(torch_version): """Decorator marking a test that requires torch with a specific version greater."""
def decorator(test_case): correct_torch_version = is_torch_available() and is_torch_version(">", torch_version) return unittest.skipUnless( correct_torch_version, f"test requires torch with the version greater than {torch_version}" )(test_case)
return decorator
def require_torch_gpu(test_case): """Decorator marking a test that requires CUDA and PyTorch.""" return unittest.skipUnless(is_torch_available() and torch_device == "cuda", "test requires PyTorch+CUDA")( test_case )
def require_torch_cuda_compatibility(expected_compute_capability): def decorator(test_case): if torch.cuda.is_available(): current_compute_capability = get_torch_cuda_device_capability() return unittest.skipUnless( float(current_compute_capability) == float(expected_compute_capability), "Test not supported for this compute capability.", )
return decorator
# These decorators are for accelerator-specific behaviours that are not GPU-specificdef require_torch_accelerator(test_case): """Decorator marking a test that requires an accelerator backend and PyTorch.""" return unittest.skipUnless(is_torch_available() and torch_device != "cpu", "test requires accelerator+PyTorch")( test_case )
def require_torch_multi_gpu(test_case): """ Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without multiple GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu" """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case)
import torch
return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple GPUs")(test_case)
def require_torch_multi_accelerator(test_case): """ Decorator marking a test that requires a multi-accelerator setup (in PyTorch). These tests are skipped on a machine without multiple hardware accelerators. """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case)
import torch
return unittest.skipUnless( torch.cuda.device_count() > 1 or torch.xpu.device_count() > 1, "test requires multiple hardware accelerators" )(test_case)
def require_torch_accelerator_with_fp16(test_case): """Decorator marking a test that requires an accelerator with support for the FP16 data type.""" return unittest.skipUnless(_is_torch_fp16_available(torch_device), "test requires accelerator with fp16 support")( test_case )
def require_torch_accelerator_with_fp64(test_case): """Decorator marking a test that requires an accelerator with support for the FP64 data type.""" return unittest.skipUnless(_is_torch_fp64_available(torch_device), "test requires accelerator with fp64 support")( test_case )
def require_big_gpu_with_torch_cuda(test_case): """ Decorator marking a test that requires a bigger GPU (24GB) for execution. Some example pipelines: Flux, SD3, Cog, etc. """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case)
import torch
if not torch.cuda.is_available(): return unittest.skip("test requires PyTorch CUDA")(test_case)
device_properties = torch.cuda.get_device_properties(0) total_memory = device_properties.total_memory / (1024**3) return unittest.skipUnless( total_memory >= BIG_GPU_MEMORY, f"test requires a GPU with at least {BIG_GPU_MEMORY} GB memory" )(test_case)
def require_big_accelerator(test_case): """ Decorator marking a test that requires a bigger hardware accelerator (24GB) for execution. Some example pipelines: Flux, SD3, Cog, etc. """ import pytest
test_case = pytest.mark.big_accelerator(test_case)
if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case)
import torch
if not (torch.cuda.is_available() or torch.xpu.is_available()): return unittest.skip("test requires PyTorch CUDA")(test_case)
if torch.xpu.is_available(): device_properties = torch.xpu.get_device_properties(0) else: device_properties = torch.cuda.get_device_properties(0)
total_memory = device_properties.total_memory / (1024**3) return unittest.skipUnless( total_memory >= BIG_GPU_MEMORY, f"test requires a hardware accelerator with at least {BIG_GPU_MEMORY} GB memory", )(test_case)
def require_torch_accelerator_with_training(test_case): """Decorator marking a test that requires an accelerator with support for training.""" return unittest.skipUnless( is_torch_available() and backend_supports_training(torch_device), "test requires accelerator with training support", )(test_case)
def skip_mps(test_case): """Decorator marking a test to skip if torch_device is 'mps'""" return unittest.skipUnless(torch_device != "mps", "test requires non 'mps' device")(test_case)
def require_flax(test_case): """ Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed """ return unittest.skipUnless(is_flax_available(), "test requires JAX & Flax")(test_case)
def require_compel(test_case): """ Decorator marking a test that requires compel: https://github.com/damian0815/compel. These tests are skipped when the library is not installed. """ return unittest.skipUnless(is_compel_available(), "test requires compel")(test_case)
def require_onnxruntime(test_case): """ Decorator marking a test that requires onnxruntime. These tests are skipped when onnxruntime isn't installed. """ return unittest.skipUnless(is_onnx_available(), "test requires onnxruntime")(test_case)
def require_note_seq(test_case): """ Decorator marking a test that requires note_seq. These tests are skipped when note_seq isn't installed. """ return unittest.skipUnless(is_note_seq_available(), "test requires note_seq")(test_case)
def require_accelerator(test_case): """ Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no hardware accelerator available. """ return unittest.skipUnless(torch_device != "cpu", "test requires a hardware accelerator")(test_case)
def require_torchsde(test_case): """ Decorator marking a test that requires torchsde. These tests are skipped when torchsde isn't installed. """ return unittest.skipUnless(is_torchsde_available(), "test requires torchsde")(test_case)
def require_peft_backend(test_case): """ Decorator marking a test that requires PEFT backend, this would require some specific versions of PEFT and transformers. """ return unittest.skipUnless(USE_PEFT_BACKEND, "test requires PEFT backend")(test_case)
def require_timm(test_case): """ Decorator marking a test that requires timm. These tests are skipped when timm isn't installed. """ return unittest.skipUnless(is_timm_available(), "test requires timm")(test_case)
def require_bitsandbytes(test_case): """ Decorator marking a test that requires bitsandbytes. These tests are skipped when bitsandbytes isn't installed. """ return unittest.skipUnless(is_bitsandbytes_available(), "test requires bitsandbytes")(test_case)
def require_quanto(test_case): """ Decorator marking a test that requires quanto. These tests are skipped when quanto isn't installed. """ return unittest.skipUnless(is_optimum_quanto_available(), "test requires quanto")(test_case)
def require_accelerate(test_case): """ Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed. """ return unittest.skipUnless(is_accelerate_available(), "test requires accelerate")(test_case)
def require_peft_version_greater(peft_version): """ Decorator marking a test that requires PEFT backend with a specific version, this would require some specific versions of PEFT and transformers. """
def decorator(test_case): correct_peft_version = is_peft_available() and version.parse( version.parse(importlib.metadata.version("peft")).base_version ) > version.parse(peft_version) return unittest.skipUnless( correct_peft_version, f"test requires PEFT backend with the version greater than {peft_version}" )(test_case)
return decorator
def require_transformers_version_greater(transformers_version): """ Decorator marking a test that requires transformers with a specific version, this would require some specific versions of PEFT and transformers. """
def decorator(test_case): correct_transformers_version = is_transformers_available() and version.parse( version.parse(importlib.metadata.version("transformers")).base_version ) > version.parse(transformers_version) return unittest.skipUnless( correct_transformers_version, f"test requires transformers with the version greater than {transformers_version}", )(test_case)
return decorator
def require_accelerate_version_greater(accelerate_version): def decorator(test_case): correct_accelerate_version = is_accelerate_available() and version.parse( version.parse(importlib.metadata.version("accelerate")).base_version ) > version.parse(accelerate_version) return unittest.skipUnless( correct_accelerate_version, f"Test requires accelerate with the version greater than {accelerate_version}." )(test_case)
return decorator
def require_bitsandbytes_version_greater(bnb_version): def decorator(test_case): correct_bnb_version = is_bitsandbytes_available() and version.parse( version.parse(importlib.metadata.version("bitsandbytes")).base_version ) > version.parse(bnb_version) return unittest.skipUnless( correct_bnb_version, f"Test requires bitsandbytes with the version greater than {bnb_version}." )(test_case)
return decorator
def require_hf_hub_version_greater(hf_hub_version): def decorator(test_case): correct_hf_hub_version = version.parse( version.parse(importlib.metadata.version("huggingface_hub")).base_version ) > version.parse(hf_hub_version) return unittest.skipUnless( correct_hf_hub_version, f"Test requires huggingface_hub with the version greater than {hf_hub_version}." )(test_case)
return decorator
def require_gguf_version_greater_or_equal(gguf_version): def decorator(test_case): correct_gguf_version = is_gguf_available() and version.parse( version.parse(importlib.metadata.version("gguf")).base_version ) >= version.parse(gguf_version) return unittest.skipUnless( correct_gguf_version, f"Test requires gguf with the version greater than {gguf_version}." )(test_case)
return decorator
def require_torchao_version_greater_or_equal(torchao_version): def decorator(test_case): correct_torchao_version = is_torchao_available() and version.parse( version.parse(importlib.metadata.version("torchao")).base_version ) >= version.parse(torchao_version) return unittest.skipUnless( correct_torchao_version, f"Test requires torchao with version greater than {torchao_version}." )(test_case)
return decorator
def require_kernels_version_greater_or_equal(kernels_version): def decorator(test_case): correct_kernels_version = is_kernels_available() and version.parse( version.parse(importlib.metadata.version("kernels")).base_version ) >= version.parse(kernels_version) return unittest.skipUnless( correct_kernels_version, f"Test requires kernels with version greater than {kernels_version}." )(test_case)
return decorator
def deprecate_after_peft_backend(test_case): """ Decorator marking a test that will be skipped after PEFT backend """ return unittest.skipUnless(not USE_PEFT_BACKEND, "test skipped in favor of PEFT backend")(test_case)
def get_python_version(): sys_info = sys.version_info major, minor = sys_info.major, sys_info.minor return major, minor
def load_numpy(arry: Union[str, np.ndarray], local_path: Optional[str] = None) -> np.ndarray: if isinstance(arry, str): if local_path is not None: # local_path can be passed to correct images of tests return Path(local_path, arry.split("/")[-5], arry.split("/")[-2], arry.split("/")[-1]).as_posix() elif arry.startswith("http://") or arry.startswith("https://"): response = requests.get(arry, timeout=DIFFUSERS_REQUEST_TIMEOUT) response.raise_for_status() arry = np.load(BytesIO(response.content)) elif os.path.isfile(arry): arry = np.load(arry) else: raise ValueError( f"Incorrect path or url, URLs must start with `http://` or `https://`, and {arry} is not a valid path" ) elif isinstance(arry, np.ndarray): pass else: raise ValueError( "Incorrect format used for numpy ndarray. Should be an url linking to an image, a local path, or a" " ndarray." )
return arry
def load_pt(url: str, map_location: Optional[str] = None, weights_only: Optional[bool] = True): response = requests.get(url, timeout=DIFFUSERS_REQUEST_TIMEOUT) response.raise_for_status() arry = torch.load(BytesIO(response.content), map_location=map_location, weights_only=weights_only) return arry
def load_image(image: Union[str, PIL.Image.Image]) -> PIL.Image.Image: """ Loads `image` to a PIL Image.
Args: image (`str` or `PIL.Image.Image`): The image to convert to the PIL Image format. Returns: `PIL.Image.Image`: A PIL Image. """ if isinstance(image, str): if image.startswith("http://") or image.startswith("https://"): image = PIL.Image.open(requests.get(image, stream=True, timeout=DIFFUSERS_REQUEST_TIMEOUT).raw) elif os.path.isfile(image): image = PIL.Image.open(image) else: raise ValueError( f"Incorrect path or url, URLs must start with `http://` or `https://`, and {image} is not a valid path" ) elif isinstance(image, PIL.Image.Image): image = image else: raise ValueError( "Incorrect format used for image. Should be an url linking to an image, a local path, or a PIL image." ) image = PIL.ImageOps.exif_transpose(image) image = image.convert("RGB") return image
def preprocess_image(image: PIL.Image, batch_size: int): w, h = image.size w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 image = image.resize((w, h), resample=PIL.Image.LANCZOS) image = np.array(image).astype(np.float32) / 255.0 image = np.vstack([image[None].transpose(0, 3, 1, 2)] * batch_size) image = torch.from_numpy(image) return 2.0 * image - 1.0
def export_to_gif(image: List[PIL.Image.Image], output_gif_path: str = None) -> str: if output_gif_path is None: output_gif_path = tempfile.NamedTemporaryFile(suffix=".gif").name
image[0].save( output_gif_path, save_all=True, append_images=image[1:], optimize=False, duration=100, loop=0, ) return output_gif_path
@contextmanagerdef buffered_writer(raw_f): f = io.BufferedWriter(raw_f) yield f f.flush()
def export_to_ply(mesh, output_ply_path: str = None): """ Write a PLY file for a mesh. """ if output_ply_path is None: output_ply_path = tempfile.NamedTemporaryFile(suffix=".ply").name
coords = mesh.verts.detach().cpu().numpy() faces = mesh.faces.cpu().numpy() rgb = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1)
with buffered_writer(open(output_ply_path, "wb")) as f: f.write(b"ply\n") f.write(b"format binary_little_endian 1.0\n") f.write(bytes(f"element vertex {len(coords)}\n", "ascii")) f.write(b"property float x\n") f.write(b"property float y\n") f.write(b"property float z\n") if rgb is not None: f.write(b"property uchar red\n") f.write(b"property uchar green\n") f.write(b"property uchar blue\n") if faces is not None: f.write(bytes(f"element face {len(faces)}\n", "ascii")) f.write(b"property list uchar int vertex_index\n") f.write(b"end_header\n")
if rgb is not None: rgb = (rgb * 255.499).round().astype(int) vertices = [ (*coord, *rgb) for coord, rgb in zip( coords.tolist(), rgb.tolist(), ) ] format = struct.Struct("<3f3B") for item in vertices: f.write(format.pack(*item)) else: format = struct.Struct("<3f") for vertex in coords.tolist(): f.write(format.pack(*vertex))
if faces is not None: for tri in faces.tolist(): f.write(format.pack(len(tri), *tri)) format = struct.Struct("<B3I") return output_ply_path
def export_to_obj(mesh, output_obj_path: str = None): if output_obj_path is None: output_obj_path = tempfile.NamedTemporaryFile(suffix=".obj").name
verts = mesh.verts.detach().cpu().numpy() faces = mesh.faces.cpu().numpy()
vertex_colors = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1) vertices = [ "{} {} {} {} {} {}".format(*coord, *color) for coord, color in zip(verts.tolist(), vertex_colors.tolist()) ]
faces = ["f {} {} {}".format(str(tri[0] + 1), str(tri[1] + 1), str(tri[2] + 1)) for tri in faces.tolist()]
combined_data = ["v " + vertex for vertex in vertices] + faces
with open(output_obj_path, "w") as f: f.writelines("\n".join(combined_data))
def export_to_video(video_frames: List[np.ndarray], output_video_path: str = None) -> str: if is_opencv_available(): import cv2 else: raise ImportError(BACKENDS_MAPPING["opencv"][1].format("export_to_video")) if output_video_path is None: output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name
fourcc = cv2.VideoWriter_fourcc(*"mp4v") h, w, c = video_frames[0].shape video_writer = cv2.VideoWriter(output_video_path, fourcc, fps=8, frameSize=(w, h)) for i in range(len(video_frames)): img = cv2.cvtColor(video_frames[i], cv2.COLOR_RGB2BGR) video_writer.write(img) return output_video_path
def load_hf_numpy(path) -> np.ndarray: base_url = "https://huggingface.co/datasets/fusing/diffusers-testing/resolve/main"
if not path.startswith("http://") and not path.startswith("https://"): path = os.path.join(base_url, urllib.parse.quote(path))
return load_numpy(path)
# --- pytest conf functions --- #
# to avoid multiple invocation from tests/conftest.py and examples/conftest.py - make sure it's called only oncepytest_opt_registered = {}
def pytest_addoption_shared(parser): """ This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there.
It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest` option.
""" option = "--make-reports" if option not in pytest_opt_registered: parser.addoption( option, action="store", default=False, help="generate report files. The value of this option is used as a prefix to report names", ) pytest_opt_registered[option] = 1
def pytest_terminal_summary_main(tr, id): """ Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current directory. The report files are prefixed with the test suite name.
This function emulates --duration and -rA pytest arguments.
This function is to be called from `conftest.py` via `pytest_terminal_summary` wrapper that has to be defined there.
Args: - tr: `terminalreporter` passed from `conftest.py` - id: unique id like `tests` or `examples` that will be incorporated into the final reports filenames - this is needed as some jobs have multiple runs of pytest, so we can't have them overwrite each other.
NB: this functions taps into a private _pytest API and while unlikely, it could break should pytest do internal changes - also it calls default internal methods of terminalreporter which can be hijacked by various `pytest-` plugins and interfere.
""" from _pytest.config import create_terminal_writer
if not len(id): id = "tests"
config = tr.config orig_writer = config.get_terminal_writer() orig_tbstyle = config.option.tbstyle orig_reportchars = tr.reportchars
dir = "reports" Path(dir).mkdir(parents=True, exist_ok=True) report_files = { k: f"{dir}/{id}_{k}.txt" for k in [ "durations", "errors", "failures_long", "failures_short", "failures_line", "passes", "stats", "summary_short", "warnings", ] }
# custom durations report # note: there is no need to call pytest --durations=XX to get this separate report # adapted from https://github.com/pytest-dev/pytest/blob/897f151e/src/_pytest/runner.py#L66 dlist = [] for replist in tr.stats.values(): for rep in replist: if hasattr(rep, "duration"): dlist.append(rep) if dlist: dlist.sort(key=lambda x: x.duration, reverse=True) with open(report_files["durations"], "w") as f: durations_min = 0.05 # sec f.write("slowest durations\n") for i, rep in enumerate(dlist): if rep.duration < durations_min: f.write(f"{len(dlist) - i} durations < {durations_min} secs were omitted") break f.write(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}\n")
def summary_failures_short(tr): # expecting that the reports were --tb=long (default) so we chop them off here to the last frame reports = tr.getreports("failed") if not reports: return tr.write_sep("=", "FAILURES SHORT STACK") for rep in reports: msg = tr._getfailureheadline(rep) tr.write_sep("_", msg, red=True, bold=True) # chop off the optional leading extra frames, leaving only the last one longrepr = re.sub(r".*_ _ _ (_ ){10,}_ _ ", "", rep.longreprtext, 0, re.M | re.S) tr._tw.line(longrepr) # note: not printing out any rep.sections to keep the report short
# use ready-made report funcs, we are just hijacking the filehandle to log to a dedicated file each # adapted from https://github.com/pytest-dev/pytest/blob/897f151e/src/_pytest/terminal.py#L814 # note: some pytest plugins may interfere by hijacking the default `terminalreporter` (e.g. # pytest-instafail does that)
# report failures with line/short/long styles config.option.tbstyle = "auto" # full tb with open(report_files["failures_long"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_failures()
# config.option.tbstyle = "short" # short tb with open(report_files["failures_short"], "w") as f: tr._tw = create_terminal_writer(config, f) summary_failures_short(tr)
config.option.tbstyle = "line" # one line per error with open(report_files["failures_line"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_failures()
with open(report_files["errors"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_errors()
with open(report_files["warnings"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_warnings() # normal warnings tr.summary_warnings() # final warnings
tr.reportchars = "wPpsxXEf" # emulate -rA (used in summary_passes() and short_test_summary()) with open(report_files["passes"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_passes()
with open(report_files["summary_short"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.short_test_summary()
with open(report_files["stats"], "w") as f: tr._tw = create_terminal_writer(config, f) tr.summary_stats()
# restore: tr._tw = orig_writer tr.reportchars = orig_reportchars config.option.tbstyle = orig_tbstyle
# Adapted from https://github.com/huggingface/transformers/blob/000e52aec8850d3fe2f360adc6fd256e5b47fe4c/src/transformers/testing_utils.py#L1905def is_flaky(max_attempts: int = 5, wait_before_retry: Optional[float] = None, description: Optional[str] = None): """ To decorate flaky tests (methods or entire classes). They will be retried on failures.
Args: max_attempts (`int`, *optional*, defaults to 5): The maximum number of attempts to retry the flaky test. wait_before_retry (`float`, *optional*): If provided, will wait that number of seconds before retrying the test. description (`str`, *optional*): A string to describe the situation (what / where / why is flaky, link to GH issue/PR comments, errors, etc.) """
def decorator(obj): # If decorating a class, wrap each test method on it if inspect.isclass(obj): for attr_name, attr_value in list(obj.__dict__.items()): if callable(attr_value) and attr_name.startswith("test"): # recursively decorate the method setattr(obj, attr_name, decorator(attr_value)) return obj
# Otherwise we're decorating a single test function / method @functools.wraps(obj) def wrapper(*args, **kwargs): retry_count = 1 while retry_count < max_attempts: try: return obj(*args, **kwargs) except Exception as err: msg = ( f"[FLAKY] {description or obj.__name__!r} " f"failed on attempt {retry_count}/{max_attempts}: {err}" ) print(msg, file=sys.stderr) if wait_before_retry is not None: time.sleep(wait_before_retry) retry_count += 1
return obj(*args, **kwargs)
return wrapper
return decorator
# Taken from: https://github.com/huggingface/transformers/blob/3658488ff77ff8d45101293e749263acf437f4d5/src/transformers/testing_utils.py#L1787def run_test_in_subprocess(test_case, target_func, inputs=None, timeout=None): """ To run a test in a subprocess. In particular, this can avoid (GPU) memory issue.
Args: test_case (`unittest.TestCase`): The test that will run `target_func`. target_func (`Callable`): The function implementing the actual testing logic. inputs (`dict`, *optional*, defaults to `None`): The inputs that will be passed to `target_func` through an (input) queue. timeout (`int`, *optional*, defaults to `None`): The timeout (in seconds) that will be passed to the input and output queues. If not specified, the env. variable `PYTEST_TIMEOUT` will be checked. If still `None`, its value will be set to `600`. """ if timeout is None: timeout = int(os.environ.get("PYTEST_TIMEOUT", 600))
start_methohd = "spawn" ctx = multiprocessing.get_context(start_methohd)
input_queue = ctx.Queue(1) output_queue = ctx.JoinableQueue(1)
# We can't send `unittest.TestCase` to the child, otherwise we get issues regarding pickle. input_queue.put(inputs, timeout=timeout)
process = ctx.Process(target=target_func, args=(input_queue, output_queue, timeout)) process.start() # Kill the child process if we can't get outputs from it in time: otherwise, the hanging subprocess prevents # the test to exit properly. try: results = output_queue.get(timeout=timeout) output_queue.task_done() except Exception as e: process.terminate() test_case.fail(e) process.join(timeout=timeout)
if results["error"] is not None: test_case.fail(f"{results['error']}")
class CaptureLogger: """ Args: Context manager to capture `logging` streams logger: 'logging` logger object Returns: The captured output is available via `self.out` Example: ```python >>> from diffusers import logging >>> from diffusers.testing_utils import CaptureLogger
>>> msg = "Testing 1, 2, 3" >>> logging.set_verbosity_info() >>> logger = logging.get_logger("diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.py") >>> with CaptureLogger(logger) as cl: ... logger.info(msg) >>> assert cl.out, msg + "\n" ``` """
def __init__(self, logger): self.logger = logger self.io = StringIO() self.sh = logging.StreamHandler(self.io) self.out = ""
def __enter__(self): self.logger.addHandler(self.sh) return self
def __exit__(self, *exc): self.logger.removeHandler(self.sh) self.out = self.io.getvalue()
def __repr__(self): return f"captured: {self.out}\n"
def enable_full_determinism(): """ Helper function for reproducible behavior during distributed training. See - https://pytorch.org/docs/stable/notes/randomness.html for pytorch """ from .torch_utils import enable_full_determinism as _enable_full_determinism
logger.warning( "enable_full_determinism has been moved to diffusers.utils.torch_utils. " "Importing from diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _enable_full_determinism()
def disable_full_determinism(): from .torch_utils import disable_full_determinism as _disable_full_determinism
logger.warning( "disable_full_determinism has been moved to diffusers.utils.torch_utils. " "Importing from diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _disable_full_determinism()
# Utils for custom and alternative accelerator devicesdef _is_torch_fp16_available(device): if not is_torch_available(): return False
import torch
device = torch.device(device)
try: x = torch.zeros((2, 2), dtype=torch.float16).to(device) _ = torch.mul(x, x) return True
except Exception as e: if device.type == "cuda": raise ValueError( f"You have passed a device of type 'cuda' which should work with 'fp16', but 'cuda' does not seem to be correctly installed on your machine: {e}" )
return False
def _is_torch_fp64_available(device): if not is_torch_available(): return False
import torch
device = torch.device(device)
try: x = torch.zeros((2, 2), dtype=torch.float64).to(device) _ = torch.mul(x, x) return True
except Exception as e: if device.type == "cuda": raise ValueError( f"You have passed a device of type 'cuda' which should work with 'fp64', but 'cuda' does not seem to be correctly installed on your machine: {e}" )
return False
# Guard these lookups for when Torch is not used - alternative accelerator support is for PyTorchif is_torch_available(): # Behaviour flags BACKEND_SUPPORTS_TRAINING = {"cuda": True, "xpu": True, "cpu": True, "mps": False, "default": True}
# Function definitions BACKEND_EMPTY_CACHE = { "cuda": torch.cuda.empty_cache, "xpu": torch.xpu.empty_cache, "cpu": None, "mps": torch.mps.empty_cache, "default": None, } BACKEND_DEVICE_COUNT = { "cuda": torch.cuda.device_count, "xpu": torch.xpu.device_count, "cpu": lambda: 0, "mps": lambda: 0, "default": 0, } BACKEND_MANUAL_SEED = { "cuda": torch.cuda.manual_seed, "xpu": torch.xpu.manual_seed, "cpu": torch.manual_seed, "mps": torch.mps.manual_seed, "default": torch.manual_seed, } BACKEND_RESET_PEAK_MEMORY_STATS = { "cuda": torch.cuda.reset_peak_memory_stats, "xpu": getattr(torch.xpu, "reset_peak_memory_stats", None), "cpu": None, "mps": None, "default": None, } BACKEND_RESET_MAX_MEMORY_ALLOCATED = { "cuda": torch.cuda.reset_max_memory_allocated, "xpu": getattr(torch.xpu, "reset_peak_memory_stats", None), "cpu": None, "mps": None, "default": None, } BACKEND_MAX_MEMORY_ALLOCATED = { "cuda": torch.cuda.max_memory_allocated, "xpu": getattr(torch.xpu, "max_memory_allocated", None), "cpu": 0, "mps": 0, "default": 0, } BACKEND_SYNCHRONIZE = { "cuda": torch.cuda.synchronize, "xpu": getattr(torch.xpu, "synchronize", None), "cpu": None, "mps": None, "default": None, }
# This dispatches a defined function according to the accelerator from the function definitions.def _device_agnostic_dispatch(device: str, dispatch_table: Dict[str, Callable], *args, **kwargs): if device not in dispatch_table: return dispatch_table["default"](*args, **kwargs)
fn = dispatch_table[device]
# Some device agnostic functions return values. Need to guard against 'None' instead at # user level if not callable(fn): return fn
return fn(*args, **kwargs)
# These are callables which automatically dispatch the function specific to the acceleratordef backend_manual_seed(device: str, seed: int): from .torch_utils import backend_manual_seed as _backend_manual_seed
logger.warning( "backend_manual_seed has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_manual_seed(device, seed)
def backend_synchronize(device: str): from .torch_utils import backend_synchronize as _backend_synchronize
logger.warning( "backend_synchronize has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_synchronize(device)
def backend_empty_cache(device: str): from .torch_utils import backend_empty_cache as _backend_empty_cache
logger.warning( "backend_empty_cache has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_empty_cache(device)
def backend_device_count(device: str): from .torch_utils import backend_device_count as _backend_device_count
logger.warning( "backend_device_count has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_device_count(device)
def backend_reset_peak_memory_stats(device: str): from .torch_utils import backend_reset_peak_memory_stats as _backend_reset_peak_memory_stats
logger.warning( "backend_reset_peak_memory_stats has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_reset_peak_memory_stats(device)
def backend_reset_max_memory_allocated(device: str): from .torch_utils import backend_reset_max_memory_allocated as _backend_reset_max_memory_allocated
logger.warning( "backend_reset_max_memory_allocated has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_reset_max_memory_allocated(device)
def backend_max_memory_allocated(device: str): from .torch_utils import backend_max_memory_allocated as _backend_max_memory_allocated
logger.warning( "backend_max_memory_allocated has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_max_memory_allocated(device)
# These are callables which return boolean behaviour flags and can be used to specify some# device agnostic alternative where the feature is unsupported.def backend_supports_training(device: str): from .torch_utils import backend_supports_training as _backend_supports_training
logger.warning( "backend_supports_training has been moved to diffusers.utils.torch_utils. " "diffusers.utils.testing_utils is deprecated and will be removed in a future version." ) return _backend_supports_training(device)
# Guard for when Torch is not availableif is_torch_available(): # Update device function dict mapping def update_mapping_from_spec(device_fn_dict: Dict[str, Callable], attribute_name: str): try: # Try to import the function directly spec_fn = getattr(device_spec_module, attribute_name) device_fn_dict[torch_device] = spec_fn except AttributeError as e: # If the function doesn't exist, and there is no default, throw an error if "default" not in device_fn_dict: raise AttributeError( f"`{attribute_name}` not found in '{device_spec_path}' and no default fallback function found." ) from e
if "DIFFUSERS_TEST_DEVICE_SPEC" in os.environ: device_spec_path = os.environ["DIFFUSERS_TEST_DEVICE_SPEC"] if not Path(device_spec_path).is_file(): raise ValueError(f"Specified path to device specification file is not found. Received {device_spec_path}")
try: import_name = device_spec_path[: device_spec_path.index(".py")] except ValueError as e: raise ValueError(f"Provided device spec file is not a Python file! Received {device_spec_path}") from e
device_spec_module = importlib.import_module(import_name)
try: device_name = device_spec_module.DEVICE_NAME except AttributeError: raise AttributeError("Device spec file did not contain `DEVICE_NAME`")
if "DIFFUSERS_TEST_DEVICE" in os.environ and torch_device != device_name: msg = f"Mismatch between environment variable `DIFFUSERS_TEST_DEVICE` '{torch_device}' and device found in spec '{device_name}'\n" msg += "Either unset `DIFFUSERS_TEST_DEVICE` or ensure it matches device spec name." raise ValueError(msg)
torch_device = device_name
# Add one entry here for each `BACKEND_*` dictionary. update_mapping_from_spec(BACKEND_MANUAL_SEED, "MANUAL_SEED_FN") update_mapping_from_spec(BACKEND_EMPTY_CACHE, "EMPTY_CACHE_FN") update_mapping_from_spec(BACKEND_DEVICE_COUNT, "DEVICE_COUNT_FN") update_mapping_from_spec(BACKEND_SUPPORTS_TRAINING, "SUPPORTS_TRAINING") update_mapping_from_spec(BACKEND_RESET_PEAK_MEMORY_STATS, "RESET_PEAK_MEMORY_STATS_FN") update_mapping_from_spec(BACKEND_RESET_MAX_MEMORY_ALLOCATED, "RESET_MAX_MEMORY_ALLOCATED_FN") update_mapping_from_spec(BACKEND_MAX_MEMORY_ALLOCATED, "MAX_MEMORY_ALLOCATED_FN")
# Modified from https://github.com/huggingface/transformers/blob/cdfb018d0300fef3b07d9220f3efe9c2a9974662/src/transformers/testing_utils.py#L3090
# Type definition of key used in `Expectations` class.DeviceProperties = Tuple[Union[str, None], Union[int, None]]
@functools.lru_cachedef get_device_properties() -> DeviceProperties: """ Get environment device properties. """ if IS_CUDA_SYSTEM or IS_ROCM_SYSTEM: import torch
major, _ = torch.cuda.get_device_capability() if IS_ROCM_SYSTEM: return ("rocm", major) else: return ("cuda", major) elif IS_XPU_SYSTEM: import torch
# To get more info of the architecture meaning and bit allocation, refer to https://github.com/intel/llvm/blob/sycl/sycl/include/sycl/ext/oneapi/experimental/device_architecture.def arch = torch.xpu.get_device_capability()["architecture"] gen_mask = 0x000000FF00000000 gen = (arch & gen_mask) >> 32 return ("xpu", gen) else: return (torch_device, None)
if TYPE_CHECKING: DevicePropertiesUserDict = UserDict[DeviceProperties, Any]else: DevicePropertiesUserDict = UserDict
if is_torch_available(): from diffusers.hooks._common import _GO_LC_SUPPORTED_PYTORCH_LAYERS from diffusers.hooks.group_offloading import ( _GROUP_ID_LAZY_LEAF, _compute_group_hash, _find_parent_module_in_module_dict, _gather_buffers_with_no_group_offloading_parent, _gather_parameters_with_no_group_offloading_parent, )
def _get_expected_safetensors_files( module: torch.nn.Module, offload_to_disk_path: str, offload_type: str, num_blocks_per_group: Optional[int] = None, ) -> Set[str]: expected_files = set()
def get_hashed_filename(group_id: str) -> str: short_hash = _compute_group_hash(group_id) return os.path.join(offload_to_disk_path, f"group_{short_hash}.safetensors")
if offload_type == "block_level": if num_blocks_per_group is None: raise ValueError("num_blocks_per_group must be provided for 'block_level' offloading.")
# Handle groups of ModuleList and Sequential blocks unmatched_modules = [] for name, submodule in module.named_children(): if not isinstance(submodule, (torch.nn.ModuleList, torch.nn.Sequential)): unmatched_modules.append(module) continue
for i in range(0, len(submodule), num_blocks_per_group): current_modules = submodule[i : i + num_blocks_per_group] if not current_modules: continue group_id = f"{name}_{i}_{i + len(current_modules) - 1}" expected_files.add(get_hashed_filename(group_id))
# Handle the group for unmatched top-level modules and parameters for module in unmatched_modules: expected_files.add(get_hashed_filename(f"{module.__class__.__name__}_unmatched_group"))
elif offload_type == "leaf_level": # Handle leaf-level module groups for name, submodule in module.named_modules(): if isinstance(submodule, _GO_LC_SUPPORTED_PYTORCH_LAYERS): # These groups will always have parameters, so a file is expected expected_files.add(get_hashed_filename(name))
# Handle groups for non-leaf parameters/buffers modules_with_group_offloading = { name for name, sm in module.named_modules() if isinstance(sm, _GO_LC_SUPPORTED_PYTORCH_LAYERS) } parameters = _gather_parameters_with_no_group_offloading_parent(module, modules_with_group_offloading) buffers = _gather_buffers_with_no_group_offloading_parent(module, modules_with_group_offloading)
all_orphans = parameters + buffers if all_orphans: parent_to_tensors = {} module_dict = dict(module.named_modules()) for tensor_name, _ in all_orphans: parent_name = _find_parent_module_in_module_dict(tensor_name, module_dict) if parent_name not in parent_to_tensors: parent_to_tensors[parent_name] = [] parent_to_tensors[parent_name].append(tensor_name)
for parent_name in parent_to_tensors: # A file is expected for each parent that gathers orphaned tensors expected_files.add(get_hashed_filename(parent_name)) expected_files.add(get_hashed_filename(_GROUP_ID_LAZY_LEAF))
else: raise ValueError(f"Unsupported offload_type: {offload_type}")
return expected_files
def _check_safetensors_serialization( module: torch.nn.Module, offload_to_disk_path: str, offload_type: str, num_blocks_per_group: Optional[int] = None, ) -> bool: if not os.path.isdir(offload_to_disk_path): return False, None, None
expected_files = _get_expected_safetensors_files( module, offload_to_disk_path, offload_type, num_blocks_per_group ) actual_files = set(glob.glob(os.path.join(offload_to_disk_path, "*.safetensors"))) missing_files = expected_files - actual_files extra_files = actual_files - expected_files
is_correct = not missing_files and not extra_files return is_correct, extra_files, missing_files
class Expectations(DevicePropertiesUserDict): def get_expectation(self) -> Any: """ Find best matching expectation based on environment device properties. """ return self.find_expectation(get_device_properties())
@staticmethod def is_default(key: DeviceProperties) -> bool: return all(p is None for p in key)
@staticmethod def score(key: DeviceProperties, other: DeviceProperties) -> int: """ Returns score indicating how similar two instances of the `Properties` tuple are. Points are calculated using bits, but documented as int. Rules are as follows: * Matching `type` gives 8 points. * Semi-matching `type`, for example cuda and rocm, gives 4 points. * Matching `major` (compute capability major version) gives 2 points. * Default expectation (if present) gives 1 points. """ (device_type, major) = key (other_device_type, other_major) = other
score = 0b0 if device_type == other_device_type: score |= 0b1000 elif device_type in ["cuda", "rocm"] and other_device_type in ["cuda", "rocm"]: score |= 0b100
if major == other_major and other_major is not None: score |= 0b10
if Expectations.is_default(other): score |= 0b1
return int(score)
def find_expectation(self, key: DeviceProperties = (None, None)) -> Any: """ Find best matching expectation based on provided device properties. """ (result_key, result) = max(self.data.items(), key=lambda x: Expectations.score(key, x[0]))
if Expectations.score(key, result_key) == 0: raise ValueError(f"No matching expectation found for {key}")
return result
def __repr__(self): return f"{self.data}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""PyTorch utilities: Utilities related to PyTorch"""
import functoolsimport osfrom typing import Callable, Dict, List, Optional, Tuple, Union
from . import loggingfrom .import_utils import is_torch_available, is_torch_npu_available, is_torch_version
if is_torch_available(): import torch from torch.fft import fftn, fftshift, ifftn, ifftshift
BACKEND_SUPPORTS_TRAINING = {"cuda": True, "xpu": True, "cpu": True, "mps": False, "default": True} BACKEND_EMPTY_CACHE = { "cuda": torch.cuda.empty_cache, "xpu": torch.xpu.empty_cache, "cpu": None, "mps": torch.mps.empty_cache, "default": None, } BACKEND_DEVICE_COUNT = { "cuda": torch.cuda.device_count, "xpu": torch.xpu.device_count, "cpu": lambda: 0, "mps": lambda: 0, "default": 0, } BACKEND_MANUAL_SEED = { "cuda": torch.cuda.manual_seed, "xpu": torch.xpu.manual_seed, "cpu": torch.manual_seed, "mps": torch.mps.manual_seed, "default": torch.manual_seed, } BACKEND_RESET_PEAK_MEMORY_STATS = { "cuda": torch.cuda.reset_peak_memory_stats, "xpu": getattr(torch.xpu, "reset_peak_memory_stats", None), "cpu": None, "mps": None, "default": None, } BACKEND_RESET_MAX_MEMORY_ALLOCATED = { "cuda": torch.cuda.reset_max_memory_allocated, "xpu": getattr(torch.xpu, "reset_peak_memory_stats", None), "cpu": None, "mps": None, "default": None, } BACKEND_MAX_MEMORY_ALLOCATED = { "cuda": torch.cuda.max_memory_allocated, "xpu": getattr(torch.xpu, "max_memory_allocated", None), "cpu": 0, "mps": 0, "default": 0, } BACKEND_SYNCHRONIZE = { "cuda": torch.cuda.synchronize, "xpu": getattr(torch.xpu, "synchronize", None), "cpu": None, "mps": None, "default": None, }logger = logging.get_logger(__name__) # pylint: disable=invalid-name
try: from torch._dynamo import allow_in_graph as maybe_allow_in_graphexcept (ImportError, ModuleNotFoundError):
def maybe_allow_in_graph(cls): return cls
# This dispatches a defined function according to the accelerator from the function definitions.def _device_agnostic_dispatch(device: str, dispatch_table: Dict[str, Callable], *args, **kwargs): if device not in dispatch_table: return dispatch_table["default"](*args, **kwargs)
fn = dispatch_table[device]
# Some device agnostic functions return values. Need to guard against 'None' instead at # user level if not callable(fn): return fn
return fn(*args, **kwargs)
# These are callables which automatically dispatch the function specific to the acceleratordef backend_manual_seed(device: str, seed: int): return _device_agnostic_dispatch(device, BACKEND_MANUAL_SEED, seed)
def backend_synchronize(device: str): return _device_agnostic_dispatch(device, BACKEND_SYNCHRONIZE)
def backend_empty_cache(device: str): return _device_agnostic_dispatch(device, BACKEND_EMPTY_CACHE)
def backend_device_count(device: str): return _device_agnostic_dispatch(device, BACKEND_DEVICE_COUNT)
def backend_reset_peak_memory_stats(device: str): return _device_agnostic_dispatch(device, BACKEND_RESET_PEAK_MEMORY_STATS)
def backend_reset_max_memory_allocated(device: str): return _device_agnostic_dispatch(device, BACKEND_RESET_MAX_MEMORY_ALLOCATED)
def backend_max_memory_allocated(device: str): return _device_agnostic_dispatch(device, BACKEND_MAX_MEMORY_ALLOCATED)
# These are callables which return boolean behaviour flags and can be used to specify some# device agnostic alternative where the feature is unsupported.def backend_supports_training(device: str): if not is_torch_available(): return False
if device not in BACKEND_SUPPORTS_TRAINING: device = "default"
return BACKEND_SUPPORTS_TRAINING[device]
def randn_tensor( shape: Union[Tuple, List], generator: Optional[Union[List["torch.Generator"], "torch.Generator"]] = None, device: Optional[Union[str, "torch.device"]] = None, dtype: Optional["torch.dtype"] = None, layout: Optional["torch.layout"] = None,): """A helper function to create random tensors on the desired `device` with the desired `dtype`. When passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor is always created on the CPU. """ # device on which tensor is created defaults to device if isinstance(device, str): device = torch.device(device) rand_device = device batch_size = shape[0]
layout = layout or torch.strided device = device or torch.device("cpu")
if generator is not None: gen_device_type = generator.device.type if not isinstance(generator, list) else generator[0].device.type if gen_device_type != device.type and gen_device_type == "cpu": rand_device = "cpu" if device != "mps": logger.info( f"The passed generator was created on 'cpu' even though a tensor on {device} was expected." f" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably" f" slightly speed up this function by passing a generator that was created on the {device} device." ) elif gen_device_type != device.type and gen_device_type == "cuda": raise ValueError(f"Cannot generate a {device} tensor from a generator of type {gen_device_type}.")
# make sure generator list of length 1 is treated like a non-list if isinstance(generator, list) and len(generator) == 1: generator = generator[0]
if isinstance(generator, list): shape = (1,) + shape[1:] latents = [ torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype, layout=layout) for i in range(batch_size) ] latents = torch.cat(latents, dim=0).to(device) else: latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device)
return latents
def is_compiled_module(module) -> bool: """Check whether the module was compiled with torch.compile()""" if is_torch_version("<", "2.0.0") or not hasattr(torch, "_dynamo"): return False return isinstance(module, torch._dynamo.eval_frame.OptimizedModule)
def unwrap_module(module): """Unwraps a module if it was compiled with torch.compile()""" return module._orig_mod if is_compiled_module(module) else module
def fourier_filter(x_in: "torch.Tensor", threshold: int, scale: int) -> "torch.Tensor": """Fourier filter as introduced in FreeU (https://huggingface.co/papers/2309.11497).
This version of the method comes from here: https://github.com/huggingface/diffusers/pull/5164#issuecomment-1732638706 """ x = x_in B, C, H, W = x.shape
# Non-power of 2 images must be float32 if (W & (W - 1)) != 0 or (H & (H - 1)) != 0: x = x.to(dtype=torch.float32) # fftn does not support bfloat16 elif x.dtype == torch.bfloat16: x = x.to(dtype=torch.float32)
# FFT x_freq = fftn(x, dim=(-2, -1)) x_freq = fftshift(x_freq, dim=(-2, -1))
B, C, H, W = x_freq.shape mask = torch.ones((B, C, H, W), device=x.device)
crow, ccol = H // 2, W // 2 mask[..., crow - threshold : crow + threshold, ccol - threshold : ccol + threshold] = scale x_freq = x_freq * mask
# IFFT x_freq = ifftshift(x_freq, dim=(-2, -1)) x_filtered = ifftn(x_freq, dim=(-2, -1)).real
return x_filtered.to(dtype=x_in.dtype)
def apply_freeu( resolution_idx: int, hidden_states: "torch.Tensor", res_hidden_states: "torch.Tensor", **freeu_kwargs) -> Tuple["torch.Tensor", "torch.Tensor"]: """Applies the FreeU mechanism as introduced in https: //arxiv.org/abs/2309.11497. Adapted from the official code repository: https://github.com/ChenyangSi/FreeU.
Args: resolution_idx (`int`): Integer denoting the UNet block where FreeU is being applied. hidden_states (`torch.Tensor`): Inputs to the underlying block. res_hidden_states (`torch.Tensor`): Features from the skip block corresponding to the underlying block. s1 (`float`): Scaling factor for stage 1 to attenuate the contributions of the skip features. s2 (`float`): Scaling factor for stage 2 to attenuate the contributions of the skip features. b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features. b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features. """ if resolution_idx == 0: num_half_channels = hidden_states.shape[1] // 2 hidden_states[:, :num_half_channels] = hidden_states[:, :num_half_channels] * freeu_kwargs["b1"] res_hidden_states = fourier_filter(res_hidden_states, threshold=1, scale=freeu_kwargs["s1"]) if resolution_idx == 1: num_half_channels = hidden_states.shape[1] // 2 hidden_states[:, :num_half_channels] = hidden_states[:, :num_half_channels] * freeu_kwargs["b2"] res_hidden_states = fourier_filter(res_hidden_states, threshold=1, scale=freeu_kwargs["s2"])
return hidden_states, res_hidden_states
def get_torch_cuda_device_capability(): if torch.cuda.is_available(): device = torch.device("cuda") compute_capability = torch.cuda.get_device_capability(device) compute_capability = f"{compute_capability[0]}.{compute_capability[1]}" return float(compute_capability) else: return None
@functools.lru_cachedef get_device(): if torch.cuda.is_available(): return "cuda" elif is_torch_npu_available(): return "npu" elif hasattr(torch, "xpu") and torch.xpu.is_available(): return "xpu" elif torch.backends.mps.is_available(): return "mps" else: return "cpu"
def empty_device_cache(device_type: Optional[str] = None): if device_type is None: device_type = get_device() if device_type in ["cpu"]: return device_mod = getattr(torch, device_type, torch.cuda) device_mod.empty_cache()
def device_synchronize(device_type: Optional[str] = None): if device_type is None: device_type = get_device() device_mod = getattr(torch, device_type, torch.cuda) device_mod.synchronize()
def enable_full_determinism(): """ Helper function for reproducible behavior during distributed training. See - https://pytorch.org/docs/stable/notes/randomness.html for pytorch """ # Enable PyTorch deterministic mode. This potentially requires either the environment # variable 'CUDA_LAUNCH_BLOCKING' or 'CUBLAS_WORKSPACE_CONFIG' to be set, # depending on the CUDA version, so we set them both here os.environ["CUDA_LAUNCH_BLOCKING"] = "1" os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8" torch.use_deterministic_algorithms(True)
# Enable CUDNN deterministic mode torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.backends.cuda.matmul.allow_tf32 = False
def disable_full_determinism(): os.environ["CUDA_LAUNCH_BLOCKING"] = "0" os.environ["CUBLAS_WORKSPACE_CONFIG"] = "" torch.use_deterministic_algorithms(False)
if is_torch_available(): torch_device = get_device()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Typing utilities: Utilities related to type checking and validation"""
from typing import Any, Dict, List, Set, Tuple, Type, Union, get_args, get_origin
def _is_valid_type(obj: Any, class_or_tuple: Union[Type, Tuple[Type, ...]]) -> bool: """ Checks if an object is an instance of any of the provided types. For collections, it checks if every element is of the correct type as well. """ if not isinstance(class_or_tuple, tuple): class_or_tuple = (class_or_tuple,)
# Unpack unions unpacked_class_or_tuple = [] for t in class_or_tuple: if get_origin(t) is Union: unpacked_class_or_tuple.extend(get_args(t)) else: unpacked_class_or_tuple.append(t) class_or_tuple = tuple(unpacked_class_or_tuple)
if Any in class_or_tuple: return True
obj_type = type(obj) # Classes with obj's type class_or_tuple = {t for t in class_or_tuple if isinstance(obj, get_origin(t) or t)}
# Singular types (e.g. int, ControlNet, ...) # Untyped collections (e.g. List, but not List[int]) elem_class_or_tuple = {get_args(t) for t in class_or_tuple} if () in elem_class_or_tuple: return True # Typed lists or sets elif obj_type in (list, set): return any(all(_is_valid_type(x, t) for x in obj) for t in elem_class_or_tuple) # Typed tuples elif obj_type is tuple: return any( # Tuples with any length and single type (e.g. Tuple[int, ...]) (len(t) == 2 and t[-1] is Ellipsis and all(_is_valid_type(x, t[0]) for x in obj)) or # Tuples with fixed length and any types (e.g. Tuple[int, str]) (len(obj) == len(t) and all(_is_valid_type(x, tt) for x, tt in zip(obj, t))) for t in elem_class_or_tuple ) # Typed dicts elif obj_type is dict: return any( all(_is_valid_type(k, kt) and _is_valid_type(v, vt) for k, v in obj.items()) for kt, vt in elem_class_or_tuple )
else: return False
def _get_detailed_type(obj: Any) -> Type: """ Gets a detailed type for an object, including nested types for collections. """ obj_type = type(obj)
if obj_type in (list, set): obj_origin_type = List if obj_type is list else Set elems_type = Union[tuple({_get_detailed_type(x) for x in obj})] return obj_origin_type[elems_type] elif obj_type is tuple: return Tuple[tuple(_get_detailed_type(x) for x in obj)] elif obj_type is dict: keys_type = Union[tuple({_get_detailed_type(k) for k in obj.keys()})] values_type = Union[tuple({_get_detailed_type(k) for k in obj.values()})] return Dict[keys_type, values_type] else: return obj_type123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Utilities for working with package versions"""
import importlib.metadataimport operatorimport reimport sysfrom typing import Optional
from packaging import version
ops = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt,}
def _compare_versions(op, got_ver, want_ver, requirement, pkg, hint): if got_ver is None or want_ver is None: raise ValueError( f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider" f" reinstalling {pkg}." ) if not ops[op](version.parse(got_ver), version.parse(want_ver)): raise ImportError( f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}" )
def require_version(requirement: str, hint: Optional[str] = None) -> None: """ Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
The installed module version comes from the *site-packages* dir via *importlib.metadata*.
Args: requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy" hint (`str`, *optional*): what suggestion to print in case of requirements not being met
Example:
```python require_version("pandas>1.1.2") require_version("numpy>1.18.5", "this is important to have for whatever reason") ```"""
hint = f"\n{hint}" if hint is not None else ""
# non-versioned check if re.match(r"^[\w_\-\d]+$", requirement): pkg, op, want_ver = requirement, None, None else: match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)", requirement) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" f" got {requirement}" ) pkg, want_full = match[0] want_range = want_full.split(",") # there could be multiple requirements wanted = {} for w in want_range: match = re.findall(r"^([\s!=<>]{1,2})(.+)", w) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," f" but got {requirement}" ) op, want_ver = match[0] wanted[op] = want_ver if op not in ops: raise ValueError(f"{requirement}: need one of {list(ops.keys())}, but got {op}")
# special case if pkg == "python": got_ver = ".".join([str(x) for x in sys.version_info[:3]]) for op, want_ver in wanted.items(): _compare_versions(op, got_ver, want_ver, requirement, pkg, hint) return
# check if any version is installed try: got_ver = importlib.metadata.version(pkg) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"The '{requirement}' distribution was not found and is required by this application. {hint}" )
# check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
def require_version_core(requirement): """require_version wrapper which emits a core-specific hint on failure""" hint = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(requirement, hint)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# tests directory-specific settings - this file is run automatically# by pytest before any tests are run
import sysimport warningsfrom os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun# 'pip install -e .[dev]' when switching between checkouts and running tests.git_repo_path = abspath(join(dirname(dirname(__file__)), "src"))sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until# they become normal warnings - i.e. the tests still need to test the current functionalitywarnings.simplefilter(action="ignore", category=FutureWarning)
def pytest_configure(config): config.addinivalue_line("markers", "big_accelerator: marks tests as requiring big accelerator resources")
def pytest_addoption(parser): from .testing_utils import pytest_addoption_shared
pytest_addoption_shared(parser)
def pytest_terminal_summary(terminalreporter): from .testing_utils import pytest_terminal_summary_main
make_reports = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(terminalreporter, id=make_reports)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# limitations under the License.
from typing import Optional, Tuple, Union
import torch
from diffusers import DiffusionPipeline, ImagePipelineOutput, SchedulerMixin, UNet2DModel
class CustomLocalPipeline(DiffusionPipeline): r""" This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
Parameters: unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image. scheduler ([`SchedulerMixin`]): A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of [`DDPMScheduler`], or [`DDIMScheduler`]. """
def __init__(self, unet: UNet2DModel, scheduler: SchedulerMixin): super().__init__() self.register_modules(unet=unet, scheduler=scheduler)
@torch.no_grad() def __call__( self, batch_size: int = 1, generator: Optional[torch.Generator] = None, num_inference_steps: int = 50, output_type: Optional[str] = "pil", return_dict: bool = True, **kwargs, ) -> Union[ImagePipelineOutput, Tuple]: r""" Args: batch_size (`int`, *optional*, defaults to 1): The number of images to generate. generator (`torch.Generator`, *optional*): A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. eta (`float`, *optional*, defaults to 0.0): The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM). num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
Returns: [`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images. """
# Sample gaussian noise to begin loop image = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size), generator=generator, ) image = image.to(self.device)
# set step values self.scheduler.set_timesteps(num_inference_steps)
for t in self.progress_bar(self.scheduler.timesteps): # 1. predict noise model_output model_output = self.unet(image, t).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 image = self.scheduler.step(model_output, t, image).prev_sample
image = (image / 2 + 0.5).clamp(0, 1) image = image.cpu().permute(0, 2, 3, 1).numpy() if output_type == "pil": image = self.numpy_to_pil(image)
if not return_dict: return (image,), "This is a local test"
return ImagePipelineOutput(images=image), "This is a local test"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# limitations under the License.
from typing import Optional, Tuple, Union
import torch
from diffusers import SchedulerMixin, UNet2DModelfrom diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class CustomLocalPipeline(DiffusionPipeline): r""" This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
Parameters: unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image. scheduler ([`SchedulerMixin`]): A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of [`DDPMScheduler`], or [`DDIMScheduler`]. """
def __init__(self, unet: UNet2DModel, scheduler: SchedulerMixin): super().__init__() self.register_modules(unet=unet, scheduler=scheduler)
@torch.no_grad() def __call__( self, batch_size: int = 1, generator: Optional[torch.Generator] = None, num_inference_steps: int = 50, output_type: Optional[str] = "pil", return_dict: bool = True, **kwargs, ) -> Union[ImagePipelineOutput, Tuple]: r""" Args: batch_size (`int`, *optional*, defaults to 1): The number of images to generate. generator (`torch.Generator`, *optional*): A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. eta (`float`, *optional*, defaults to 0.0): The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM). num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
Returns: [`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images. """
# Sample gaussian noise to begin loop image = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size), generator=generator, ) image = image.to(self.device)
# set step values self.scheduler.set_timesteps(num_inference_steps)
for t in self.progress_bar(self.scheduler.timesteps): # 1. predict noise model_output model_output = self.unet(image, t).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 image = self.scheduler.step(model_output, t, image).prev_sample
image = (image / 2 + 0.5).clamp(0, 1) image = image.cpu().permute(0, 2, 3, 1).numpy() if output_type == "pil": image = self.numpy_to_pil(image)
if not return_dict: return (image,), "This is a local test"
return ImagePipelineOutput(images=image), "This is a local test"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import contextlibimport gcimport unittest
import torchfrom parameterized import parameterized
from diffusers.hooks import HookRegistry, ModelHookfrom diffusers.models import ModelMixinfrom diffusers.pipelines.pipeline_utils import DiffusionPipelinefrom diffusers.utils import get_loggerfrom diffusers.utils.import_utils import compare_versions
from ..testing_utils import ( backend_empty_cache, backend_max_memory_allocated, backend_reset_peak_memory_stats, require_torch_accelerator, torch_device,)
class DummyBlock(torch.nn.Module): def __init__(self, in_features: int, hidden_features: int, out_features: int) -> None: super().__init__()
self.proj_in = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.proj_out = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.proj_in(x) x = self.activation(x) x = self.proj_out(x) return x
class DummyModel(ModelMixin): def __init__(self, in_features: int, hidden_features: int, out_features: int, num_layers: int) -> None: super().__init__()
self.linear_1 = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.blocks = torch.nn.ModuleList( [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] ) self.linear_2 = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.linear_1(x) x = self.activation(x) for block in self.blocks: x = block(x) x = self.linear_2(x) return x
# This model implementation contains one type of block (single_blocks) instantiated before another type of block (double_blocks).# The invocation order of these blocks, however, is first the double_blocks and then the single_blocks.# With group offloading implementation before https://github.com/huggingface/diffusers/pull/11375, such a modeling implementation# would result in a device mismatch error because of the assumptions made by the code. The failure case occurs when using:# offload_type="block_level", num_blocks_per_group=2, use_stream=True# Post the linked PR, the implementation will work as expected.class DummyModelWithMultipleBlocks(ModelMixin): def __init__( self, in_features: int, hidden_features: int, out_features: int, num_layers: int, num_single_layers: int ) -> None: super().__init__()
self.linear_1 = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.single_blocks = torch.nn.ModuleList( [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_single_layers)] ) self.double_blocks = torch.nn.ModuleList( [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] ) self.linear_2 = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.linear_1(x) x = self.activation(x) for block in self.double_blocks: x = block(x) for block in self.single_blocks: x = block(x) x = self.linear_2(x) return x
# Test for https://github.com/huggingface/diffusers/pull/12077class DummyModelWithLayerNorm(ModelMixin): def __init__(self, in_features: int, hidden_features: int, out_features: int, num_layers: int) -> None: super().__init__()
self.linear_1 = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.blocks = torch.nn.ModuleList( [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] ) self.layer_norm = torch.nn.LayerNorm(hidden_features, elementwise_affine=True) self.linear_2 = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.linear_1(x) x = self.activation(x) for block in self.blocks: x = block(x) x = self.layer_norm(x) x = self.linear_2(x) return x
class DummyPipeline(DiffusionPipeline): model_cpu_offload_seq = "model"
def __init__(self, model: torch.nn.Module) -> None: super().__init__()
self.register_modules(model=model)
def __call__(self, x: torch.Tensor) -> torch.Tensor: for _ in range(2): x = x + 0.1 * self.model(x) return x
class LayerOutputTrackerHook(ModelHook): def __init__(self): super().__init__() self.outputs = []
def post_forward(self, module, output): self.outputs.append(output) return output
@require_torch_acceleratorclass GroupOffloadTests(unittest.TestCase): in_features = 64 hidden_features = 256 out_features = 64 num_layers = 4
def setUp(self): with torch.no_grad(): self.model = self.get_model() self.input = torch.randn((4, self.in_features)).to(torch_device)
def tearDown(self): super().tearDown()
del self.model del self.input gc.collect() backend_empty_cache(torch_device) backend_reset_peak_memory_stats(torch_device)
def get_model(self): torch.manual_seed(0) return DummyModel( in_features=self.in_features, hidden_features=self.hidden_features, out_features=self.out_features, num_layers=self.num_layers, )
def test_offloading_forward_pass(self): @torch.no_grad() def run_forward(model): gc.collect() backend_empty_cache(torch_device) backend_reset_peak_memory_stats(torch_device) self.assertTrue( all( module._diffusers_hook.get_hook("group_offloading") is not None for module in model.modules() if hasattr(module, "_diffusers_hook") ) ) model.eval() output = model(self.input)[0].cpu() max_memory_allocated = backend_max_memory_allocated(torch_device) return output, max_memory_allocated
self.model.to(torch_device) output_without_group_offloading, mem_baseline = run_forward(self.model) self.model.to("cpu")
model = self.get_model() model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3) output_with_group_offloading1, mem1 = run_forward(model)
model = self.get_model() model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=1) output_with_group_offloading2, mem2 = run_forward(model)
model = self.get_model() model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=1, use_stream=True) output_with_group_offloading3, mem3 = run_forward(model)
model = self.get_model() model.enable_group_offload(torch_device, offload_type="leaf_level") output_with_group_offloading4, mem4 = run_forward(model)
model = self.get_model() model.enable_group_offload(torch_device, offload_type="leaf_level", use_stream=True) output_with_group_offloading5, mem5 = run_forward(model)
# Precision assertions - offloading should not impact the output self.assertTrue(torch.allclose(output_without_group_offloading, output_with_group_offloading1, atol=1e-5)) self.assertTrue(torch.allclose(output_without_group_offloading, output_with_group_offloading2, atol=1e-5)) self.assertTrue(torch.allclose(output_without_group_offloading, output_with_group_offloading3, atol=1e-5)) self.assertTrue(torch.allclose(output_without_group_offloading, output_with_group_offloading4, atol=1e-5)) self.assertTrue(torch.allclose(output_without_group_offloading, output_with_group_offloading5, atol=1e-5))
# Memory assertions - offloading should reduce memory usage self.assertTrue(mem4 <= mem5 < mem2 <= mem3 < mem1 < mem_baseline)
def test_warning_logged_if_group_offloaded_module_moved_to_accelerator(self): if torch.device(torch_device).type not in ["cuda", "xpu"]: return self.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3) logger = get_logger("diffusers.models.modeling_utils") logger.setLevel("INFO") with self.assertLogs(logger, level="WARNING") as cm: self.model.to(torch_device) self.assertIn(f"The module '{self.model.__class__.__name__}' is group offloaded", cm.output[0])
def test_warning_logged_if_group_offloaded_pipe_moved_to_accelerator(self): if torch.device(torch_device).type not in ["cuda", "xpu"]: return pipe = DummyPipeline(self.model) self.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3) logger = get_logger("diffusers.pipelines.pipeline_utils") logger.setLevel("INFO") with self.assertLogs(logger, level="WARNING") as cm: pipe.to(torch_device) self.assertIn(f"The module '{self.model.__class__.__name__}' is group offloaded", cm.output[0])
def test_error_raised_if_streams_used_and_no_accelerator_device(self): torch_accelerator_module = getattr(torch, torch_device, torch.cuda) original_is_available = torch_accelerator_module.is_available torch_accelerator_module.is_available = lambda: False with self.assertRaises(ValueError): self.model.enable_group_offload( onload_device=torch.device(torch_device), offload_type="leaf_level", use_stream=True ) torch_accelerator_module.is_available = original_is_available
def test_error_raised_if_supports_group_offloading_false(self): self.model._supports_group_offloading = False with self.assertRaisesRegex(ValueError, "does not support group offloading"): self.model.enable_group_offload(onload_device=torch.device(torch_device))
def test_error_raised_if_model_offloading_applied_on_group_offloaded_module(self): pipe = DummyPipeline(self.model) pipe.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3) with self.assertRaisesRegex(ValueError, "You are trying to apply model/sequential CPU offloading"): pipe.enable_model_cpu_offload()
def test_error_raised_if_sequential_offloading_applied_on_group_offloaded_module(self): pipe = DummyPipeline(self.model) pipe.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3) with self.assertRaisesRegex(ValueError, "You are trying to apply model/sequential CPU offloading"): pipe.enable_sequential_cpu_offload()
def test_error_raised_if_group_offloading_applied_on_model_offloaded_module(self): pipe = DummyPipeline(self.model) pipe.enable_model_cpu_offload() with self.assertRaisesRegex(ValueError, "Cannot apply group offloading"): pipe.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3)
def test_error_raised_if_group_offloading_applied_on_sequential_offloaded_module(self): pipe = DummyPipeline(self.model) pipe.enable_sequential_cpu_offload() with self.assertRaisesRegex(ValueError, "Cannot apply group offloading"): pipe.model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=3)
def test_block_level_stream_with_invocation_order_different_from_initialization_order(self): if torch.device(torch_device).type not in ["cuda", "xpu"]: return
model = DummyModelWithMultipleBlocks( in_features=self.in_features, hidden_features=self.hidden_features, out_features=self.out_features, num_layers=self.num_layers, num_single_layers=self.num_layers + 1, ) model.enable_group_offload(torch_device, offload_type="block_level", num_blocks_per_group=1, use_stream=True)
context = contextlib.nullcontext() if compare_versions("diffusers", "<=", "0.33.0"): # Will raise a device mismatch RuntimeError mentioning weights are on CPU but input is on device context = self.assertRaisesRegex(RuntimeError, "Expected all tensors to be on the same device")
with context: model(self.input)
@parameterized.expand([("block_level",), ("leaf_level",)]) def test_block_level_offloading_with_parameter_only_module_group(self, offload_type: str): if torch.device(torch_device).type not in ["cuda", "xpu"]: return
def apply_layer_output_tracker_hook(model: DummyModelWithLayerNorm): for name, module in model.named_modules(): registry = HookRegistry.check_if_exists_or_initialize(module) hook = LayerOutputTrackerHook() registry.register_hook(hook, "layer_output_tracker")
model_ref = DummyModelWithLayerNorm(128, 256, 128, 2) model = DummyModelWithLayerNorm(128, 256, 128, 2)
model.load_state_dict(model_ref.state_dict(), strict=True)
model_ref.to(torch_device) model.enable_group_offload(torch_device, offload_type=offload_type, num_blocks_per_group=1, use_stream=True)
apply_layer_output_tracker_hook(model_ref) apply_layer_output_tracker_hook(model)
x = torch.randn(2, 128).to(torch_device)
out_ref = model_ref(x) out = model(x) self.assertTrue(torch.allclose(out_ref, out, atol=1e-5), "Outputs do not match.")
num_repeats = 4 for i in range(num_repeats): out_ref = model_ref(x) out = model(x)
self.assertTrue(torch.allclose(out_ref, out, atol=1e-5), "Outputs do not match after multiple invocations.")
for (ref_name, ref_module), (name, module) in zip(model_ref.named_modules(), model.named_modules()): assert ref_name == name ref_outputs = ( HookRegistry.check_if_exists_or_initialize(ref_module).get_hook("layer_output_tracker").outputs ) outputs = HookRegistry.check_if_exists_or_initialize(module).get_hook("layer_output_tracker").outputs cumulated_absmax = 0.0 for i in range(len(outputs)): diff = ref_outputs[0] - outputs[i] absdiff = diff.abs() absmax = absdiff.max().item() cumulated_absmax += absmax self.assertLess( cumulated_absmax, 1e-5, f"Output differences for {name} exceeded threshold: {cumulated_absmax:.5f}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import gcimport unittest
import torch
from diffusers.hooks import HookRegistry, ModelHookfrom diffusers.training_utils import free_memoryfrom diffusers.utils.logging import get_logger
from ..testing_utils import CaptureLogger, torch_device
logger = get_logger(__name__) # pylint: disable=invalid-name
class DummyBlock(torch.nn.Module): def __init__(self, in_features: int, hidden_features: int, out_features: int) -> None: super().__init__()
self.proj_in = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.proj_out = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.proj_in(x) x = self.activation(x) x = self.proj_out(x) return x
class DummyModel(torch.nn.Module): def __init__(self, in_features: int, hidden_features: int, out_features: int, num_layers: int) -> None: super().__init__()
self.linear_1 = torch.nn.Linear(in_features, hidden_features) self.activation = torch.nn.ReLU() self.blocks = torch.nn.ModuleList( [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] ) self.linear_2 = torch.nn.Linear(hidden_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.linear_1(x) x = self.activation(x) for block in self.blocks: x = block(x) x = self.linear_2(x) return x
class AddHook(ModelHook): def __init__(self, value: int): super().__init__() self.value = value
def pre_forward(self, module: torch.nn.Module, *args, **kwargs): logger.debug("AddHook pre_forward") args = ((x + self.value) if torch.is_tensor(x) else x for x in args) return args, kwargs
def post_forward(self, module, output): logger.debug("AddHook post_forward") return output
class MultiplyHook(ModelHook): def __init__(self, value: int): super().__init__() self.value = value
def pre_forward(self, module, *args, **kwargs): logger.debug("MultiplyHook pre_forward") args = ((x * self.value) if torch.is_tensor(x) else x for x in args) return args, kwargs
def post_forward(self, module, output): logger.debug("MultiplyHook post_forward") return output
def __repr__(self): return f"MultiplyHook(value={self.value})"
class StatefulAddHook(ModelHook): _is_stateful = True
def __init__(self, value: int): super().__init__() self.value = value self.increment = 0
def pre_forward(self, module, *args, **kwargs): logger.debug("StatefulAddHook pre_forward") add_value = self.value + self.increment self.increment += 1 args = ((x + add_value) if torch.is_tensor(x) else x for x in args) return args, kwargs
def reset_state(self, module): self.increment = 0
class SkipLayerHook(ModelHook): def __init__(self, skip_layer: bool): super().__init__() self.skip_layer = skip_layer
def pre_forward(self, module, *args, **kwargs): logger.debug("SkipLayerHook pre_forward") return args, kwargs
def new_forward(self, module, *args, **kwargs): logger.debug("SkipLayerHook new_forward") if self.skip_layer: return args[0] return self.fn_ref.original_forward(*args, **kwargs)
def post_forward(self, module, output): logger.debug("SkipLayerHook post_forward") return output
class HookTests(unittest.TestCase): in_features = 4 hidden_features = 8 out_features = 4 num_layers = 2
def setUp(self): params = self.get_module_parameters() self.model = DummyModel(**params) self.model.to(torch_device)
def tearDown(self): super().tearDown()
del self.model gc.collect() free_memory()
def get_module_parameters(self): return { "in_features": self.in_features, "hidden_features": self.hidden_features, "out_features": self.out_features, "num_layers": self.num_layers, }
def get_generator(self): return torch.manual_seed(0)
def test_hook_registry(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(AddHook(1), "add_hook") registry.register_hook(MultiplyHook(2), "multiply_hook")
registry_repr = repr(registry) expected_repr = "HookRegistry(\n (0) add_hook - AddHook\n (1) multiply_hook - MultiplyHook(value=2)\n)"
self.assertEqual(len(registry.hooks), 2) self.assertEqual(registry._hook_order, ["add_hook", "multiply_hook"]) self.assertEqual(registry_repr, expected_repr)
registry.remove_hook("add_hook")
self.assertEqual(len(registry.hooks), 1) self.assertEqual(registry._hook_order, ["multiply_hook"])
def test_stateful_hook(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(StatefulAddHook(1), "stateful_add_hook")
self.assertEqual(registry.hooks["stateful_add_hook"].increment, 0)
input = torch.randn(1, 4, device=torch_device, generator=self.get_generator()) num_repeats = 3
for i in range(num_repeats): result = self.model(input) if i == 0: output1 = result
self.assertEqual(registry.get_hook("stateful_add_hook").increment, num_repeats)
registry.reset_stateful_hooks() output2 = self.model(input)
self.assertEqual(registry.get_hook("stateful_add_hook").increment, 1) self.assertTrue(torch.allclose(output1, output2))
def test_inference(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(AddHook(1), "add_hook") registry.register_hook(MultiplyHook(2), "multiply_hook")
input = torch.randn(1, 4, device=torch_device, generator=self.get_generator()) output1 = self.model(input).mean().detach().cpu().item()
registry.remove_hook("multiply_hook") new_input = input * 2 output2 = self.model(new_input).mean().detach().cpu().item()
registry.remove_hook("add_hook") new_input = input * 2 + 1 output3 = self.model(new_input).mean().detach().cpu().item()
self.assertAlmostEqual(output1, output2, places=5) self.assertAlmostEqual(output1, output3, places=5) self.assertAlmostEqual(output2, output3, places=5)
def test_skip_layer_hook(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(SkipLayerHook(skip_layer=True), "skip_layer_hook")
input = torch.zeros(1, 4, device=torch_device) output = self.model(input).mean().detach().cpu().item() self.assertEqual(output, 0.0)
registry.remove_hook("skip_layer_hook") registry.register_hook(SkipLayerHook(skip_layer=False), "skip_layer_hook") output = self.model(input).mean().detach().cpu().item() self.assertNotEqual(output, 0.0)
def test_skip_layer_internal_block(self): registry = HookRegistry.check_if_exists_or_initialize(self.model.linear_1) input = torch.zeros(1, 4, device=torch_device)
registry.register_hook(SkipLayerHook(skip_layer=True), "skip_layer_hook") with self.assertRaises(RuntimeError) as cm: self.model(input).mean().detach().cpu().item() self.assertIn("mat1 and mat2 shapes cannot be multiplied", str(cm.exception))
registry.remove_hook("skip_layer_hook") output = self.model(input).mean().detach().cpu().item() self.assertNotEqual(output, 0.0)
registry = HookRegistry.check_if_exists_or_initialize(self.model.blocks[1]) registry.register_hook(SkipLayerHook(skip_layer=True), "skip_layer_hook") output = self.model(input).mean().detach().cpu().item() self.assertNotEqual(output, 0.0)
def test_invocation_order_stateful_first(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(StatefulAddHook(1), "add_hook") registry.register_hook(AddHook(2), "add_hook_2") registry.register_hook(MultiplyHook(3), "multiply_hook")
input = torch.randn(1, 4, device=torch_device, generator=self.get_generator())
logger = get_logger(__name__) logger.setLevel("DEBUG")
with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ( "MultiplyHook pre_forward\n" "AddHook pre_forward\n" "StatefulAddHook pre_forward\n" "AddHook post_forward\n" "MultiplyHook post_forward\n" ) .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
registry.remove_hook("add_hook") with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ("MultiplyHook pre_forward\nAddHook pre_forward\nAddHook post_forward\nMultiplyHook post_forward\n") .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
def test_invocation_order_stateful_middle(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(AddHook(2), "add_hook") registry.register_hook(StatefulAddHook(1), "add_hook_2") registry.register_hook(MultiplyHook(3), "multiply_hook")
input = torch.randn(1, 4, device=torch_device, generator=self.get_generator())
logger = get_logger(__name__) logger.setLevel("DEBUG")
with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ( "MultiplyHook pre_forward\n" "StatefulAddHook pre_forward\n" "AddHook pre_forward\n" "AddHook post_forward\n" "MultiplyHook post_forward\n" ) .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
registry.remove_hook("add_hook") with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ("MultiplyHook pre_forward\nStatefulAddHook pre_forward\nMultiplyHook post_forward\n") .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
registry.remove_hook("add_hook_2") with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ("MultiplyHook pre_forward\nMultiplyHook post_forward\n").replace(" ", "").replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
def test_invocation_order_stateful_last(self): registry = HookRegistry.check_if_exists_or_initialize(self.model) registry.register_hook(AddHook(1), "add_hook") registry.register_hook(MultiplyHook(2), "multiply_hook") registry.register_hook(StatefulAddHook(3), "add_hook_2")
input = torch.randn(1, 4, device=torch_device, generator=self.get_generator())
logger = get_logger(__name__) logger.setLevel("DEBUG")
with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ( "StatefulAddHook pre_forward\n" "MultiplyHook pre_forward\n" "AddHook pre_forward\n" "AddHook post_forward\n" "MultiplyHook post_forward\n" ) .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)
registry.remove_hook("add_hook") with CaptureLogger(logger) as cap_logger: self.model(input) output = cap_logger.out.replace(" ", "").replace("\n", "") expected_invocation_order_log = ( ("StatefulAddHook pre_forward\nMultiplyHook pre_forward\nMultiplyHook post_forward\n") .replace(" ", "") .replace("\n", "") ) self.assertEqual(output, expected_invocation_order_log)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import sysimport unittest
import torchfrom transformers import AutoTokenizer, UMT5EncoderModel
from diffusers import ( AuraFlowPipeline, AuraFlowTransformer2DModel, FlowMatchEulerDiscreteScheduler,)
from ..testing_utils import ( floats_tensor, is_peft_available, require_peft_backend,)
if is_peft_available(): pass
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backendclass AuraFlowLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = AuraFlowPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "sample_size": 64, "patch_size": 1, "in_channels": 4, "num_mmdit_layers": 1, "num_single_dit_layers": 1, "attention_head_dim": 16, "num_attention_heads": 2, "joint_attention_dim": 32, "caption_projection_dim": 32, "pos_embed_max_size": 64, } transformer_cls = AuraFlowTransformer2DModel vae_kwargs = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "block_out_channels": (4,), "layers_per_block": 1, "latent_channels": 4, "norm_num_groups": 1, "use_quant_conv": False, "use_post_quant_conv": False, "shift_factor": 0.0609, "scaling_factor": 1.5035, } tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = UMT5EncoderModel, "hf-internal-testing/tiny-random-umt5" text_encoder_target_modules = ["q", "k", "v", "o"] denoiser_target_modules = ["to_q", "to_k", "to_v", "to_out.0", "linear_1"]
@property def output_shape(self): return (1, 8, 8, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 10 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "A painting of a squirrel eating a burger", "num_inference_steps": 4, "guidance_scale": 0.0, "height": 8, "width": 8, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
@unittest.skip("Not supported in AuraFlow.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in AuraFlow.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in AuraFlow.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in AuraFlow.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in AuraFlow.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in AuraFlow.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in AuraFlow.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in AuraFlow.") def test_simple_inference_with_text_lora_save_load(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport unittest
import torchfrom parameterized import parameterizedfrom transformers import AutoTokenizer, T5EncoderModel
from diffusers import ( AutoencoderKLCogVideoX, CogVideoXDDIMScheduler, CogVideoXDPMScheduler, CogVideoXPipeline, CogVideoXTransformer3DModel,)
from ..testing_utils import ( floats_tensor, require_peft_backend, require_torch_accelerator,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backendclass CogVideoXLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = CogVideoXPipeline scheduler_cls = CogVideoXDPMScheduler scheduler_kwargs = {"timestep_spacing": "trailing"} scheduler_classes = [CogVideoXDDIMScheduler, CogVideoXDPMScheduler]
transformer_kwargs = { "num_attention_heads": 4, "attention_head_dim": 8, "in_channels": 4, "out_channels": 4, "time_embed_dim": 2, "text_embed_dim": 32, "num_layers": 1, "sample_width": 16, "sample_height": 16, "sample_frames": 9, "patch_size": 2, "temporal_compression_ratio": 4, "max_text_seq_length": 16, } transformer_cls = CogVideoXTransformer3DModel vae_kwargs = { "in_channels": 3, "out_channels": 3, "down_block_types": ( "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", ), "up_block_types": ( "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", ), "block_out_channels": (8, 8, 8, 8), "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 2, "temporal_compression_ratio": 4, } vae_cls = AutoencoderKLCogVideoX tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
text_encoder_target_modules = ["q", "k", "v", "o"]
@property def output_shape(self): return (1, 9, 16, 16, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 num_frames = 9 num_latent_frames = 3 # (num_frames - 1) // temporal_compression_ratio + 1 sizes = (2, 2)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "dance monkey", "num_frames": num_frames, "num_inference_steps": 4, "guidance_scale": 6.0, # Cannot reduce because convolution kernel becomes bigger than sample "height": 16, "width": 16, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
def test_lora_scale_kwargs_match_fusion(self): super().test_lora_scale_kwargs_match_fusion(expected_atol=9e-3, expected_rtol=9e-3)
@parameterized.expand([("block_level", True), ("leaf_level", False)]) @require_torch_accelerator def test_group_offloading_inference_denoiser(self, offload_type, use_stream): # TODO: We don't run the (leaf_level, True) test here that is enabled for other models. # The reason for this can be found here: https://github.com/huggingface/diffusers/pull/11804#issuecomment-3013325338 super()._test_group_offloading_inference_denoiser(offload_type, use_stream)
@unittest.skip("Not supported in CogVideoX.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in CogVideoX.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in CogVideoX.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogVideoX.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogVideoX.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogVideoX.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogVideoX.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogVideoX.") def test_simple_inference_with_text_lora_save_load(self): pass
@unittest.skip("Not supported in CogVideoX.") def test_simple_inference_with_text_denoiser_multi_adapter_block_lora(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport tempfileimport unittest
import numpy as npimport torchfrom parameterized import parameterizedfrom transformers import AutoTokenizer, GlmModel
from diffusers import AutoencoderKL, CogView4Pipeline, CogView4Transformer2DModel, FlowMatchEulerDiscreteScheduler
from ..testing_utils import ( floats_tensor, require_peft_backend, require_torch_accelerator, skip_mps, torch_device,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
class TokenizerWrapper: @staticmethod def from_pretrained(*args, **kwargs): return AutoTokenizer.from_pretrained( "hf-internal-testing/tiny-random-cogview4", subfolder="tokenizer", trust_remote_code=True )
@require_peft_backend@skip_mpsclass CogView4LoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = CogView4Pipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "patch_size": 2, "in_channels": 4, "num_layers": 2, "attention_head_dim": 4, "num_attention_heads": 4, "out_channels": 4, "text_embed_dim": 32, "time_embed_dim": 8, "condition_dim": 4, } transformer_cls = CogView4Transformer2DModel vae_kwargs = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, "sample_size": 128, } vae_cls = AutoencoderKL tokenizer_cls, tokenizer_id, tokenizer_subfolder = ( TokenizerWrapper, "hf-internal-testing/tiny-random-cogview4", "tokenizer", ) text_encoder_cls, text_encoder_id, text_encoder_subfolder = ( GlmModel, "hf-internal-testing/tiny-random-cogview4", "text_encoder", )
@property def output_shape(self): return (1, 32, 32, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 sizes = (4, 4)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "", "num_inference_steps": 1, "guidance_scale": 6.0, "height": 32, "width": 32, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
def test_simple_inference_save_pretrained(self): """ Tests a simple usecase where users could use saving utilities for LoRA through save_pretrained """ for scheduler_cls in self.scheduler_classes: components, _, _ = self.get_dummy_components(scheduler_cls) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
output_no_lora = pipe(**inputs, generator=torch.manual_seed(0))[0] self.assertTrue(output_no_lora.shape == self.output_shape)
images_lora = pipe(**inputs, generator=torch.manual_seed(0))[0]
with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(tmpdirname)
pipe_from_pretrained = self.pipeline_class.from_pretrained(tmpdirname) pipe_from_pretrained.to(torch_device)
images_lora_save_pretrained = pipe_from_pretrained(**inputs, generator=torch.manual_seed(0))[0]
self.assertTrue( np.allclose(images_lora, images_lora_save_pretrained, atol=1e-3, rtol=1e-3), "Loading from saved checkpoints should give same results.", )
@parameterized.expand([("block_level", True), ("leaf_level", False)]) @require_torch_accelerator def test_group_offloading_inference_denoiser(self, offload_type, use_stream): # TODO: We don't run the (leaf_level, True) test here that is enabled for other models. # The reason for this can be found here: https://github.com/huggingface/diffusers/pull/11804#issuecomment-3013325338 super()._test_group_offloading_inference_denoiser(offload_type, use_stream)
@unittest.skip("Not supported in CogView4.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in CogView4.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in CogView4.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogView4.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogView4.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogView4.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogView4.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in CogView4.") def test_simple_inference_with_text_lora_save_load(self): pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import copyimport gcimport osimport sysimport tempfileimport unittest
import numpy as npimport safetensors.torchimport torchfrom parameterized import parameterizedfrom PIL import Imagefrom transformers import AutoTokenizer, CLIPTextModel, CLIPTokenizer, T5EncoderModel
from diffusers import FlowMatchEulerDiscreteScheduler, FluxControlPipeline, FluxPipeline, FluxTransformer2DModelfrom diffusers.utils import load_image, logging
from ..testing_utils import ( CaptureLogger, backend_empty_cache, floats_tensor, is_peft_available, nightly, numpy_cosine_similarity_distance, require_big_accelerator, require_peft_backend, require_torch_accelerator, slow, torch_device,)
if is_peft_available(): from peft.utils import get_peft_model_state_dict
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests, check_if_lora_correctly_set # noqa: E402
@require_peft_backendclass FluxLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = FluxPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler() scheduler_kwargs = {} scheduler_classes = [FlowMatchEulerDiscreteScheduler] transformer_kwargs = { "patch_size": 1, "in_channels": 4, "num_layers": 1, "num_single_layers": 1, "attention_head_dim": 16, "num_attention_heads": 2, "joint_attention_dim": 32, "pooled_projection_dim": 32, "axes_dims_rope": [4, 4, 8], } transformer_cls = FluxTransformer2DModel vae_kwargs = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "block_out_channels": (4,), "layers_per_block": 1, "latent_channels": 1, "norm_num_groups": 1, "use_quant_conv": False, "use_post_quant_conv": False, "shift_factor": 0.0609, "scaling_factor": 1.5035, } has_two_text_encoders = True tokenizer_cls, tokenizer_id = CLIPTokenizer, "peft-internal-testing/tiny-clip-text-2" tokenizer_2_cls, tokenizer_2_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = CLIPTextModel, "peft-internal-testing/tiny-clip-text-2" text_encoder_2_cls, text_encoder_2_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
@property def output_shape(self): return (1, 8, 8, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 10 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "A painting of a squirrel eating a burger", "num_inference_steps": 4, "guidance_scale": 0.0, "height": 8, "width": 8, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_with_alpha_in_state_dict(self): components, _, denoiser_lora_config = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
output_no_lora = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertTrue(output_no_lora.shape == self.output_shape)
pipe.transformer.add_adapter(denoiser_lora_config) self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in transformer")
images_lora = pipe(**inputs, generator=torch.manual_seed(0)).images
with tempfile.TemporaryDirectory() as tmpdirname: denoiser_state_dict = get_peft_model_state_dict(pipe.transformer) self.pipeline_class.save_lora_weights(tmpdirname, transformer_lora_layers=denoiser_state_dict)
self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"))) pipe.unload_lora_weights() pipe.load_lora_weights(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"))
# modify the state dict to have alpha values following # https://huggingface.co/TheLastBen/Jon_Snow_Flux_LoRA/blob/main/jon_snow.safetensors state_dict_with_alpha = safetensors.torch.load_file( os.path.join(tmpdirname, "pytorch_lora_weights.safetensors") ) alpha_dict = {} for k, v in state_dict_with_alpha.items(): # only do for `transformer` and for the k projections -- should be enough to test. if "transformer" in k and "to_k" in k and "lora_A" in k: alpha_dict[f"{k}.alpha"] = float(torch.randint(10, 100, size=())) state_dict_with_alpha.update(alpha_dict)
images_lora_from_pretrained = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
pipe.unload_lora_weights() pipe.load_lora_weights(state_dict_with_alpha) images_lora_with_alpha = pipe(**inputs, generator=torch.manual_seed(0)).images
self.assertTrue( np.allclose(images_lora, images_lora_from_pretrained, atol=1e-3, rtol=1e-3), "Loading from saved checkpoints should give same results.", ) self.assertFalse(np.allclose(images_lora_with_alpha, images_lora, atol=1e-3, rtol=1e-3))
def test_lora_expansion_works_for_absent_keys(self): components, _, denoiser_lora_config = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
output_no_lora = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertTrue(output_no_lora.shape == self.output_shape)
# Modify the config to have a layer which won't be present in the second LoRA we will load. modified_denoiser_lora_config = copy.deepcopy(denoiser_lora_config) modified_denoiser_lora_config.target_modules.add("x_embedder")
pipe.transformer.add_adapter(modified_denoiser_lora_config) self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in transformer")
images_lora = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertFalse( np.allclose(images_lora, output_no_lora, atol=1e-3, rtol=1e-3), "LoRA should lead to different results.", )
with tempfile.TemporaryDirectory() as tmpdirname: denoiser_state_dict = get_peft_model_state_dict(pipe.transformer) self.pipeline_class.save_lora_weights(tmpdirname, transformer_lora_layers=denoiser_state_dict)
self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"))) pipe.unload_lora_weights() pipe.load_lora_weights(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"), adapter_name="one")
# Modify the state dict to exclude "x_embedder" related LoRA params. lora_state_dict = safetensors.torch.load_file(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors")) lora_state_dict_without_xembedder = {k: v for k, v in lora_state_dict.items() if "x_embedder" not in k}
pipe.load_lora_weights(lora_state_dict_without_xembedder, adapter_name="two") pipe.set_adapters(["one", "two"]) self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in transformer") images_lora_with_absent_keys = pipe(**inputs, generator=torch.manual_seed(0)).images
self.assertFalse( np.allclose(images_lora, images_lora_with_absent_keys, atol=1e-3, rtol=1e-3), "Different LoRAs should lead to different results.", ) self.assertFalse( np.allclose(output_no_lora, images_lora_with_absent_keys, atol=1e-3, rtol=1e-3), "LoRA should lead to different results.", )
def test_lora_expansion_works_for_extra_keys(self): components, _, denoiser_lora_config = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
output_no_lora = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertTrue(output_no_lora.shape == self.output_shape)
# Modify the config to have a layer which won't be present in the first LoRA we will load. modified_denoiser_lora_config = copy.deepcopy(denoiser_lora_config) modified_denoiser_lora_config.target_modules.add("x_embedder")
pipe.transformer.add_adapter(modified_denoiser_lora_config) self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in transformer")
images_lora = pipe(**inputs, generator=torch.manual_seed(0)).images self.assertFalse( np.allclose(images_lora, output_no_lora, atol=1e-3, rtol=1e-3), "LoRA should lead to different results.", )
with tempfile.TemporaryDirectory() as tmpdirname: denoiser_state_dict = get_peft_model_state_dict(pipe.transformer) self.pipeline_class.save_lora_weights(tmpdirname, transformer_lora_layers=denoiser_state_dict)
self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"))) pipe.unload_lora_weights() # Modify the state dict to exclude "x_embedder" related LoRA params. lora_state_dict = safetensors.torch.load_file(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors")) lora_state_dict_without_xembedder = {k: v for k, v in lora_state_dict.items() if "x_embedder" not in k} pipe.load_lora_weights(lora_state_dict_without_xembedder, adapter_name="one")
# Load state dict with `x_embedder`. pipe.load_lora_weights(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"), adapter_name="two")
pipe.set_adapters(["one", "two"]) self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in transformer") images_lora_with_extra_keys = pipe(**inputs, generator=torch.manual_seed(0)).images
self.assertFalse( np.allclose(images_lora, images_lora_with_extra_keys, atol=1e-3, rtol=1e-3), "Different LoRAs should lead to different results.", ) self.assertFalse( np.allclose(output_no_lora, images_lora_with_extra_keys, atol=1e-3, rtol=1e-3), "LoRA should lead to different results.", )
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Flux.") def test_modify_padding_mode(self): pass
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_multi_adapter_block_lora(self): pass
class FluxControlLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = FluxControlPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler() scheduler_kwargs = {} scheduler_classes = [FlowMatchEulerDiscreteScheduler] transformer_kwargs = { "patch_size": 1, "in_channels": 8, "out_channels": 4, "num_layers": 1, "num_single_layers": 1, "attention_head_dim": 16, "num_attention_heads": 2, "joint_attention_dim": 32, "pooled_projection_dim": 32, "axes_dims_rope": [4, 4, 8], } transformer_cls = FluxTransformer2DModel vae_kwargs = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "block_out_channels": (4,), "layers_per_block": 1, "latent_channels": 1, "norm_num_groups": 1, "use_quant_conv": False, "use_post_quant_conv": False, "shift_factor": 0.0609, "scaling_factor": 1.5035, } has_two_text_encoders = True tokenizer_cls, tokenizer_id = CLIPTokenizer, "peft-internal-testing/tiny-clip-text-2" tokenizer_2_cls, tokenizer_2_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = CLIPTextModel, "peft-internal-testing/tiny-clip-text-2" text_encoder_2_cls, text_encoder_2_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
@property def output_shape(self): return (1, 8, 8, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 10 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "A painting of a squirrel eating a burger", "control_image": Image.fromarray(np.random.randint(0, 255, size=(32, 32, 3), dtype="uint8")), "num_inference_steps": 4, "guidance_scale": 0.0, "height": 8, "width": 8, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_with_norm_in_state_dict(self): components, _, denoiser_lora_config = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
_, _, inputs = self.get_dummy_inputs(with_generator=False)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.INFO)
original_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
for norm_layer in ["norm_q", "norm_k", "norm_added_q", "norm_added_k"]: norm_state_dict = {} for name, module in pipe.transformer.named_modules(): if norm_layer not in name or not hasattr(module, "weight") or module.weight is None: continue norm_state_dict[f"transformer.{name}.weight"] = torch.randn( module.weight.shape, device=module.weight.device, dtype=module.weight.dtype )
with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(norm_state_dict) lora_load_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertTrue( "The provided state dict contains normalization layers in addition to LoRA layers" in cap_logger.out ) self.assertTrue(len(pipe.transformer._transformer_norm_layers) > 0)
pipe.unload_lora_weights() lora_unload_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertTrue(pipe.transformer._transformer_norm_layers is None) self.assertTrue(np.allclose(original_output, lora_unload_output, atol=1e-5, rtol=1e-5)) self.assertFalse( np.allclose(original_output, lora_load_output, atol=1e-6, rtol=1e-6), f"{norm_layer} is tested" )
with CaptureLogger(logger) as cap_logger: for key in list(norm_state_dict.keys()): norm_state_dict[key.replace("norm", "norm_k_something_random")] = norm_state_dict.pop(key) pipe.load_lora_weights(norm_state_dict)
self.assertTrue( "Unsupported keys found in state dict when trying to load normalization layers" in cap_logger.out )
def test_lora_parameter_expanded_shapes(self): components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
_, _, inputs = self.get_dummy_inputs(with_generator=False) original_out = pipe(**inputs, generator=torch.manual_seed(0))[0]
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
# Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) self.assertTrue( transformer.config.in_channels == num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {transformer.config.in_channels=}", )
original_transformer_state_dict = pipe.transformer.state_dict() x_embedder_weight = original_transformer_state_dict.pop("x_embedder.weight") incompatible_keys = transformer.load_state_dict(original_transformer_state_dict, strict=False) self.assertTrue( "x_embedder.weight" in incompatible_keys.missing_keys, "Could not find x_embedder.weight in the missing keys.", ) transformer.x_embedder.weight.data.copy_(x_embedder_weight[..., :num_channels_without_control]) pipe.transformer = transformer
out_features, in_features = pipe.transformer.x_embedder.weight.shape rank = 4
dummy_lora_A = torch.nn.Linear(2 * in_features, rank, bias=False) dummy_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": dummy_lora_A.weight, "transformer.x_embedder.lora_B.weight": dummy_lora_B.weight, } with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(lora_state_dict, "adapter-1")
self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
lora_out = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(original_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == 2 * in_features) self.assertTrue(pipe.transformer.config.in_channels == 2 * in_features) self.assertTrue(cap_logger.out.startswith("Expanding the nn.Linear input/output features for module"))
# Testing opposite direction where the LoRA params are zero-padded. components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) dummy_lora_A = torch.nn.Linear(1, rank, bias=False) dummy_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": dummy_lora_A.weight, "transformer.x_embedder.lora_B.weight": dummy_lora_B.weight, } with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(lora_state_dict, "adapter-1")
self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
lora_out = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(original_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == 2 * in_features) self.assertTrue(pipe.transformer.config.in_channels == 2 * in_features) self.assertTrue("The following LoRA modules were zero padded to match the state dict of" in cap_logger.out)
def test_normal_lora_with_expanded_lora_raises_error(self): # Test the following situation. Load a regular LoRA (such as the ones trained on Flux.1-Dev). And then # load shape expanded LoRA (such as Control LoRA). components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler)
# Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) components["transformer"] = transformer
pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
out_features, in_features = pipe.transformer.x_embedder.weight.shape rank = 4
shape_expander_lora_A = torch.nn.Linear(2 * in_features, rank, bias=False) shape_expander_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": shape_expander_lora_A.weight, "transformer.x_embedder.lora_B.weight": shape_expander_lora_B.weight, } with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(lora_state_dict, "adapter-1")
self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser") self.assertTrue(pipe.get_active_adapters() == ["adapter-1"]) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == 2 * in_features) self.assertTrue(pipe.transformer.config.in_channels == 2 * in_features) self.assertTrue(cap_logger.out.startswith("Expanding the nn.Linear input/output features for module"))
_, _, inputs = self.get_dummy_inputs(with_generator=False) lora_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
normal_lora_A = torch.nn.Linear(in_features, rank, bias=False) normal_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": normal_lora_A.weight, "transformer.x_embedder.lora_B.weight": normal_lora_B.weight, }
with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(lora_state_dict, "adapter-2")
self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser") self.assertTrue("The following LoRA modules were zero padded to match the state dict of" in cap_logger.out) self.assertTrue(pipe.get_active_adapters() == ["adapter-2"])
lora_output_2 = pipe(**inputs, generator=torch.manual_seed(0))[0] self.assertFalse(np.allclose(lora_output, lora_output_2, atol=1e-3, rtol=1e-3))
# Test the opposite case where the first lora has the correct input features and the second lora has expanded input features. # This should raise a runtime error on input shapes being incompatible. components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) # Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) components["transformer"] = transformer
pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
out_features, in_features = pipe.transformer.x_embedder.weight.shape rank = 4
lora_state_dict = { "transformer.x_embedder.lora_A.weight": normal_lora_A.weight, "transformer.x_embedder.lora_B.weight": normal_lora_B.weight, } pipe.load_lora_weights(lora_state_dict, "adapter-1")
self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser") self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == in_features) self.assertTrue(pipe.transformer.config.in_channels == in_features)
lora_state_dict = { "transformer.x_embedder.lora_A.weight": shape_expander_lora_A.weight, "transformer.x_embedder.lora_B.weight": shape_expander_lora_B.weight, }
# We should check for input shapes being incompatible here. But because above mentioned issue is # not a supported use case, and because of the PEFT renaming, we will currently have a shape # mismatch error. self.assertRaisesRegex( RuntimeError, "size mismatch for x_embedder.lora_A.adapter-2.weight", pipe.load_lora_weights, lora_state_dict, "adapter-2", )
def test_fuse_expanded_lora_with_regular_lora(self): # This test checks if it works when a lora with expanded shapes (like control loras) but # another lora with correct shapes is loaded. The opposite direction isn't supported and is # tested with it. components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler)
# Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) components["transformer"] = transformer
pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
out_features, in_features = pipe.transformer.x_embedder.weight.shape rank = 4
shape_expander_lora_A = torch.nn.Linear(2 * in_features, rank, bias=False) shape_expander_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": shape_expander_lora_A.weight, "transformer.x_embedder.lora_B.weight": shape_expander_lora_B.weight, } pipe.load_lora_weights(lora_state_dict, "adapter-1") self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
_, _, inputs = self.get_dummy_inputs(with_generator=False) lora_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
normal_lora_A = torch.nn.Linear(in_features, rank, bias=False) normal_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": normal_lora_A.weight, "transformer.x_embedder.lora_B.weight": normal_lora_B.weight, }
pipe.load_lora_weights(lora_state_dict, "adapter-2") self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
lora_output_2 = pipe(**inputs, generator=torch.manual_seed(0))[0]
pipe.set_adapters(["adapter-1", "adapter-2"], [1.0, 1.0]) lora_output_3 = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(lora_output, lora_output_2, atol=1e-3, rtol=1e-3)) self.assertFalse(np.allclose(lora_output, lora_output_3, atol=1e-3, rtol=1e-3)) self.assertFalse(np.allclose(lora_output_2, lora_output_3, atol=1e-3, rtol=1e-3))
pipe.fuse_lora(lora_scale=1.0, adapter_names=["adapter-1", "adapter-2"]) lora_output_4 = pipe(**inputs, generator=torch.manual_seed(0))[0] self.assertTrue(np.allclose(lora_output_3, lora_output_4, atol=1e-3, rtol=1e-3))
def test_load_regular_lora(self): # This test checks if a regular lora (think of one trained on Flux.1 Dev for example) can be loaded # into the transformer with more input channels than Flux.1 Dev, for example. Some examples of those # transformers include Flux Fill, Flux Control, etc. components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
original_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
out_features, in_features = pipe.transformer.x_embedder.weight.shape rank = 4 in_features = in_features // 2 # to mimic the Flux.1-Dev LoRA. normal_lora_A = torch.nn.Linear(in_features, rank, bias=False) normal_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": normal_lora_A.weight, "transformer.x_embedder.lora_B.weight": normal_lora_B.weight, }
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.INFO) with CaptureLogger(logger) as cap_logger: pipe.load_lora_weights(lora_state_dict, "adapter-1") self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
lora_output = pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertTrue("The following LoRA modules were zero padded to match the state dict of" in cap_logger.out) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == in_features * 2) self.assertFalse(np.allclose(original_output, lora_output, atol=1e-3, rtol=1e-3))
def test_lora_unload_with_parameter_expanded_shapes(self): components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
# Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) self.assertTrue( transformer.config.in_channels == num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {transformer.config.in_channels=}", )
# This should be initialized with a Flux pipeline variant that doesn't accept `control_image`. components["transformer"] = transformer pipe = FluxPipeline(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
_, _, inputs = self.get_dummy_inputs(with_generator=False) control_image = inputs.pop("control_image") original_out = pipe(**inputs, generator=torch.manual_seed(0))[0]
control_pipe = self.pipeline_class(**components) out_features, in_features = control_pipe.transformer.x_embedder.weight.shape rank = 4
dummy_lora_A = torch.nn.Linear(2 * in_features, rank, bias=False) dummy_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": dummy_lora_A.weight, "transformer.x_embedder.lora_B.weight": dummy_lora_B.weight, } with CaptureLogger(logger) as cap_logger: control_pipe.load_lora_weights(lora_state_dict, "adapter-1") self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
inputs["control_image"] = control_image lora_out = control_pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(original_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == 2 * in_features) self.assertTrue(pipe.transformer.config.in_channels == 2 * in_features) self.assertTrue(cap_logger.out.startswith("Expanding the nn.Linear input/output features for module"))
control_pipe.unload_lora_weights(reset_to_overwritten_params=True) self.assertTrue( control_pipe.transformer.config.in_channels == num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {control_pipe.transformer.config.in_channels=}", ) loaded_pipe = FluxPipeline.from_pipe(control_pipe) self.assertTrue( loaded_pipe.transformer.config.in_channels == num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {loaded_pipe.transformer.config.in_channels=}", ) inputs.pop("control_image") unloaded_lora_out = loaded_pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(unloaded_lora_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(np.allclose(unloaded_lora_out, original_out, atol=1e-4, rtol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == in_features) self.assertTrue(pipe.transformer.config.in_channels == in_features)
def test_lora_unload_with_parameter_expanded_shapes_and_no_reset(self): components, _, _ = self.get_dummy_components(FlowMatchEulerDiscreteScheduler)
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(logging.DEBUG)
# Change the transformer config to mimic a real use case. num_channels_without_control = 4 transformer = FluxTransformer2DModel.from_config( components["transformer"].config, in_channels=num_channels_without_control ).to(torch_device) self.assertTrue( transformer.config.in_channels == num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {transformer.config.in_channels=}", )
# This should be initialized with a Flux pipeline variant that doesn't accept `control_image`. components["transformer"] = transformer pipe = FluxPipeline(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
_, _, inputs = self.get_dummy_inputs(with_generator=False) control_image = inputs.pop("control_image") original_out = pipe(**inputs, generator=torch.manual_seed(0))[0]
control_pipe = self.pipeline_class(**components) out_features, in_features = control_pipe.transformer.x_embedder.weight.shape rank = 4
dummy_lora_A = torch.nn.Linear(2 * in_features, rank, bias=False) dummy_lora_B = torch.nn.Linear(rank, out_features, bias=False) lora_state_dict = { "transformer.x_embedder.lora_A.weight": dummy_lora_A.weight, "transformer.x_embedder.lora_B.weight": dummy_lora_B.weight, } with CaptureLogger(logger) as cap_logger: control_pipe.load_lora_weights(lora_state_dict, "adapter-1") self.assertTrue(check_if_lora_correctly_set(pipe.transformer), "Lora not correctly set in denoiser")
inputs["control_image"] = control_image lora_out = control_pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(original_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == 2 * in_features) self.assertTrue(pipe.transformer.config.in_channels == 2 * in_features) self.assertTrue(cap_logger.out.startswith("Expanding the nn.Linear input/output features for module"))
control_pipe.unload_lora_weights(reset_to_overwritten_params=False) self.assertTrue( control_pipe.transformer.config.in_channels == 2 * num_channels_without_control, f"Expected {num_channels_without_control} channels in the modified transformer but has {control_pipe.transformer.config.in_channels=}", ) no_lora_out = control_pipe(**inputs, generator=torch.manual_seed(0))[0]
self.assertFalse(np.allclose(no_lora_out, lora_out, rtol=1e-4, atol=1e-4)) self.assertTrue(pipe.transformer.x_embedder.weight.data.shape[1] == in_features * 2) self.assertTrue(pipe.transformer.config.in_channels == in_features * 2)
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Flux.") def test_modify_padding_mode(self): pass
@unittest.skip("Not supported in Flux.") def test_simple_inference_with_text_denoiser_multi_adapter_block_lora(self): pass
@slow@nightly@require_torch_accelerator@require_peft_backend@require_big_acceleratorclass FluxLoRAIntegrationTests(unittest.TestCase): """internal note: The integration slices were obtained on audace.
torch: 2.6.0.dev20241006+cu124 with CUDA 12.5. Need the same setup for the assertions to pass. """
num_inference_steps = 10 seed = 0
def setUp(self): super().setUp()
gc.collect() backend_empty_cache(torch_device)
self.pipeline = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
def tearDown(self): super().tearDown()
del self.pipeline gc.collect() backend_empty_cache(torch_device)
def test_flux_the_last_ben(self): self.pipeline.load_lora_weights("TheLastBen/Jon_Snow_Flux_LoRA", weight_name="jon_snow.safetensors") self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() # Instead of calling `enable_model_cpu_offload()`, we do a accelerator placement here because the CI # run supports it. We have about 34GB RAM in the CI runner which kills the test when run with # `enable_model_cpu_offload()`. We repeat this for the other tests, too. self.pipeline = self.pipeline.to(torch_device)
prompt = "jon snow eating pizza with ketchup"
out = self.pipeline( prompt, num_inference_steps=self.num_inference_steps, guidance_scale=4.0, output_type="np", generator=torch.manual_seed(self.seed), ).images out_slice = out[0, -3:, -3:, -1].flatten() expected_slice = np.array([0.1855, 0.1855, 0.1836, 0.1855, 0.1836, 0.1875, 0.1777, 0.1758, 0.2246])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
def test_flux_kohya(self): self.pipeline.load_lora_weights("Norod78/brain-slug-flux") self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() self.pipeline = self.pipeline.to(torch_device)
prompt = "The cat with a brain slug earring" out = self.pipeline( prompt, num_inference_steps=self.num_inference_steps, guidance_scale=4.5, output_type="np", generator=torch.manual_seed(self.seed), ).images
out_slice = out[0, -3:, -3:, -1].flatten() expected_slice = np.array([0.6367, 0.6367, 0.6328, 0.6367, 0.6328, 0.6289, 0.6367, 0.6328, 0.6484])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
def test_flux_kohya_with_text_encoder(self): self.pipeline.load_lora_weights("cocktailpeanut/optimus", weight_name="optimus.safetensors") self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() self.pipeline = self.pipeline.to(torch_device)
prompt = "optimus is cleaning the house with broomstick" out = self.pipeline( prompt, num_inference_steps=self.num_inference_steps, guidance_scale=4.5, output_type="np", generator=torch.manual_seed(self.seed), ).images
out_slice = out[0, -3:, -3:, -1].flatten() expected_slice = np.array([0.4023, 0.4023, 0.4023, 0.3965, 0.3984, 0.3965, 0.3926, 0.3906, 0.4219])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
def test_flux_xlabs(self): self.pipeline.load_lora_weights("XLabs-AI/flux-lora-collection", weight_name="disney_lora.safetensors") self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() self.pipeline = self.pipeline.to(torch_device)
prompt = "A blue jay standing on a large basket of rainbow macarons, disney style"
out = self.pipeline( prompt, num_inference_steps=self.num_inference_steps, guidance_scale=3.5, output_type="np", generator=torch.manual_seed(self.seed), ).images out_slice = out[0, -3:, -3:, -1].flatten() expected_slice = np.array([0.3965, 0.4180, 0.4434, 0.4082, 0.4375, 0.4590, 0.4141, 0.4375, 0.4980])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
def test_flux_xlabs_load_lora_with_single_blocks(self): self.pipeline.load_lora_weights( "salinasr/test_xlabs_flux_lora_with_singleblocks", weight_name="lora.safetensors" ) self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() self.pipeline.enable_model_cpu_offload()
prompt = "a wizard mouse playing chess"
out = self.pipeline( prompt, num_inference_steps=self.num_inference_steps, guidance_scale=3.5, output_type="np", generator=torch.manual_seed(self.seed), ).images out_slice = out[0, -3:, -3:, -1].flatten() expected_slice = np.array( [0.04882812, 0.04101562, 0.04882812, 0.03710938, 0.02929688, 0.02734375, 0.0234375, 0.01757812, 0.0390625] ) max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
@nightly@require_torch_accelerator@require_peft_backend@require_big_acceleratorclass FluxControlLoRAIntegrationTests(unittest.TestCase): num_inference_steps = 10 seed = 0 prompt = "A robot made of exotic candies and chocolates of different kinds."
def setUp(self): super().setUp()
gc.collect() backend_empty_cache(torch_device)
self.pipeline = FluxControlPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16 ).to(torch_device)
def tearDown(self): super().tearDown()
gc.collect() backend_empty_cache(torch_device)
@parameterized.expand(["black-forest-labs/FLUX.1-Canny-dev-lora", "black-forest-labs/FLUX.1-Depth-dev-lora"]) def test_lora(self, lora_ckpt_id): self.pipeline.load_lora_weights(lora_ckpt_id) self.pipeline.fuse_lora() self.pipeline.unload_lora_weights()
if "Canny" in lora_ckpt_id: control_image = load_image( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux-control-lora/canny_condition_image.png" ) else: control_image = load_image( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux-control-lora/depth_condition_image.png" )
image = self.pipeline( prompt=self.prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=self.num_inference_steps, guidance_scale=30.0 if "Canny" in lora_ckpt_id else 10.0, output_type="np", generator=torch.manual_seed(self.seed), ).images
out_slice = image[0, -3:, -3:, -1].flatten() if "Canny" in lora_ckpt_id: expected_slice = np.array([0.8438, 0.8438, 0.8438, 0.8438, 0.8438, 0.8398, 0.8438, 0.8438, 0.8516]) else: expected_slice = np.array([0.8203, 0.8320, 0.8359, 0.8203, 0.8281, 0.8281, 0.8203, 0.8242, 0.8359])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3
@parameterized.expand(["black-forest-labs/FLUX.1-Canny-dev-lora", "black-forest-labs/FLUX.1-Depth-dev-lora"]) def test_lora_with_turbo(self, lora_ckpt_id): self.pipeline.load_lora_weights(lora_ckpt_id) self.pipeline.load_lora_weights("ByteDance/Hyper-SD", weight_name="Hyper-FLUX.1-dev-8steps-lora.safetensors") self.pipeline.fuse_lora() self.pipeline.unload_lora_weights()
if "Canny" in lora_ckpt_id: control_image = load_image( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux-control-lora/canny_condition_image.png" ) else: control_image = load_image( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux-control-lora/depth_condition_image.png" )
image = self.pipeline( prompt=self.prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=self.num_inference_steps, guidance_scale=30.0 if "Canny" in lora_ckpt_id else 10.0, output_type="np", generator=torch.manual_seed(self.seed), ).images
out_slice = image[0, -3:, -3:, -1].flatten() if "Canny" in lora_ckpt_id: expected_slice = np.array([0.6562, 0.7266, 0.7578, 0.6367, 0.6758, 0.7031, 0.6172, 0.6602, 0.6484]) else: expected_slice = np.array([0.6680, 0.7344, 0.7656, 0.6484, 0.6875, 0.7109, 0.6328, 0.6719, 0.6562])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import gcimport sysimport unittest
import numpy as npimport torchfrom transformers import CLIPTextModel, CLIPTokenizer, LlamaModel, LlamaTokenizerFast
from diffusers import ( AutoencoderKLHunyuanVideo, FlowMatchEulerDiscreteScheduler, HunyuanVideoPipeline, HunyuanVideoTransformer3DModel,)
from ..testing_utils import ( Expectations, backend_empty_cache, floats_tensor, nightly, numpy_cosine_similarity_distance, require_big_accelerator, require_peft_backend, require_torch_accelerator, skip_mps, torch_device,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backend@skip_mpsclass HunyuanVideoLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = HunyuanVideoPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "in_channels": 4, "out_channels": 4, "num_attention_heads": 2, "attention_head_dim": 10, "num_layers": 1, "num_single_layers": 1, "num_refiner_layers": 1, "patch_size": 1, "patch_size_t": 1, "guidance_embeds": True, "text_embed_dim": 16, "pooled_projection_dim": 8, "rope_axes_dim": (2, 4, 4), } transformer_cls = HunyuanVideoTransformer3DModel vae_kwargs = { "in_channels": 3, "out_channels": 3, "latent_channels": 4, "down_block_types": ( "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", ), "up_block_types": ( "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", ), "block_out_channels": (8, 8, 8, 8), "layers_per_block": 1, "act_fn": "silu", "norm_num_groups": 4, "scaling_factor": 0.476986, "spatial_compression_ratio": 8, "temporal_compression_ratio": 4, "mid_block_add_attention": True, } vae_cls = AutoencoderKLHunyuanVideo has_two_text_encoders = True tokenizer_cls, tokenizer_id, tokenizer_subfolder = ( LlamaTokenizerFast, "hf-internal-testing/tiny-random-hunyuanvideo", "tokenizer", ) tokenizer_2_cls, tokenizer_2_id, tokenizer_2_subfolder = ( CLIPTokenizer, "hf-internal-testing/tiny-random-hunyuanvideo", "tokenizer_2", ) text_encoder_cls, text_encoder_id, text_encoder_subfolder = ( LlamaModel, "hf-internal-testing/tiny-random-hunyuanvideo", "text_encoder", ) text_encoder_2_cls, text_encoder_2_id, text_encoder_2_subfolder = ( CLIPTextModel, "hf-internal-testing/tiny-random-hunyuanvideo", "text_encoder_2", )
@property def output_shape(self): return (1, 9, 32, 32, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 num_frames = 9 num_latent_frames = 3 # (num_frames - 1) // temporal_compression_ratio + 1 sizes = (4, 4)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "", "num_frames": num_frames, "num_inference_steps": 1, "guidance_scale": 6.0, "height": 32, "width": 32, "max_sequence_length": sequence_length, "prompt_template": {"template": "{}", "crop_start": 0}, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
# TODO(aryan): Fix the following test @unittest.skip("This test fails with an error I haven't been able to debug yet.") def test_simple_inference_save_pretrained(self): pass
@unittest.skip("Not supported in HunyuanVideo.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in HunyuanVideo.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in HunyuanVideo.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in HunyuanVideo.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in HunyuanVideo.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in HunyuanVideo.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in HunyuanVideo.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in HunyuanVideo.") def test_simple_inference_with_text_lora_save_load(self): pass
@nightly@require_torch_accelerator@require_peft_backend@require_big_acceleratorclass HunyuanVideoLoRAIntegrationTests(unittest.TestCase): """internal note: The integration slices were obtained on DGX.
torch: 2.5.1+cu124 with CUDA 12.5. Need the same setup for the assertions to pass. """
num_inference_steps = 10 seed = 0
def setUp(self): super().setUp()
gc.collect() backend_empty_cache(torch_device)
model_id = "hunyuanvideo-community/HunyuanVideo" transformer = HunyuanVideoTransformer3DModel.from_pretrained( model_id, subfolder="transformer", torch_dtype=torch.bfloat16 ) self.pipeline = HunyuanVideoPipeline.from_pretrained( model_id, transformer=transformer, torch_dtype=torch.float16 ).to(torch_device)
def tearDown(self): super().tearDown()
gc.collect() backend_empty_cache(torch_device)
def test_original_format_cseti(self): self.pipeline.load_lora_weights( "Cseti/HunyuanVideo-LoRA-Arcane_Jinx-v1", weight_name="csetiarcane-nfjinx-v1-6000.safetensors" ) self.pipeline.fuse_lora() self.pipeline.unload_lora_weights() self.pipeline.vae.enable_tiling()
prompt = "CSETIARCANE. A cat walks on the grass, realistic"
out = self.pipeline( prompt=prompt, height=320, width=512, num_frames=9, num_inference_steps=self.num_inference_steps, output_type="np", generator=torch.manual_seed(self.seed), ).frames[0] out = out.flatten() out_slice = np.concatenate((out[:8], out[-8:]))
# fmt: off expected_slices = Expectations( { ("cuda", 7): np.array([0.1013, 0.1924, 0.0078, 0.1021, 0.1929, 0.0078, 0.1023, 0.1919, 0.7402, 0.104, 0.4482, 0.7354, 0.0925, 0.4382, 0.7275, 0.0815]), } ) # fmt: on expected_slice = expected_slices.get_expectation()
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), out_slice)
assert max_diff < 1e-3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport unittest
import torchfrom transformers import AutoTokenizer, T5EncoderModel
from diffusers import ( AutoencoderKLLTXVideo, FlowMatchEulerDiscreteScheduler, LTXPipeline, LTXVideoTransformer3DModel,)
from ..testing_utils import floats_tensor, require_peft_backend
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backendclass LTXVideoLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = LTXPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "in_channels": 8, "out_channels": 8, "patch_size": 1, "patch_size_t": 1, "num_attention_heads": 4, "attention_head_dim": 8, "cross_attention_dim": 32, "num_layers": 1, "caption_channels": 32, } transformer_cls = LTXVideoTransformer3DModel vae_kwargs = { "in_channels": 3, "out_channels": 3, "latent_channels": 8, "block_out_channels": (8, 8, 8, 8), "decoder_block_out_channels": (8, 8, 8, 8), "layers_per_block": (1, 1, 1, 1, 1), "decoder_layers_per_block": (1, 1, 1, 1, 1), "spatio_temporal_scaling": (True, True, False, False), "decoder_spatio_temporal_scaling": (True, True, False, False), "decoder_inject_noise": (False, False, False, False, False), "upsample_residual": (False, False, False, False), "upsample_factor": (1, 1, 1, 1), "timestep_conditioning": False, "patch_size": 1, "patch_size_t": 1, "encoder_causal": True, "decoder_causal": False, } vae_cls = AutoencoderKLLTXVideo tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
text_encoder_target_modules = ["q", "k", "v", "o"]
@property def output_shape(self): return (1, 9, 32, 32, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 8 num_frames = 9 num_latent_frames = 3 # (num_frames - 1) // temporal_compression_ratio + 1 latent_height = 8 latent_width = 8
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels, latent_height, latent_width)) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "dance monkey", "num_frames": num_frames, "num_inference_steps": 4, "guidance_scale": 6.0, "height": 32, "width": 32, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
@unittest.skip("Not supported in LTXVideo.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in LTXVideo.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in LTXVideo.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in LTXVideo.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in LTXVideo.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in LTXVideo.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in LTXVideo.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in LTXVideo.") def test_simple_inference_with_text_lora_save_load(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport unittest
import numpy as npimport pytestimport torchfrom transformers import AutoTokenizer, GemmaForCausalLM
from diffusers import ( AutoencoderKL, FlowMatchEulerDiscreteScheduler, Lumina2Pipeline, Lumina2Transformer2DModel,)
from ..testing_utils import floats_tensor, is_torch_version, require_peft_backend, skip_mps, torch_device
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests, check_if_lora_correctly_set # noqa: E402
@require_peft_backendclass Lumina2LoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = Lumina2Pipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "sample_size": 4, "patch_size": 2, "in_channels": 4, "hidden_size": 8, "num_layers": 2, "num_attention_heads": 1, "num_kv_heads": 1, "multiple_of": 16, "ffn_dim_multiplier": None, "norm_eps": 1e-5, "scaling_factor": 1.0, "axes_dim_rope": [4, 2, 2], "cap_feat_dim": 8, } transformer_cls = Lumina2Transformer2DModel vae_kwargs = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "block_out_channels": (4,), "layers_per_block": 1, "latent_channels": 4, "norm_num_groups": 1, "use_quant_conv": False, "use_post_quant_conv": False, "shift_factor": 0.0609, "scaling_factor": 1.5035, } vae_cls = AutoencoderKL tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/dummy-gemma" text_encoder_cls, text_encoder_id = GemmaForCausalLM, "hf-internal-testing/dummy-gemma-diffusers"
@property def output_shape(self): return (1, 4, 4, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "A painting of a squirrel eating a burger", "num_inference_steps": 2, "guidance_scale": 5.0, "height": 32, "width": 32, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
@unittest.skip("Not supported in Lumina2.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Lumina2.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Lumina2.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in Lumina2.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Lumina2.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Lumina2.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in Lumina2.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in Lumina2.") def test_simple_inference_with_text_lora_save_load(self): pass
@skip_mps @pytest.mark.xfail( condition=torch.device(torch_device).type == "cpu" and is_torch_version(">=", "2.5"), reason="Test currently fails on CPU and PyTorch 2.5.1 but not on PyTorch 2.4.1.", strict=False, ) def test_lora_fuse_nan(self): for scheduler_cls in self.scheduler_classes: components, text_lora_config, denoiser_lora_config = self.get_dummy_components(scheduler_cls) pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) _, _, inputs = self.get_dummy_inputs(with_generator=False)
if "text_encoder" in self.pipeline_class._lora_loadable_modules: pipe.text_encoder.add_adapter(text_lora_config, "adapter-1") self.assertTrue( check_if_lora_correctly_set(pipe.text_encoder), "Lora not correctly set in text encoder" )
denoiser = pipe.transformer if self.unet_kwargs is None else pipe.unet denoiser.add_adapter(denoiser_lora_config, "adapter-1") self.assertTrue(check_if_lora_correctly_set(denoiser), "Lora not correctly set in denoiser.")
# corrupt one LoRA weight with `inf` values with torch.no_grad(): pipe.transformer.layers[0].attn.to_q.lora_A["adapter-1"].weight += float("inf")
# with `safe_fusing=True` we should see an Error with self.assertRaises(ValueError): pipe.fuse_lora(components=self.pipeline_class._lora_loadable_modules, safe_fusing=True)
# without we should not see an error, but every image will be black pipe.fuse_lora(components=self.pipeline_class._lora_loadable_modules, safe_fusing=False) out = pipe(**inputs)[0]
self.assertTrue(np.isnan(out).all())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport unittest
import torchfrom transformers import AutoTokenizer, T5EncoderModel
from diffusers import AutoencoderKLMochi, FlowMatchEulerDiscreteScheduler, MochiPipeline, MochiTransformer3DModel
from ..testing_utils import ( floats_tensor, require_peft_backend, skip_mps,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backend@skip_mpsclass MochiLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = MochiPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "patch_size": 2, "num_attention_heads": 2, "attention_head_dim": 8, "num_layers": 2, "pooled_projection_dim": 16, "in_channels": 12, "out_channels": None, "qk_norm": "rms_norm", "text_embed_dim": 32, "time_embed_dim": 4, "activation_fn": "swiglu", "max_sequence_length": 16, } transformer_cls = MochiTransformer3DModel vae_kwargs = { "latent_channels": 12, "out_channels": 3, "encoder_block_out_channels": (32, 32, 32, 32), "decoder_block_out_channels": (32, 32, 32, 32), "layers_per_block": (1, 1, 1, 1, 1), } vae_cls = AutoencoderKLMochi tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
text_encoder_target_modules = ["q", "k", "v", "o"]
@property def output_shape(self): return (1, 7, 16, 16, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 num_frames = 7 num_latent_frames = 3 sizes = (2, 2)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "dance monkey", "num_frames": num_frames, "num_inference_steps": 4, "guidance_scale": 6.0, # Cannot reduce because convolution kernel becomes bigger than sample "height": 16, "width": 16, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
@unittest.skip("Not supported in Mochi.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Mochi.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Mochi.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in Mochi.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Mochi.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Mochi.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in Mochi.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in Mochi.") def test_simple_inference_with_text_lora_save_load(self): pass
@unittest.skip("Not supported in CogVideoX.") def test_simple_inference_with_text_denoiser_multi_adapter_block_lora(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import sysimport unittest
import torchfrom transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer
from diffusers import ( AutoencoderKLQwenImage, FlowMatchEulerDiscreteScheduler, QwenImagePipeline, QwenImageTransformer2DModel,)
from ..testing_utils import floats_tensor, require_peft_backend
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backendclass QwenImageLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = QwenImagePipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "patch_size": 2, "in_channels": 16, "out_channels": 4, "num_layers": 2, "attention_head_dim": 16, "num_attention_heads": 3, "joint_attention_dim": 16, "guidance_embeds": False, "axes_dims_rope": (8, 4, 4), } transformer_cls = QwenImageTransformer2DModel z_dim = 4 vae_kwargs = { "base_dim": z_dim * 6, "z_dim": z_dim, "dim_mult": [1, 2, 4], "num_res_blocks": 1, "temperal_downsample": [False, True], "latents_mean": [0.0] * 4, "latents_std": [1.0] * 4, } vae_cls = AutoencoderKLQwenImage tokenizer_cls, tokenizer_id = Qwen2Tokenizer, "hf-internal-testing/tiny-random-Qwen25VLForCondGen" text_encoder_cls, text_encoder_id = ( Qwen2_5_VLForConditionalGeneration, "hf-internal-testing/tiny-random-Qwen25VLForCondGen", ) denoiser_target_modules = ["to_q", "to_k", "to_v", "to_out.0"]
@property def output_shape(self): return (1, 8, 8, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 10 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "A painting of a squirrel eating a burger", "num_inference_steps": 4, "guidance_scale": 0.0, "height": 8, "width": 8, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
@unittest.skip("Not supported in Qwen Image.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Qwen Image.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Qwen Image.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in Qwen Image.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Qwen Image.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Qwen Image.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in Qwen Image.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in Qwen Image.") def test_simple_inference_with_text_lora_save_load(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import sysimport unittest
import torchfrom transformers import Gemma2Model, GemmaTokenizer
from diffusers import AutoencoderDC, FlowMatchEulerDiscreteScheduler, SanaPipeline, SanaTransformer2DModel
from ..testing_utils import floats_tensor, require_peft_backend
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backendclass SanaLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = SanaPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler(shift=7.0) scheduler_kwargs = {} scheduler_classes = [FlowMatchEulerDiscreteScheduler] transformer_kwargs = { "patch_size": 1, "in_channels": 4, "out_channels": 4, "num_layers": 1, "num_attention_heads": 2, "attention_head_dim": 4, "num_cross_attention_heads": 2, "cross_attention_head_dim": 4, "cross_attention_dim": 8, "caption_channels": 8, "sample_size": 32, } transformer_cls = SanaTransformer2DModel vae_kwargs = { "in_channels": 3, "latent_channels": 4, "attention_head_dim": 2, "encoder_block_types": ( "ResBlock", "EfficientViTBlock", ), "decoder_block_types": ( "ResBlock", "EfficientViTBlock", ), "encoder_block_out_channels": (8, 8), "decoder_block_out_channels": (8, 8), "encoder_qkv_multiscales": ((), (5,)), "decoder_qkv_multiscales": ((), (5,)), "encoder_layers_per_block": (1, 1), "decoder_layers_per_block": [1, 1], "downsample_block_type": "conv", "upsample_block_type": "interpolate", "decoder_norm_types": "rms_norm", "decoder_act_fns": "silu", "scaling_factor": 0.41407, } vae_cls = AutoencoderDC tokenizer_cls, tokenizer_id = GemmaTokenizer, "hf-internal-testing/dummy-gemma" text_encoder_cls, text_encoder_id = Gemma2Model, "hf-internal-testing/dummy-gemma-for-diffusers"
@property def output_shape(self): return (1, 32, 32, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 sizes = (32, 32)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "", "negative_prompt": "", "num_inference_steps": 4, "guidance_scale": 4.5, "height": 32, "width": 32, "max_sequence_length": sequence_length, "output_type": "np", "complex_human_instruction": None, } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
@unittest.skip("Not supported in SANA.") def test_modify_padding_mode(self): pass
@unittest.skip("Not supported in SANA.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in SANA.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Text encoder LoRA is not supported in SANA.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in SANA.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in SANA.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in SANA.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in SANA.") def test_simple_inference_with_text_lora_save_load(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import gcimport sysimport unittest
import numpy as npimport torchimport torch.nn as nnfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filefrom transformers import CLIPTextModel, CLIPTokenizer
from diffusers import ( AutoPipelineForImage2Image, AutoPipelineForText2Image, DDIMScheduler, DiffusionPipeline, LCMScheduler, StableDiffusionPipeline,)from diffusers.utils.import_utils import is_accelerate_available
from ..testing_utils import ( Expectations, backend_empty_cache, load_image, nightly, numpy_cosine_similarity_distance, require_peft_backend, require_torch_accelerator, slow, torch_device,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests, check_if_lora_correctly_set # noqa: E402
if is_accelerate_available(): from accelerate.utils import release_memory
class StableDiffusionLoRATests(PeftLoraLoaderMixinTests, unittest.TestCase): pipeline_class = StableDiffusionPipeline scheduler_cls = DDIMScheduler scheduler_kwargs = { "beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear", "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 1, } unet_kwargs = { "block_out_channels": (32, 64), "layers_per_block": 2, "sample_size": 32, "in_channels": 4, "out_channels": 4, "down_block_types": ("DownBlock2D", "CrossAttnDownBlock2D"), "up_block_types": ("CrossAttnUpBlock2D", "UpBlock2D"), "cross_attention_dim": 32, } vae_kwargs = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } text_encoder_cls, text_encoder_id = CLIPTextModel, "peft-internal-testing/tiny-clip-text-2" tokenizer_cls, tokenizer_id = CLIPTokenizer, "peft-internal-testing/tiny-clip-text-2"
@property def output_shape(self): return (1, 64, 64, 3)
def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device)
def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device)
# Keeping this test here makes sense because it doesn't look any integration # (value assertions on logits). @slow @require_torch_accelerator def test_integration_move_lora_cpu(self): path = "stable-diffusion-v1-5/stable-diffusion-v1-5" lora_id = "takuma104/lora-test-text-encoder-lora-target"
pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe.load_lora_weights(lora_id, adapter_name="adapter-1") pipe.load_lora_weights(lora_id, adapter_name="adapter-2") pipe = pipe.to(torch_device)
self.assertTrue( check_if_lora_correctly_set(pipe.text_encoder), "Lora not correctly set in text encoder", )
self.assertTrue( check_if_lora_correctly_set(pipe.unet), "Lora not correctly set in unet", )
# We will offload the first adapter in CPU and check if the offloading # has been performed correctly pipe.set_lora_device(["adapter-1"], "cpu")
for name, module in pipe.unet.named_modules(): if "adapter-1" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device == torch.device("cpu")) elif "adapter-2" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device != torch.device("cpu"))
for name, module in pipe.text_encoder.named_modules(): if "adapter-1" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device == torch.device("cpu")) elif "adapter-2" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device != torch.device("cpu"))
pipe.set_lora_device(["adapter-1"], 0)
for n, m in pipe.unet.named_modules(): if "adapter-1" in n and not isinstance(m, (nn.Dropout, nn.Identity)): self.assertTrue(m.weight.device != torch.device("cpu"))
for n, m in pipe.text_encoder.named_modules(): if "adapter-1" in n and not isinstance(m, (nn.Dropout, nn.Identity)): self.assertTrue(m.weight.device != torch.device("cpu"))
pipe.set_lora_device(["adapter-1", "adapter-2"], torch_device)
for n, m in pipe.unet.named_modules(): if ("adapter-1" in n or "adapter-2" in n) and not isinstance(m, (nn.Dropout, nn.Identity)): self.assertTrue(m.weight.device != torch.device("cpu"))
for n, m in pipe.text_encoder.named_modules(): if ("adapter-1" in n or "adapter-2" in n) and not isinstance(m, (nn.Dropout, nn.Identity)): self.assertTrue(m.weight.device != torch.device("cpu"))
@slow @require_torch_accelerator def test_integration_move_lora_dora_cpu(self): from peft import LoraConfig
path = "stable-diffusion-v1-5/stable-diffusion-v1-5" unet_lora_config = LoraConfig( init_lora_weights="gaussian", target_modules=["to_k", "to_q", "to_v", "to_out.0"], use_dora=True, ) text_lora_config = LoraConfig( init_lora_weights="gaussian", target_modules=["q_proj", "k_proj", "v_proj", "out_proj"], use_dora=True, )
pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe.unet.add_adapter(unet_lora_config, "adapter-1") pipe.text_encoder.add_adapter(text_lora_config, "adapter-1")
self.assertTrue( check_if_lora_correctly_set(pipe.text_encoder), "Lora not correctly set in text encoder", )
self.assertTrue( check_if_lora_correctly_set(pipe.unet), "Lora not correctly set in unet", )
for name, param in pipe.unet.named_parameters(): if "lora_" in name: self.assertEqual(param.device, torch.device("cpu"))
for name, param in pipe.text_encoder.named_parameters(): if "lora_" in name: self.assertEqual(param.device, torch.device("cpu"))
pipe.set_lora_device(["adapter-1"], torch_device)
for name, param in pipe.unet.named_parameters(): if "lora_" in name: self.assertNotEqual(param.device, torch.device("cpu"))
for name, param in pipe.text_encoder.named_parameters(): if "lora_" in name: self.assertNotEqual(param.device, torch.device("cpu"))
@slow @require_torch_accelerator def test_integration_set_lora_device_different_target_layers(self): # fixes a bug that occurred when calling set_lora_device with multiple adapters loaded that target different # layers, see #11833 from peft import LoraConfig
path = "stable-diffusion-v1-5/stable-diffusion-v1-5" pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float16) # configs partly target the same, partly different layers config0 = LoraConfig(target_modules=["to_k", "to_v"]) config1 = LoraConfig(target_modules=["to_k", "to_q"]) pipe.unet.add_adapter(config0, adapter_name="adapter-0") pipe.unet.add_adapter(config1, adapter_name="adapter-1") pipe = pipe.to(torch_device)
self.assertTrue( check_if_lora_correctly_set(pipe.unet), "Lora not correctly set in unet", )
# sanity check that the adapters don't target the same layers, otherwise the test passes even without the fix modules_adapter_0 = {n for n, _ in pipe.unet.named_modules() if n.endswith(".adapter-0")} modules_adapter_1 = {n for n, _ in pipe.unet.named_modules() if n.endswith(".adapter-1")} self.assertNotEqual(modules_adapter_0, modules_adapter_1) self.assertTrue(modules_adapter_0 - modules_adapter_1) self.assertTrue(modules_adapter_1 - modules_adapter_0)
# setting both separately works pipe.set_lora_device(["adapter-0"], "cpu") pipe.set_lora_device(["adapter-1"], "cpu")
for name, module in pipe.unet.named_modules(): if "adapter-0" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device == torch.device("cpu")) elif "adapter-1" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device == torch.device("cpu"))
# setting both at once also works pipe.set_lora_device(["adapter-0", "adapter-1"], torch_device)
for name, module in pipe.unet.named_modules(): if "adapter-0" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device != torch.device("cpu")) elif "adapter-1" in name and not isinstance(module, (nn.Dropout, nn.Identity)): self.assertTrue(module.weight.device != torch.device("cpu"))
@slow@nightly@require_torch_accelerator@require_peft_backendclass LoraIntegrationTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device)
def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device)
def test_integration_logits_with_scale(self): path = "stable-diffusion-v1-5/stable-diffusion-v1-5" lora_id = "takuma104/lora-test-text-encoder-lora-target"
pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float32) pipe.load_lora_weights(lora_id) pipe = pipe.to(torch_device)
self.assertTrue( check_if_lora_correctly_set(pipe.text_encoder), "Lora not correctly set in text encoder", )
prompt = "a red sks dog"
images = pipe( prompt=prompt, num_inference_steps=15, cross_attention_kwargs={"scale": 0.5}, generator=torch.manual_seed(0), output_type="np", ).images
expected_slice_scale = np.array([0.307, 0.283, 0.310, 0.310, 0.300, 0.314, 0.336, 0.314, 0.321]) predicted_slice = images[0, -3:, -3:, -1].flatten()
max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_integration_logits_no_scale(self): path = "stable-diffusion-v1-5/stable-diffusion-v1-5" lora_id = "takuma104/lora-test-text-encoder-lora-target"
pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float32) pipe.load_lora_weights(lora_id) pipe = pipe.to(torch_device)
self.assertTrue( check_if_lora_correctly_set(pipe.text_encoder), "Lora not correctly set in text encoder", )
prompt = "a red sks dog"
images = pipe(prompt=prompt, num_inference_steps=30, generator=torch.manual_seed(0), output_type="np").images
expected_slice_scale = np.array([0.074, 0.064, 0.073, 0.0842, 0.069, 0.0641, 0.0794, 0.076, 0.084]) predicted_slice = images[0, -3:, -3:, -1].flatten()
max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice)
assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_dreambooth_old_format(self): generator = torch.Generator("cpu").manual_seed(0)
lora_model_id = "hf-internal-testing/lora_dreambooth_dog_example"
base_model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(base_model_id, safety_checker=None) pipe = pipe.to(torch_device) pipe.load_lora_weights(lora_model_id)
images = pipe( "A photo of a sks dog floating in the river", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.7207, 0.6787, 0.6010, 0.7478, 0.6838, 0.6064, 0.6984, 0.6443, 0.5785])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_dreambooth_text_encoder_new_format(self): generator = torch.Generator().manual_seed(0)
lora_model_id = "hf-internal-testing/lora-trained"
base_model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(base_model_id, safety_checker=None) pipe = pipe.to(torch_device) pipe.load_lora_weights(lora_model_id)
images = pipe("A photo of a sks dog", output_type="np", generator=generator, num_inference_steps=2).images
images = images[0, -3:, -3:, -1].flatten()
expected = np.array([0.6628, 0.6138, 0.5390, 0.6625, 0.6130, 0.5463, 0.6166, 0.5788, 0.5359])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_a1111(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionPipeline.from_pretrained("hf-internal-testing/Counterfeit-V2.5", safety_checker=None).to( torch_device ) lora_model_id = "hf-internal-testing/civitai-light-shadow-lora" lora_filename = "light_and_shadow.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.3636, 0.3708, 0.3694, 0.3679, 0.3829, 0.3677, 0.3692, 0.3688, 0.3292])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_lycoris(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/Amixx", safety_checker=None, use_safetensors=True, variant="fp16" ).to(torch_device) lora_model_id = "hf-internal-testing/edgLycorisMugler-light" lora_filename = "edgLycorisMugler-light.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.6463, 0.658, 0.599, 0.6542, 0.6512, 0.6213, 0.658, 0.6485, 0.6017])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_a1111_with_model_cpu_offload(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionPipeline.from_pretrained("hf-internal-testing/Counterfeit-V2.5", safety_checker=None) pipe.enable_model_cpu_offload(device=torch_device) lora_model_id = "hf-internal-testing/civitai-light-shadow-lora" lora_filename = "light_and_shadow.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.3636, 0.3708, 0.3694, 0.3679, 0.3829, 0.3677, 0.3692, 0.3688, 0.3292])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_a1111_with_sequential_cpu_offload(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionPipeline.from_pretrained("hf-internal-testing/Counterfeit-V2.5", safety_checker=None) pipe.enable_sequential_cpu_offload(device=torch_device) lora_model_id = "hf-internal-testing/civitai-light-shadow-lora" lora_filename = "light_and_shadow.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.3636, 0.3708, 0.3694, 0.3679, 0.3829, 0.3677, 0.3692, 0.3688, 0.3292])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_kohya_sd_v15_with_higher_dimensions(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionPipeline.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None ).to(torch_device) lora_model_id = "hf-internal-testing/urushisato-lora" lora_filename = "urushisato_v15.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.7165, 0.6616, 0.5833, 0.7504, 0.6718, 0.587, 0.6871, 0.6361, 0.5694])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_vanilla_funetuning(self): generator = torch.Generator().manual_seed(0)
lora_model_id = "hf-internal-testing/sd-model-finetuned-lora-t4"
base_model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(base_model_id, safety_checker=None) pipe = pipe.to(torch_device) pipe.load_lora_weights(lora_model_id)
images = pipe("A pokemon with blue eyes.", output_type="np", generator=generator, num_inference_steps=2).images
image_slice = images[0, -3:, -3:, -1].flatten()
expected_slices = Expectations( { ("xpu", 3): np.array( [ 0.6544, 0.6127, 0.5397, 0.6845, 0.6047, 0.5469, 0.6349, 0.5906, 0.5382, ] ), ("cuda", 7): np.array( [ 0.7406, 0.699, 0.5963, 0.7493, 0.7045, 0.6096, 0.6886, 0.6388, 0.583, ] ), ("cuda", 8): np.array( [ 0.6542, 0.61253, 0.5396, 0.6843, 0.6044, 0.5468, 0.6349, 0.5905, 0.5381, ] ), } ) expected_slice = expected_slices.get_expectation()
max_diff = numpy_cosine_similarity_distance(expected_slice, image_slice) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_unload_kohya_lora(self): generator = torch.manual_seed(0) prompt = "masterpiece, best quality, mountain" num_inference_steps = 2
pipe = StableDiffusionPipeline.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None ).to(torch_device) initial_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images initial_images = initial_images[0, -3:, -3:, -1].flatten()
lora_model_id = "hf-internal-testing/civitai-colored-icons-lora" lora_filename = "Colored_Icons_by_vizsumit.safetensors"
pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) generator = torch.manual_seed(0) lora_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images lora_images = lora_images[0, -3:, -3:, -1].flatten()
pipe.unload_lora_weights() generator = torch.manual_seed(0) unloaded_lora_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images unloaded_lora_images = unloaded_lora_images[0, -3:, -3:, -1].flatten()
self.assertFalse(np.allclose(initial_images, lora_images)) self.assertTrue(np.allclose(initial_images, unloaded_lora_images, atol=1e-3))
release_memory(pipe)
def test_load_unload_load_kohya_lora(self): # This test ensures that a Kohya-style LoRA can be safely unloaded and then loaded # without introducing any side-effects. Even though the test uses a Kohya-style # LoRA, the underlying adapter handling mechanism is format-agnostic. generator = torch.manual_seed(0) prompt = "masterpiece, best quality, mountain" num_inference_steps = 2
pipe = StableDiffusionPipeline.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None ).to(torch_device) initial_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images initial_images = initial_images[0, -3:, -3:, -1].flatten()
lora_model_id = "hf-internal-testing/civitai-colored-icons-lora" lora_filename = "Colored_Icons_by_vizsumit.safetensors"
pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) generator = torch.manual_seed(0) lora_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images lora_images = lora_images[0, -3:, -3:, -1].flatten()
pipe.unload_lora_weights() generator = torch.manual_seed(0) unloaded_lora_images = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images unloaded_lora_images = unloaded_lora_images[0, -3:, -3:, -1].flatten()
self.assertFalse(np.allclose(initial_images, lora_images)) self.assertTrue(np.allclose(initial_images, unloaded_lora_images, atol=1e-3))
# make sure we can load a LoRA again after unloading and they don't have # any undesired effects. pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) generator = torch.manual_seed(0) lora_images_again = pipe( prompt, output_type="np", generator=generator, num_inference_steps=num_inference_steps ).images lora_images_again = lora_images_again[0, -3:, -3:, -1].flatten()
self.assertTrue(np.allclose(lora_images, lora_images_again, atol=1e-3)) release_memory(pipe)
def test_not_empty_state_dict(self): # Makes sure https://github.com/huggingface/diffusers/issues/7054 does not happen again pipe = AutoPipelineForText2Image.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16 ).to(torch_device) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
cached_file = hf_hub_download("hf-internal-testing/lcm-lora-test-sd-v1-5", "test_lora.safetensors") lcm_lora = load_file(cached_file)
pipe.load_lora_weights(lcm_lora, adapter_name="lcm") self.assertTrue(lcm_lora != {}) release_memory(pipe)
def test_load_unload_load_state_dict(self): # Makes sure https://github.com/huggingface/diffusers/issues/7054 does not happen again pipe = AutoPipelineForText2Image.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16 ).to(torch_device) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
cached_file = hf_hub_download("hf-internal-testing/lcm-lora-test-sd-v1-5", "test_lora.safetensors") lcm_lora = load_file(cached_file) previous_state_dict = lcm_lora.copy()
pipe.load_lora_weights(lcm_lora, adapter_name="lcm") self.assertDictEqual(lcm_lora, previous_state_dict)
pipe.unload_lora_weights() pipe.load_lora_weights(lcm_lora, adapter_name="lcm") self.assertDictEqual(lcm_lora, previous_state_dict)
release_memory(pipe)
def test_sdv1_5_lcm_lora(self): pipe = DiffusionPipeline.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16 ) pipe.to(torch_device) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
generator = torch.Generator("cpu").manual_seed(0)
lora_model_id = "latent-consistency/lcm-lora-sdv1-5" pipe.load_lora_weights(lora_model_id)
image = pipe( "masterpiece, best quality, mountain", generator=generator, num_inference_steps=4, guidance_scale=0.5 ).images[0]
expected_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/lcm_lora/sdv15_lcm_lora.png" )
image_np = pipe.image_processor.pil_to_numpy(image) expected_image_np = pipe.image_processor.pil_to_numpy(expected_image)
max_diff = numpy_cosine_similarity_distance(image_np.flatten(), expected_image_np.flatten()) assert max_diff < 1e-4
pipe.unload_lora_weights()
release_memory(pipe)
def test_sdv1_5_lcm_lora_img2img(self): pipe = AutoPipelineForImage2Image.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16 ) pipe.to(torch_device) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
init_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape.png" )
generator = torch.Generator("cpu").manual_seed(0)
lora_model_id = "latent-consistency/lcm-lora-sdv1-5" pipe.load_lora_weights(lora_model_id)
image = pipe( "snowy mountain", generator=generator, image=init_image, strength=0.5, num_inference_steps=4, guidance_scale=0.5, ).images[0]
expected_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/lcm_lora/sdv15_lcm_lora_img2img.png" )
image_np = pipe.image_processor.pil_to_numpy(image) expected_image_np = pipe.image_processor.pil_to_numpy(expected_image)
max_diff = numpy_cosine_similarity_distance(image_np.flatten(), expected_image_np.flatten()) assert max_diff < 1e-4
pipe.unload_lora_weights()
release_memory(pipe)
def test_sd_load_civitai_empty_network_alpha(self): """ This test simply checks that loading a LoRA with an empty network alpha works fine See: https://github.com/huggingface/diffusers/issues/5606 """ pipeline = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5") pipeline.enable_sequential_cpu_offload(device=torch_device) civitai_path = hf_hub_download("ybelkada/test-ahi-civitai", "ahi_lora_weights.safetensors") pipeline.load_lora_weights(civitai_path, adapter_name="ahri")
images = pipeline( "ahri, masterpiece, league of legends", output_type="np", generator=torch.manual_seed(156), num_inference_steps=5, ).images images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.0, 0.0, 0.0, 0.002557, 0.020954, 0.001792, 0.006581, 0.00591, 0.002995])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipeline.unload_lora_weights() release_memory(pipeline)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import gcimport sysimport unittest
import numpy as npimport torchfrom transformers import AutoTokenizer, CLIPTextModelWithProjection, CLIPTokenizer, T5EncoderModel
from diffusers import ( FlowMatchEulerDiscreteScheduler, SD3Transformer2DModel, StableDiffusion3Img2ImgPipeline, StableDiffusion3Pipeline,)from diffusers.utils import load_imagefrom diffusers.utils.import_utils import is_accelerate_available
from ..testing_utils import ( backend_empty_cache, is_flaky, nightly, numpy_cosine_similarity_distance, require_big_accelerator, require_peft_backend, require_torch_accelerator, torch_device,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
if is_accelerate_available(): from accelerate.utils import release_memory
@require_peft_backendclass SD3LoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = StableDiffusion3Pipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_kwargs = {} scheduler_classes = [FlowMatchEulerDiscreteScheduler] transformer_kwargs = { "sample_size": 32, "patch_size": 1, "in_channels": 4, "num_layers": 1, "attention_head_dim": 8, "num_attention_heads": 4, "caption_projection_dim": 32, "joint_attention_dim": 32, "pooled_projection_dim": 64, "out_channels": 4, } transformer_cls = SD3Transformer2DModel vae_kwargs = { "sample_size": 32, "in_channels": 3, "out_channels": 3, "block_out_channels": (4,), "layers_per_block": 1, "latent_channels": 4, "norm_num_groups": 1, "use_quant_conv": False, "use_post_quant_conv": False, "shift_factor": 0.0609, "scaling_factor": 1.5035, } has_three_text_encoders = True tokenizer_cls, tokenizer_id = CLIPTokenizer, "hf-internal-testing/tiny-random-clip" tokenizer_2_cls, tokenizer_2_id = CLIPTokenizer, "hf-internal-testing/tiny-random-clip" tokenizer_3_cls, tokenizer_3_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = CLIPTextModelWithProjection, "hf-internal-testing/tiny-sd3-text_encoder" text_encoder_2_cls, text_encoder_2_id = CLIPTextModelWithProjection, "hf-internal-testing/tiny-sd3-text_encoder-2" text_encoder_3_cls, text_encoder_3_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
@property def output_shape(self): return (1, 32, 32, 3)
@require_torch_accelerator def test_sd3_lora(self): """ Test loading the loras that are saved with the diffusers and peft formats. Related PR: https://github.com/huggingface/diffusers/pull/8584 """ components = self.get_dummy_components() pipe = self.pipeline_class(**components[0]) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None)
lora_model_id = "hf-internal-testing/tiny-sd3-loras"
lora_filename = "lora_diffusers_format.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) pipe.unload_lora_weights()
lora_filename = "lora_peft_format.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
@unittest.skip("Not supported in SD3.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in SD3.") def test_simple_inference_with_text_denoiser_multi_adapter_block_lora(self): pass
@unittest.skip("Not supported in SD3.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in SD3.") def test_modify_padding_mode(self): pass
@is_flaky def test_multiple_wrong_adapter_name_raises_error(self): super().test_multiple_wrong_adapter_name_raises_error()
@nightly@require_torch_accelerator@require_peft_backend@require_big_acceleratorclass SD3LoraIntegrationTests(unittest.TestCase): pipeline_class = StableDiffusion3Img2ImgPipeline repo_id = "stabilityai/stable-diffusion-3-medium-diffusers"
def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device)
def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device)
def get_inputs(self, device, seed=0): init_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ) if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device="cpu").manual_seed(seed)
return { "prompt": "corgi", "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "np", "generator": generator, "image": init_image, }
def test_sd3_img2img_lora(self): pipe = self.pipeline_class.from_pretrained(self.repo_id, torch_dtype=torch.float16) pipe.load_lora_weights("zwloong/sd3-lora-training-rank16-v2") pipe.fuse_lora() pipe.unload_lora_weights() pipe = pipe.to(torch_device)
inputs = self.get_inputs(torch_device)
image = pipe(**inputs).images[0] image_slice = image[0, -3:, -3:] expected_slice = np.array([0.5649, 0.5405, 0.5488, 0.5688, 0.5449, 0.5513, 0.5337, 0.5107, 0.5059])
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
assert max_diff < 1e-4, f"Outputs are not close enough, got {max_diff}" pipe.unload_lora_weights() release_memory(pipe)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import copyimport gcimport importlibimport sysimport timeimport unittest
import numpy as npimport torchfrom packaging import versionfrom transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import ( ControlNetModel, EulerDiscreteScheduler, LCMScheduler, StableDiffusionXLAdapterPipeline, StableDiffusionXLControlNetPipeline, StableDiffusionXLPipeline, T2IAdapter,)from diffusers.utils import loggingfrom diffusers.utils.import_utils import is_accelerate_available
from ..testing_utils import ( CaptureLogger, backend_empty_cache, is_flaky, load_image, nightly, numpy_cosine_similarity_distance, require_peft_backend, require_torch_accelerator, slow, torch_device,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests, check_if_lora_correctly_set, state_dicts_almost_equal # noqa: E402
if is_accelerate_available(): from accelerate.utils import release_memory
class StableDiffusionXLLoRATests(PeftLoraLoaderMixinTests, unittest.TestCase): has_two_text_encoders = True pipeline_class = StableDiffusionXLPipeline scheduler_cls = EulerDiscreteScheduler scheduler_kwargs = { "beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear", "timestep_spacing": "leading", "steps_offset": 1, } unet_kwargs = { "block_out_channels": (32, 64), "layers_per_block": 2, "sample_size": 32, "in_channels": 4, "out_channels": 4, "down_block_types": ("DownBlock2D", "CrossAttnDownBlock2D"), "up_block_types": ("CrossAttnUpBlock2D", "UpBlock2D"), "attention_head_dim": (2, 4), "use_linear_projection": True, "addition_embed_type": "text_time", "addition_time_embed_dim": 8, "transformer_layers_per_block": (1, 2), "projection_class_embeddings_input_dim": 80, # 6 * 8 + 32 "cross_attention_dim": 64, } vae_kwargs = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, "sample_size": 128, } text_encoder_cls, text_encoder_id = CLIPTextModel, "peft-internal-testing/tiny-clip-text-2" tokenizer_cls, tokenizer_id = CLIPTokenizer, "peft-internal-testing/tiny-clip-text-2" text_encoder_2_cls, text_encoder_2_id = CLIPTextModelWithProjection, "peft-internal-testing/tiny-clip-text-2" tokenizer_2_cls, tokenizer_2_id = CLIPTokenizer, "peft-internal-testing/tiny-clip-text-2"
@property def output_shape(self): return (1, 64, 64, 3)
def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device)
def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device)
@is_flaky def test_multiple_wrong_adapter_name_raises_error(self): super().test_multiple_wrong_adapter_name_raises_error()
def test_simple_inference_with_text_denoiser_lora_unfused(self): if torch.cuda.is_available(): expected_atol = 9e-2 expected_rtol = 9e-2 else: expected_atol = 1e-3 expected_rtol = 1e-3
super().test_simple_inference_with_text_denoiser_lora_unfused( expected_atol=expected_atol, expected_rtol=expected_rtol )
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): if torch.cuda.is_available(): expected_atol = 9e-2 expected_rtol = 9e-2 else: expected_atol = 1e-3 expected_rtol = 1e-3
super().test_simple_inference_with_text_lora_denoiser_fused_multi( expected_atol=expected_atol, expected_rtol=expected_rtol )
def test_lora_scale_kwargs_match_fusion(self): if torch.cuda.is_available(): expected_atol = 9e-2 expected_rtol = 9e-2 else: expected_atol = 1e-3 expected_rtol = 1e-3
super().test_lora_scale_kwargs_match_fusion(expected_atol=expected_atol, expected_rtol=expected_rtol)
@slow@nightly@require_torch_accelerator@require_peft_backendclass LoraSDXLIntegrationTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device)
def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device)
def test_sdxl_1_0_lora(self): generator = torch.Generator("cpu").manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") pipe.enable_model_cpu_offload() lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.4468, 0.4061, 0.4134, 0.3637, 0.3202, 0.365, 0.3786, 0.3725, 0.3535])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_sdxl_1_0_blockwise_lora(self): generator = torch.Generator("cpu").manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") pipe.enable_model_cpu_offload() lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename, adapter_name="offset") scales = { "unet": { "down": {"block_1": [1.0, 1.0], "block_2": [1.0, 1.0]}, "mid": 1.0, "up": {"block_0": [1.0, 1.0, 1.0], "block_1": [1.0, 1.0, 1.0]}, }, } pipe.set_adapters(["offset"], [scales])
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([00.4468, 0.4061, 0.4134, 0.3637, 0.3202, 0.365, 0.3786, 0.3725, 0.3535])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_sdxl_lcm_lora(self): pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload()
generator = torch.Generator("cpu").manual_seed(0)
lora_model_id = "latent-consistency/lcm-lora-sdxl"
pipe.load_lora_weights(lora_model_id)
image = pipe( "masterpiece, best quality, mountain", generator=generator, num_inference_steps=4, guidance_scale=0.5 ).images[0]
expected_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/lcm_lora/sdxl_lcm_lora.png" )
image_np = pipe.image_processor.pil_to_numpy(image) expected_image_np = pipe.image_processor.pil_to_numpy(expected_image)
max_diff = numpy_cosine_similarity_distance(image_np.flatten(), expected_image_np.flatten()) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_sdxl_1_0_lora_fusion(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
pipe.fuse_lora() # We need to unload the lora weights since in the previous API `fuse_lora` led to lora weights being # silently deleted - otherwise this will CPU OOM pipe.unload_lora_weights()
pipe.enable_model_cpu_offload()
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() # This way we also test equivalence between LoRA fusion and the non-fusion behaviour. expected = np.array([0.4468, 0.4061, 0.4134, 0.3637, 0.3202, 0.365, 0.3786, 0.3725, 0.3535])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-4
release_memory(pipe)
def test_sdxl_1_0_lora_unfusion(self): generator = torch.Generator("cpu").manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) pipe.fuse_lora()
pipe.enable_model_cpu_offload()
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=3 ).images images_with_fusion = images.flatten()
pipe.unfuse_lora() generator = torch.Generator("cpu").manual_seed(0) images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=3 ).images images_without_fusion = images.flatten()
max_diff = numpy_cosine_similarity_distance(images_with_fusion, images_without_fusion) assert max_diff < 1e-4
release_memory(pipe)
def test_sdxl_1_0_lora_unfusion_effectivity(self): pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") pipe.enable_model_cpu_offload()
generator = torch.Generator().manual_seed(0) images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images original_image_slice = images[0, -3:, -3:, -1].flatten()
lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename) pipe.fuse_lora()
generator = torch.Generator().manual_seed(0) _ = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
pipe.unfuse_lora()
# We need to unload the lora weights - in the old API unfuse led to unloading the adapter weights pipe.unload_lora_weights()
generator = torch.Generator().manual_seed(0) images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images images_without_fusion_slice = images[0, -3:, -3:, -1].flatten()
max_diff = numpy_cosine_similarity_distance(images_without_fusion_slice, original_image_slice) assert max_diff < 1e-3
release_memory(pipe)
def test_sdxl_1_0_lora_fusion_efficiency(self): generator = torch.Generator().manual_seed(0) lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors"
pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ) pipe.load_lora_weights(lora_model_id, weight_name=lora_filename, torch_dtype=torch.float16) pipe.enable_model_cpu_offload()
start_time = time.time() for _ in range(3): pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images end_time = time.time() elapsed_time_non_fusion = end_time - start_time
del pipe
pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ) pipe.load_lora_weights(lora_model_id, weight_name=lora_filename, torch_dtype=torch.float16) pipe.fuse_lora()
# We need to unload the lora weights since in the previous API `fuse_lora` led to lora weights being # silently deleted - otherwise this will CPU OOM pipe.unload_lora_weights() pipe.enable_model_cpu_offload()
generator = torch.Generator().manual_seed(0) start_time = time.time() for _ in range(3): pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images end_time = time.time() elapsed_time_fusion = end_time - start_time
self.assertTrue(elapsed_time_fusion < elapsed_time_non_fusion)
release_memory(pipe)
def test_sdxl_1_0_last_ben(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") pipe.enable_model_cpu_offload() lora_model_id = "TheLastBen/Papercut_SDXL" lora_filename = "papercut.safetensors" pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe("papercut.safetensors", output_type="np", generator=generator, num_inference_steps=2).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.5244, 0.4347, 0.4312, 0.4246, 0.4398, 0.4409, 0.4884, 0.4938, 0.4094])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_sdxl_1_0_fuse_unfuse_all(self): pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ) text_encoder_1_sd = copy.deepcopy(pipe.text_encoder.state_dict()) text_encoder_2_sd = copy.deepcopy(pipe.text_encoder_2.state_dict()) unet_sd = copy.deepcopy(pipe.unet.state_dict())
pipe.load_lora_weights( "davizca87/sun-flower", weight_name="snfw3rXL-000004.safetensors", torch_dtype=torch.float16 )
fused_te_state_dict = pipe.text_encoder.state_dict() fused_te_2_state_dict = pipe.text_encoder_2.state_dict() unet_state_dict = pipe.unet.state_dict()
peft_ge_070 = version.parse(importlib.metadata.version("peft")) >= version.parse("0.7.0")
def remap_key(key, sd): # some keys have moved around for PEFT >= 0.7.0, but they should still be loaded correctly if (key in sd) or (not peft_ge_070): return key
# instead of linear.weight, we now have linear.base_layer.weight, etc. if key.endswith(".weight"): key = key[:-7] + ".base_layer.weight" elif key.endswith(".bias"): key = key[:-5] + ".base_layer.bias" return key
for key, value in text_encoder_1_sd.items(): key = remap_key(key, fused_te_state_dict) self.assertTrue(torch.allclose(fused_te_state_dict[key], value))
for key, value in text_encoder_2_sd.items(): key = remap_key(key, fused_te_2_state_dict) self.assertTrue(torch.allclose(fused_te_2_state_dict[key], value))
for key, value in unet_state_dict.items(): self.assertTrue(torch.allclose(unet_state_dict[key], value))
pipe.fuse_lora() pipe.unload_lora_weights()
assert not state_dicts_almost_equal(text_encoder_1_sd, pipe.text_encoder.state_dict()) assert not state_dicts_almost_equal(text_encoder_2_sd, pipe.text_encoder_2.state_dict()) assert not state_dicts_almost_equal(unet_sd, pipe.unet.state_dict())
release_memory(pipe) del unet_sd, text_encoder_1_sd, text_encoder_2_sd
def test_sdxl_1_0_lora_with_sequential_cpu_offloading(self): generator = torch.Generator().manual_seed(0)
pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0") pipe.enable_sequential_cpu_offload() lora_model_id = "hf-internal-testing/sdxl-1.0-lora" lora_filename = "sd_xl_offset_example-lora_1.0.safetensors"
pipe.load_lora_weights(lora_model_id, weight_name=lora_filename)
images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images
images = images[0, -3:, -3:, -1].flatten() expected = np.array([0.4468, 0.4087, 0.4134, 0.366, 0.3202, 0.3505, 0.3786, 0.387, 0.3535])
max_diff = numpy_cosine_similarity_distance(expected, images) assert max_diff < 1e-3
pipe.unload_lora_weights() release_memory(pipe)
def test_controlnet_canny_lora(self): controlnet = ControlNetModel.from_pretrained("diffusers/controlnet-canny-sdxl-1.0")
pipe = StableDiffusionXLControlNetPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet ) pipe.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors") pipe.enable_sequential_cpu_offload()
generator = torch.Generator(device="cpu").manual_seed(0) prompt = "corgi" image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ) images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
assert images[0].shape == (768, 512, 3)
original_image = images[0, -3:, -3:, -1].flatten() expected_image = np.array([0.4574, 0.4487, 0.4435, 0.5163, 0.4396, 0.4411, 0.518, 0.4465, 0.4333])
max_diff = numpy_cosine_similarity_distance(expected_image, original_image) assert max_diff < 1e-4
pipe.unload_lora_weights() release_memory(pipe)
def test_sdxl_t2i_adapter_canny_lora(self): adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-lineart-sdxl-1.0", torch_dtype=torch.float16).to( "cpu" ) pipe = StableDiffusionXLAdapterPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", adapter=adapter, torch_dtype=torch.float16, variant="fp16", ) pipe.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors") pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=None)
generator = torch.Generator(device="cpu").manual_seed(0) prompt = "toy" image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/t2i_adapter/toy_canny.png" )
images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
assert images[0].shape == (768, 512, 3)
image_slice = images[0, -3:, -3:, -1].flatten() expected_slice = np.array([0.4284, 0.4337, 0.4319, 0.4255, 0.4329, 0.4280, 0.4338, 0.4420, 0.4226]) assert numpy_cosine_similarity_distance(image_slice, expected_slice) < 1e-4
@nightly def test_sequential_fuse_unfuse(self): pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 )
# 1. round pipe.load_lora_weights("Pclanglais/TintinIA", torch_dtype=torch.float16) pipe.to(torch_device) pipe.fuse_lora()
generator = torch.Generator().manual_seed(0) images = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images image_slice = images[0, -3:, -3:, -1].flatten()
pipe.unfuse_lora()
# 2. round pipe.load_lora_weights("ProomptEngineer/pe-balloon-diffusion-style", torch_dtype=torch.float16) pipe.fuse_lora() pipe.unfuse_lora()
# 3. round pipe.load_lora_weights("ostris/crayon_style_lora_sdxl", torch_dtype=torch.float16) pipe.fuse_lora() pipe.unfuse_lora()
# 4. back to 1st round pipe.load_lora_weights("Pclanglais/TintinIA", torch_dtype=torch.float16) pipe.fuse_lora()
generator = torch.Generator().manual_seed(0) images_2 = pipe( "masterpiece, best quality, mountain", output_type="np", generator=generator, num_inference_steps=2 ).images image_slice_2 = images_2[0, -3:, -3:, -1].flatten()
max_diff = numpy_cosine_similarity_distance(image_slice, image_slice_2) assert max_diff < 1e-3 pipe.unload_lora_weights() release_memory(pipe)
@nightly def test_integration_logits_multi_adapter(self): path = "stabilityai/stable-diffusion-xl-base-1.0" lora_id = "CiroN2022/toy-face"
pipe = StableDiffusionXLPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe.load_lora_weights(lora_id, weight_name="toy_face_sdxl.safetensors", adapter_name="toy") pipe = pipe.to(torch_device)
self.assertTrue(check_if_lora_correctly_set(pipe.unet), "Lora not correctly set in Unet")
prompt = "toy_face of a hacker with a hoodie"
lora_scale = 0.9
images = pipe( prompt=prompt, num_inference_steps=30, generator=torch.manual_seed(0), cross_attention_kwargs={"scale": lora_scale}, output_type="np", ).images expected_slice_scale = np.array([0.538, 0.539, 0.540, 0.540, 0.542, 0.539, 0.538, 0.541, 0.539])
predicted_slice = images[0, -3:, -3:, -1].flatten() max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3
pipe.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel") pipe.set_adapters("pixel")
prompt = "pixel art, a hacker with a hoodie, simple, flat colors" images = pipe( prompt, num_inference_steps=30, guidance_scale=7.5, cross_attention_kwargs={"scale": lora_scale}, generator=torch.manual_seed(0), output_type="np", ).images
predicted_slice = images[0, -3:, -3:, -1].flatten() expected_slice_scale = np.array( [0.61973065, 0.62018543, 0.62181497, 0.61933696, 0.6208608, 0.620576, 0.6200281, 0.62258327, 0.6259889] ) max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3
# multi-adapter inference pipe.set_adapters(["pixel", "toy"], adapter_weights=[0.5, 1.0]) images = pipe( prompt, num_inference_steps=30, guidance_scale=7.5, cross_attention_kwargs={"scale": 1.0}, generator=torch.manual_seed(0), output_type="np", ).images predicted_slice = images[0, -3:, -3:, -1].flatten() expected_slice_scale = np.array([0.5888, 0.5897, 0.5946, 0.5888, 0.5935, 0.5946, 0.5857, 0.5891, 0.5909]) max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3
# Lora disabled pipe.disable_lora() images = pipe( prompt, num_inference_steps=30, guidance_scale=7.5, cross_attention_kwargs={"scale": lora_scale}, generator=torch.manual_seed(0), output_type="np", ).images predicted_slice = images[0, -3:, -3:, -1].flatten() expected_slice_scale = np.array([0.5456, 0.5466, 0.5487, 0.5458, 0.5469, 0.5454, 0.5446, 0.5479, 0.5487]) max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3
@nightly def test_integration_logits_for_dora_lora(self): pipeline = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
logger = logging.get_logger("diffusers.loaders.lora_pipeline") logger.setLevel(30) with CaptureLogger(logger) as cap_logger: pipeline.load_lora_weights("hf-internal-testing/dora-trained-on-kohya") pipeline.enable_model_cpu_offload() images = pipeline( "photo of ohwx dog", num_inference_steps=10, generator=torch.manual_seed(0), output_type="np", ).images assert "It seems like you are using a DoRA checkpoint" in cap_logger.out
predicted_slice = images[0, -3:, -3:, -1].flatten() expected_slice_scale = np.array([0.1817, 0.0697, 0.2346, 0.0900, 0.1261, 0.2279, 0.1767, 0.1991, 0.2886]) max_diff = numpy_cosine_similarity_distance(expected_slice_scale, predicted_slice) assert max_diff < 1e-3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport unittest
import torchfrom transformers import AutoTokenizer, T5EncoderModel
from diffusers import ( AutoencoderKLWan, FlowMatchEulerDiscreteScheduler, WanPipeline, WanTransformer3DModel,)
from ..testing_utils import ( floats_tensor, require_peft_backend, skip_mps,)
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backend@skip_mpsclass WanLoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = WanPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "patch_size": (1, 2, 2), "num_attention_heads": 2, "attention_head_dim": 12, "in_channels": 16, "out_channels": 16, "text_dim": 32, "freq_dim": 256, "ffn_dim": 32, "num_layers": 2, "cross_attn_norm": True, "qk_norm": "rms_norm_across_heads", "rope_max_seq_len": 32, } transformer_cls = WanTransformer3DModel vae_kwargs = { "base_dim": 3, "z_dim": 16, "dim_mult": [1, 1, 1, 1], "num_res_blocks": 1, "temperal_downsample": [False, True, True], } vae_cls = AutoencoderKLWan has_two_text_encoders = True tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
text_encoder_target_modules = ["q", "k", "v", "o"]
@property def output_shape(self): return (1, 9, 32, 32, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 num_frames = 9 num_latent_frames = 3 # (num_frames - 1) // temporal_compression_ratio + 1 sizes = (4, 4)
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator)
pipeline_inputs = { "prompt": "", "num_frames": num_frames, "num_inference_steps": 1, "guidance_scale": 6.0, "height": 32, "width": 32, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
@unittest.skip("Not supported in Wan.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Wan.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Wan.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan.") def test_simple_inference_with_text_lora_save_load(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import osimport sysimport tempfileimport unittest
import numpy as npimport safetensors.torchimport torchfrom PIL import Imagefrom transformers import AutoTokenizer, T5EncoderModel
from diffusers import AutoencoderKLWan, FlowMatchEulerDiscreteScheduler, WanVACEPipeline, WanVACETransformer3DModelfrom diffusers.utils.import_utils import is_peft_available
from ..testing_utils import ( floats_tensor, is_flaky, require_peft_backend, require_peft_version_greater, skip_mps, torch_device,)
if is_peft_available(): from peft.utils import get_peft_model_state_dict
sys.path.append(".")
from .utils import PeftLoraLoaderMixinTests # noqa: E402
@require_peft_backend@skip_mps@is_flaky(max_attempts=10, description="very flaky class")class WanVACELoRATests(unittest.TestCase, PeftLoraLoaderMixinTests): pipeline_class = WanVACEPipeline scheduler_cls = FlowMatchEulerDiscreteScheduler scheduler_classes = [FlowMatchEulerDiscreteScheduler] scheduler_kwargs = {}
transformer_kwargs = { "patch_size": (1, 2, 2), "num_attention_heads": 2, "attention_head_dim": 8, "in_channels": 4, "out_channels": 4, "text_dim": 32, "freq_dim": 16, "ffn_dim": 16, "num_layers": 2, "cross_attn_norm": True, "qk_norm": "rms_norm_across_heads", "rope_max_seq_len": 16, "vace_layers": [0], "vace_in_channels": 72, } transformer_cls = WanVACETransformer3DModel vae_kwargs = { "base_dim": 3, "z_dim": 4, "dim_mult": [1, 1, 1, 1], "latents_mean": torch.randn(4).numpy().tolist(), "latents_std": torch.randn(4).numpy().tolist(), "num_res_blocks": 1, "temperal_downsample": [False, True, True], } vae_cls = AutoencoderKLWan has_two_text_encoders = True tokenizer_cls, tokenizer_id = AutoTokenizer, "hf-internal-testing/tiny-random-t5" text_encoder_cls, text_encoder_id = T5EncoderModel, "hf-internal-testing/tiny-random-t5"
text_encoder_target_modules = ["q", "k", "v", "o"]
@property def output_shape(self): return (1, 9, 16, 16, 3)
def get_dummy_inputs(self, with_generator=True): batch_size = 1 sequence_length = 16 num_channels = 4 num_frames = 9 num_latent_frames = 3 # (num_frames - 1) // temporal_compression_ratio + 1 sizes = (4, 4) height, width = 16, 16
generator = torch.manual_seed(0) noise = floats_tensor((batch_size, num_latent_frames, num_channels) + sizes) input_ids = torch.randint(1, sequence_length, size=(batch_size, sequence_length), generator=generator) video = [Image.new("RGB", (height, width))] * num_frames mask = [Image.new("L", (height, width), 0)] * num_frames
pipeline_inputs = { "video": video, "mask": mask, "prompt": "", "num_frames": num_frames, "num_inference_steps": 1, "guidance_scale": 6.0, "height": height, "width": height, "max_sequence_length": sequence_length, "output_type": "np", } if with_generator: pipeline_inputs.update({"generator": generator})
return noise, input_ids, pipeline_inputs
def test_simple_inference_with_text_lora_denoiser_fused_multi(self): super().test_simple_inference_with_text_lora_denoiser_fused_multi(expected_atol=9e-3)
def test_simple_inference_with_text_denoiser_lora_unfused(self): super().test_simple_inference_with_text_denoiser_lora_unfused(expected_atol=9e-3)
@unittest.skip("Not supported in Wan VACE.") def test_simple_inference_with_text_denoiser_block_scale(self): pass
@unittest.skip("Not supported in Wan VACE.") def test_simple_inference_with_text_denoiser_block_scale_for_all_dict_options(self): pass
@unittest.skip("Not supported in Wan VACE.") def test_modify_padding_mode(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan VACE.") def test_simple_inference_with_partial_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan VACE.") def test_simple_inference_with_text_lora(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan VACE.") def test_simple_inference_with_text_lora_and_scale(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan VACE.") def test_simple_inference_with_text_lora_fused(self): pass
@unittest.skip("Text encoder LoRA is not supported in Wan VACE.") def test_simple_inference_with_text_lora_save_load(self): pass
def test_layerwise_casting_inference_denoiser(self): super().test_layerwise_casting_inference_denoiser()
@require_peft_version_greater("0.13.2") def test_lora_exclude_modules_wanvace(self): scheduler_cls = self.scheduler_classes[0] exclude_module_name = "vace_blocks.0.proj_out" components, text_lora_config, denoiser_lora_config = self.get_dummy_components(scheduler_cls) pipe = self.pipeline_class(**components).to(torch_device) _, _, inputs = self.get_dummy_inputs(with_generator=False)
output_no_lora = pipe(**inputs, generator=torch.manual_seed(0))[0] self.assertTrue(output_no_lora.shape == self.output_shape)
# only supported for `denoiser` now denoiser_lora_config.target_modules = ["proj_out"] denoiser_lora_config.exclude_modules = [exclude_module_name] pipe, _ = self.add_adapters_to_pipeline( pipe, text_lora_config=text_lora_config, denoiser_lora_config=denoiser_lora_config ) # The state dict shouldn't contain the modules to be excluded from LoRA. state_dict_from_model = get_peft_model_state_dict(pipe.transformer, adapter_name="default") self.assertTrue(not any(exclude_module_name in k for k in state_dict_from_model)) self.assertTrue(any("proj_out" in k for k in state_dict_from_model)) output_lora_exclude_modules = pipe(**inputs, generator=torch.manual_seed(0))[0]
with tempfile.TemporaryDirectory() as tmpdir: modules_to_save = self._get_modules_to_save(pipe, has_denoiser=True) lora_state_dicts = self._get_lora_state_dicts(modules_to_save) self.pipeline_class.save_lora_weights(save_directory=tmpdir, **lora_state_dicts) pipe.unload_lora_weights()
# Check in the loaded state dict. loaded_state_dict = safetensors.torch.load_file(os.path.join(tmpdir, "pytorch_lora_weights.safetensors")) self.assertTrue(not any(exclude_module_name in k for k in loaded_state_dict)) self.assertTrue(any("proj_out" in k for k in loaded_state_dict))
# Check in the state dict obtained after loading LoRA. pipe.load_lora_weights(tmpdir) state_dict_from_model = get_peft_model_state_dict(pipe.transformer, adapter_name="default_0") self.assertTrue(not any(exclude_module_name in k for k in state_dict_from_model)) self.assertTrue(any("proj_out" in k for k in state_dict_from_model))
output_lora_pretrained = pipe(**inputs, generator=torch.manual_seed(0))[0] self.assertTrue( not np.allclose(output_no_lora, output_lora_exclude_modules, atol=1e-3, rtol=1e-3), "LoRA should change outputs.", ) self.assertTrue( np.allclose(output_lora_exclude_modules, output_lora_pretrained, atol=1e-3, rtol=1e-3), "Lora outputs should match.", )
def test_simple_inference_with_text_denoiser_lora_and_scale(self): super().test_simple_inference_with_text_denoiser_lora_and_scale()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import gcimport unittest
import torchfrom parameterized import parameterized
from diffusers import AsymmetricAutoencoderKLfrom diffusers.utils.import_utils import is_xformers_available
from ...testing_utils import ( Expectations, backend_empty_cache, enable_full_determinism, floats_tensor, load_hf_numpy, require_torch_accelerator, require_torch_gpu, skip_mps, slow, torch_all_close, torch_device,)from ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class AutoencoderKLTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase): model_class = AsymmetricAutoencoderKL main_input_name = "sample" base_precision = 1e-2
def get_asym_autoencoder_kl_config(self, block_out_channels=None, norm_num_groups=None): block_out_channels = block_out_channels or [2, 4] norm_num_groups = norm_num_groups or 2 init_dict = { "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D"] * len(block_out_channels), "down_block_out_channels": block_out_channels, "layers_per_down_block": 1, "up_block_types": ["UpDecoderBlock2D"] * len(block_out_channels), "up_block_out_channels": block_out_channels, "layers_per_up_block": 1, "act_fn": "silu", "latent_channels": 4, "norm_num_groups": norm_num_groups, "sample_size": 32, "scaling_factor": 0.18215, } return init_dict
@property def dummy_input(self): batch_size = 4 num_channels = 3 sizes = (32, 32)
image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device) mask = torch.ones((batch_size, 1) + sizes).to(torch_device)
return {"sample": image, "mask": mask}
@property def input_shape(self): return (3, 32, 32)
@property def output_shape(self): return (3, 32, 32)
def prepare_init_args_and_inputs_for_common(self): init_dict = self.get_asym_autoencoder_kl_config() inputs_dict = self.dummy_input return init_dict, inputs_dict
@unittest.skip("Unsupported test.") def test_forward_with_norm_groups(self): pass
@slowclass AsymmetricAutoencoderKLIntegrationTests(unittest.TestCase): def get_file_format(self, seed, shape): return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"
def tearDown(self): # clean up the VRAM after each test super().tearDown() gc.collect() backend_empty_cache(torch_device)
def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False): dtype = torch.float16 if fp16 else torch.float32 image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype) return image
def get_sd_vae_model(self, model_id="cross-attention/asymmetric-autoencoder-kl-x-1-5", fp16=False): revision = "main" torch_dtype = torch.float32
model = AsymmetricAutoencoderKL.from_pretrained( model_id, torch_dtype=torch_dtype, revision=revision, ) model.to(torch_device).eval()
return model
def get_generator(self, seed=0): generator_device = "cpu" if not torch_device.startswith(torch_device) else torch_device if torch_device != "mps": return torch.Generator(device=generator_device).manual_seed(seed) return torch.manual_seed(seed)
@parameterized.expand( [ # fmt: off [ 33, Expectations( { ("xpu", 3): torch.tensor([-0.0343, 0.2873, 0.1680, -0.0140, -0.3459, 0.3522, -0.1336, 0.1075]), ("cuda", 7): torch.tensor([-0.0336, 0.3011, 0.1764, 0.0087, -0.3401, 0.3645, -0.1247, 0.1205]), ("mps", None): torch.tensor( [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824] ), } ), ], [ 47, Expectations( { ("xpu", 3): torch.tensor([0.4400, 0.0543, 0.2873, 0.2946, 0.0553, 0.0839, -0.1585, 0.2529]), ("cuda", 7): torch.tensor([0.4400, 0.0543, 0.2873, 0.2946, 0.0553, 0.0839, -0.1585, 0.2529]), ("mps", None): torch.tensor( [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089] ), } ), ], # fmt: on ] ) def test_stable_diffusion(self, seed, expected_slices): model = self.get_sd_vae_model() image = self.get_sd_image(seed) generator = self.get_generator(seed)
with torch.no_grad(): sample = model(image, generator=generator, sample_posterior=True).sample
assert sample.shape == image.shape
output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
expected_slice = expected_slices.get_expectation() assert torch_all_close(output_slice, expected_slice, atol=5e-3)
@parameterized.expand( [ # fmt: off [ 33, [-0.0340, 0.2870, 0.1698, -0.0105, -0.3448, 0.3529, -0.1321, 0.1097], [-0.0344, 0.2912, 0.1687, -0.0137, -0.3462, 0.3552, -0.1337, 0.1078], ], [ 47, [0.4397, 0.0550, 0.2873, 0.2946, 0.0567, 0.0855, -0.1580, 0.2531], [0.4397, 0.0550, 0.2873, 0.2946, 0.0567, 0.0855, -0.1580, 0.2531], ], # fmt: on ] ) def test_stable_diffusion_mode(self, seed, expected_slice, expected_slice_mps): model = self.get_sd_vae_model() image = self.get_sd_image(seed)
with torch.no_grad(): sample = model(image).sample
assert sample.shape == image.shape
output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)
@parameterized.expand( [ # fmt: off [13, [-0.0521, -0.2939, 0.1540, -0.1855, -0.5936, -0.3138, -0.4579, -0.2275]], [37, [-0.1820, -0.4345, -0.0455, -0.2923, -0.8035, -0.5089, -0.4795, -0.3106]], # fmt: on ] ) @require_torch_accelerator @skip_mps def test_stable_diffusion_decode(self, seed, expected_slice): model = self.get_sd_vae_model() encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))
with torch.no_grad(): sample = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
output_slice = sample[-1, -2:, :2, -2:].flatten().cpu() expected_output_slice = torch.tensor(expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=2e-3)
@parameterized.expand([(13,), (16,), (37,)]) @require_torch_gpu @unittest.skipIf( not is_xformers_available(), reason="xformers is not required when using PyTorch 2.0.", ) def test_stable_diffusion_decode_xformers_vs_2_0(self, seed): model = self.get_sd_vae_model() encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))
with torch.no_grad(): sample = model.decode(encoding).sample
model.enable_xformers_memory_efficient_attention() with torch.no_grad(): sample_2 = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
assert torch_all_close(sample, sample_2, atol=5e-2)
@parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def test_stable_diffusion_encode_sample(self, seed, expected_slice): model = self.get_sd_vae_model() image = self.get_sd_image(seed) generator = self.get_generator(seed)
with torch.no_grad(): dist = model.encode(image).latent_dist sample = dist.sample(generator=generator)
assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
output_slice = sample[0, -1, -3:, -3:].flatten().cpu() expected_output_slice = torch.tensor(expected_slice)
tolerance = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(output_slice, expected_output_slice, atol=tolerance)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import unittest
from diffusers import AutoencoderKLCosmos
from ...testing_utils import enable_full_determinism, floats_tensor, torch_devicefrom ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class AutoencoderKLCosmosTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase): model_class = AutoencoderKLCosmos main_input_name = "sample" base_precision = 1e-2
def get_autoencoder_kl_cosmos_config(self): return { "in_channels": 3, "out_channels": 3, "latent_channels": 4, "encoder_block_out_channels": (8, 8, 8, 8), "decode_block_out_channels": (8, 8, 8, 8), "attention_resolutions": (8,), "resolution": 64, "num_layers": 2, "patch_size": 4, "patch_type": "haar", "scaling_factor": 1.0, "spatial_compression_ratio": 4, "temporal_compression_ratio": 4, }
@property def dummy_input(self): batch_size = 2 num_frames = 9 num_channels = 3 height = 32 width = 32
image = floats_tensor((batch_size, num_channels, num_frames, height, width)).to(torch_device)
return {"sample": image}
@property def input_shape(self): return (3, 9, 32, 32)
@property def output_shape(self): return (3, 9, 32, 32)
def prepare_init_args_and_inputs_for_common(self): init_dict = self.get_autoencoder_kl_cosmos_config() inputs_dict = self.dummy_input return init_dict, inputs_dict
def test_gradient_checkpointing_is_applied(self): expected_set = { "CosmosEncoder3d", "CosmosDecoder3d", } super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
@unittest.skip("Not sure why this test fails. Investigate later.") def test_effective_gradient_checkpointing(self): pass
@unittest.skip("Unsupported test.") def test_forward_with_norm_groups(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import unittest
from diffusers import AutoencoderDC
from ...testing_utils import ( enable_full_determinism, floats_tensor, torch_device,)from ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class AutoencoderDCTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase): model_class = AutoencoderDC main_input_name = "sample" base_precision = 1e-2
def get_autoencoder_dc_config(self): return { "in_channels": 3, "latent_channels": 4, "attention_head_dim": 2, "encoder_block_types": ( "ResBlock", "EfficientViTBlock", ), "decoder_block_types": ( "ResBlock", "EfficientViTBlock", ), "encoder_block_out_channels": (8, 8), "decoder_block_out_channels": (8, 8), "encoder_qkv_multiscales": ((), (5,)), "decoder_qkv_multiscales": ((), (5,)), "encoder_layers_per_block": (1, 1), "decoder_layers_per_block": [1, 1], "downsample_block_type": "conv", "upsample_block_type": "interpolate", "decoder_norm_types": "rms_norm", "decoder_act_fns": "silu", "scaling_factor": 0.41407, }
@property def dummy_input(self): batch_size = 4 num_channels = 3 sizes = (32, 32)
image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
return {"sample": image}
@property def input_shape(self): return (3, 32, 32)
@property def output_shape(self): return (3, 32, 32)
def prepare_init_args_and_inputs_for_common(self): init_dict = self.get_autoencoder_dc_config() inputs_dict = self.dummy_input return init_dict, inputs_dict
@unittest.skip("AutoencoderDC does not support `norm_num_groups` because it does not use GroupNorm.") def test_forward_with_norm_groups(self): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import unittest
import torch
from diffusers import AutoencoderKLHunyuanVideofrom diffusers.models.autoencoders.autoencoder_kl_hunyuan_video import prepare_causal_attention_mask
from ...testing_utils import ( enable_full_determinism, floats_tensor, torch_device,)from ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class AutoencoderKLHunyuanVideoTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase): model_class = AutoencoderKLHunyuanVideo main_input_name = "sample" base_precision = 1e-2
def get_autoencoder_kl_hunyuan_video_config(self): return { "in_channels": 3, "out_channels": 3, "latent_channels": 4, "down_block_types": ( "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", "HunyuanVideoDownBlock3D", ), "up_block_types": ( "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", "HunyuanVideoUpBlock3D", ), "block_out_channels": (8, 8, 8, 8), "layers_per_block": 1, "act_fn": "silu", "norm_num_groups": 4, "scaling_factor": 0.476986, "spatial_compression_ratio": 8, "temporal_compression_ratio": 4, "mid_block_add_attention": True, }
@property def dummy_input(self): batch_size = 2 num_frames = 9 num_channels = 3 sizes = (16, 16)
image = floats_tensor((batch_size, num_channels, num_frames) + sizes).to(torch_device)
return {"sample": image}
@property def input_shape(self): return (3, 9, 16, 16)
@property def output_shape(self): return (3, 9, 16, 16)
def prepare_init_args_and_inputs_for_common(self): init_dict = self.get_autoencoder_kl_hunyuan_video_config() inputs_dict = self.dummy_input return init_dict, inputs_dict
def test_enable_disable_tiling(self): init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
torch.manual_seed(0) model = self.model_class(**init_dict).to(torch_device)
inputs_dict.update({"return_dict": False})
torch.manual_seed(0) output_without_tiling = model(**inputs_dict, generator=torch.manual_seed(0))[0]
torch.manual_seed(0) model.enable_tiling() output_with_tiling = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertLess( (output_without_tiling.detach().cpu().numpy() - output_with_tiling.detach().cpu().numpy()).max(), 0.5, "VAE tiling should not affect the inference results", )
torch.manual_seed(0) model.disable_tiling() output_without_tiling_2 = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertEqual( output_without_tiling.detach().cpu().numpy().all(), output_without_tiling_2.detach().cpu().numpy().all(), "Without tiling outputs should match with the outputs when tiling is manually disabled.", )
def test_enable_disable_slicing(self): init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
torch.manual_seed(0) model = self.model_class(**init_dict).to(torch_device)
inputs_dict.update({"return_dict": False})
torch.manual_seed(0) output_without_slicing = model(**inputs_dict, generator=torch.manual_seed(0))[0]
torch.manual_seed(0) model.enable_slicing() output_with_slicing = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertLess( (output_without_slicing.detach().cpu().numpy() - output_with_slicing.detach().cpu().numpy()).max(), 0.5, "VAE slicing should not affect the inference results", )
torch.manual_seed(0) model.disable_slicing() output_without_slicing_2 = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertEqual( output_without_slicing.detach().cpu().numpy().all(), output_without_slicing_2.detach().cpu().numpy().all(), "Without slicing outputs should match with the outputs when slicing is manually disabled.", )
def test_gradient_checkpointing_is_applied(self): expected_set = { "HunyuanVideoDecoder3D", "HunyuanVideoDownBlock3D", "HunyuanVideoEncoder3D", "HunyuanVideoMidBlock3D", "HunyuanVideoUpBlock3D", } super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
# We need to overwrite this test because the base test does not account length of down_block_types def test_forward_with_norm_groups(self): init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
init_dict["norm_num_groups"] = 16 init_dict["block_out_channels"] = (16, 16, 16, 16)
model = self.model_class(**init_dict) model.to(torch_device) model.eval()
with torch.no_grad(): output = model(**inputs_dict)
if isinstance(output, dict): output = output.to_tuple()[0]
self.assertIsNotNone(output) expected_shape = inputs_dict["sample"].shape self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
@unittest.skip("Unsupported test.") def test_outputs_equivalence(self): pass
def test_prepare_causal_attention_mask(self): def prepare_causal_attention_mask_orig( num_frames: int, height_width: int, dtype: torch.dtype, device: torch.device, batch_size: int = None ) -> torch.Tensor: seq_len = num_frames * height_width mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device) for i in range(seq_len): i_frame = i // height_width mask[i, : (i_frame + 1) * height_width] = 0 if batch_size is not None: mask = mask.unsqueeze(0).expand(batch_size, -1, -1) return mask
# test with some odd shapes original_mask = prepare_causal_attention_mask_orig( num_frames=31, height_width=111, dtype=torch.float32, device=torch_device ) new_mask = prepare_causal_attention_mask( num_frames=31, height_width=111, dtype=torch.float32, device=torch_device ) self.assertTrue( torch.allclose(original_mask, new_mask), "Causal attention mask should be the same", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468# coding=utf-8# Copyright 2025 HuggingFace Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import gcimport unittest
import torchfrom parameterized import parameterized
from diffusers import AutoencoderKLfrom diffusers.utils.import_utils import is_xformers_available
from ...testing_utils import ( backend_empty_cache, enable_full_determinism, floats_tensor, load_hf_numpy, require_torch_accelerator, require_torch_accelerator_with_fp16, require_torch_gpu, skip_mps, slow, torch_all_close, torch_device,)from ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class AutoencoderKLTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase): model_class = AutoencoderKL main_input_name = "sample" base_precision = 1e-2
def get_autoencoder_kl_config(self, block_out_channels=None, norm_num_groups=None): block_out_channels = block_out_channels or [2, 4] norm_num_groups = norm_num_groups or 2 init_dict = { "block_out_channels": block_out_channels, "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D"] * len(block_out_channels), "up_block_types": ["UpDecoderBlock2D"] * len(block_out_channels), "latent_channels": 4, "norm_num_groups": norm_num_groups, } return init_dict
@property def dummy_input(self): batch_size = 4 num_channels = 3 sizes = (32, 32)
image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
return {"sample": image}
@property def input_shape(self): return (3, 32, 32)
@property def output_shape(self): return (3, 32, 32)
def prepare_init_args_and_inputs_for_common(self): init_dict = self.get_autoencoder_kl_config() inputs_dict = self.dummy_input return init_dict, inputs_dict
def test_enable_disable_tiling(self): init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
torch.manual_seed(0) model = self.model_class(**init_dict).to(torch_device)
inputs_dict.update({"return_dict": False})
torch.manual_seed(0) output_without_tiling = model(**inputs_dict, generator=torch.manual_seed(0))[0]
torch.manual_seed(0) model.enable_tiling() output_with_tiling = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertLess( (output_without_tiling.detach().cpu().numpy() - output_with_tiling.detach().cpu().numpy()).max(), 0.5, "VAE tiling should not affect the inference results", )
torch.manual_seed(0) model.disable_tiling() output_without_tiling_2 = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertEqual( output_without_tiling.detach().cpu().numpy().all(), output_without_tiling_2.detach().cpu().numpy().all(), "Without tiling outputs should match with the outputs when tiling is manually disabled.", )
def test_enable_disable_slicing(self): init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
torch.manual_seed(0) model = self.model_class(**init_dict).to(torch_device)
inputs_dict.update({"return_dict": False})
torch.manual_seed(0) output_without_slicing = model(**inputs_dict, generator=torch.manual_seed(0))[0]
torch.manual_seed(0) model.enable_slicing() output_with_slicing = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertLess( (output_without_slicing.detach().cpu().numpy() - output_with_slicing.detach().cpu().numpy()).max(), 0.5, "VAE slicing should not affect the inference results", )
torch.manual_seed(0) model.disable_slicing() output_without_slicing_2 = model(**inputs_dict, generator=torch.manual_seed(0))[0]
self.assertEqual( output_without_slicing.detach().cpu().numpy().all(), output_without_slicing_2.detach().cpu().numpy().all(), "Without slicing outputs should match with the outputs when slicing is manually disabled.", )
def test_gradient_checkpointing_is_applied(self): expected_set = {"Decoder", "Encoder", "UNetMidBlock2D"} super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
def test_from_pretrained_hub(self): model, loading_info = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy", output_loading_info=True) self.assertIsNotNone(model) self.assertEqual(len(loading_info["missing_keys"]), 0)
model.to(torch_device) image = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def test_output_pretrained(self): model = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy") model = model.to(torch_device) model.eval()
# Keep generator on CPU for non-CUDA devices to compare outputs with CPU result tensors generator_device = "cpu" if not torch_device.startswith(torch_device) else torch_device if torch_device != "mps": generator = torch.Generator(device=generator_device).manual_seed(0) else: generator = torch.manual_seed(0)
image = torch.randn( 1, model.config.in_channels, model.config.sample_size, model.config.sample_size, generator=torch.manual_seed(0), ) image = image.to(torch_device) with torch.no_grad(): output = model(image, sample_posterior=True, generator=generator).sample
output_slice = output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": expected_output_slice = torch.tensor( [ -4.0078e-01, -3.8323e-04, -1.2681e-01, -1.1462e-01, 2.0095e-01, 1.0893e-01, -8.8247e-02, -3.0361e-01, -9.8644e-03, ] ) elif generator_device == "cpu": expected_output_slice = torch.tensor( [ -0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026, ] ) else: expected_output_slice = torch.tensor( [ -0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485, ] )
self.assertTrue(torch_all_close(output_slice, expected_output_slice, rtol=1e-2))
@slowclass AutoencoderKLIntegrationTests(unittest.TestCase): def get_file_format(self, seed, shape): return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"
def tearDown(self): # clean up the VRAM after each test super().tearDown() gc.collect() backend_empty_cache(torch_device)
def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False): dtype = torch.float16 if fp16 else torch.float32 image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype) return image
def get_sd_vae_model(self, model_id="CompVis/stable-diffusion-v1-4", fp16=False): revision = "fp16" if fp16 else None torch_dtype = torch.float16 if fp16 else torch.float32
model = AutoencoderKL.from_pretrained( model_id, subfolder="vae", torch_dtype=torch_dtype, revision=revision, ) model.to(torch_device)
return model
def get_generator(self, seed=0): generator_device = "cpu" if not torch_device.startswith(torch_device) else torch_device if torch_device != "mps": return torch.Generator(device=generator_device).manual_seed(seed) return torch.manual_seed(seed)
@parameterized.expand( [ # fmt: off [ 33, [-0.1556, 0.9848, -0.0410, -0.0642, -0.2685, 0.8381, -0.2004, -0.0700], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824], ], [ 47, [-0.2376, 0.1200, 0.1337, -0.4830, -0.2504, -0.0759, -0.0486, -0.4077], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131], ], # fmt: on ] ) def test_stable_diffusion(self, seed, expected_slice, expected_slice_mps): model = self.get_sd_vae_model() image = self.get_sd_image(seed) generator = self.get_generator(seed)
with torch.no_grad(): sample = model(image, generator=generator, sample_posterior=True).sample
assert sample.shape == image.shape
output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)
@parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_accelerator_with_fp16 def test_stable_diffusion_fp16(self, seed, expected_slice): model = self.get_sd_vae_model(fp16=True) image = self.get_sd_image(seed, fp16=True) generator = self.get_generator(seed)
with torch.no_grad(): sample = model(image, generator=generator, sample_posterior=True).sample
assert sample.shape == image.shape
output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu() expected_output_slice = torch.tensor(expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=1e-2)
@parameterized.expand( [ # fmt: off [ 33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824], ], [ 47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131], ], # fmt: on ] ) def test_stable_diffusion_mode(self, seed, expected_slice, expected_slice_mps): model = self.get_sd_vae_model() image = self.get_sd_image(seed)
with torch.no_grad(): sample = model(image).sample
assert sample.shape == image.shape
output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)
@parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_accelerator @skip_mps def test_stable_diffusion_decode(self, seed, expected_slice): model = self.get_sd_vae_model() encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))
with torch.no_grad(): sample = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
output_slice = sample[-1, -2:, :2, -2:].flatten().cpu() expected_output_slice = torch.tensor(expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)
@parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_accelerator_with_fp16 def test_stable_diffusion_decode_fp16(self, seed, expected_slice): model = self.get_sd_vae_model(fp16=True) encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64), fp16=True)
with torch.no_grad(): sample = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu() expected_output_slice = torch.tensor(expected_slice)
assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)
@parameterized.expand([(13,), (16,), (27,)]) @require_torch_gpu @unittest.skipIf( not is_xformers_available(), reason="xformers is not required when using PyTorch 2.0.", ) def test_stable_diffusion_decode_xformers_vs_2_0_fp16(self, seed): model = self.get_sd_vae_model(fp16=True) encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64), fp16=True)
with torch.no_grad(): sample = model.decode(encoding).sample
model.enable_xformers_memory_efficient_attention() with torch.no_grad(): sample_2 = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
assert torch_all_close(sample, sample_2, atol=1e-1)
@parameterized.expand([(13,), (16,), (37,)]) @require_torch_gpu @unittest.skipIf( not is_xformers_available(), reason="xformers is not required when using PyTorch 2.0.", ) def test_stable_diffusion_decode_xformers_vs_2_0(self, seed): model = self.get_sd_vae_model() encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))
with torch.no_grad(): sample = model.decode(encoding).sample
model.enable_xformers_memory_efficient_attention() with torch.no_grad(): sample_2 = model.decode(encoding).sample
assert list(sample.shape) == [3, 3, 512, 512]
assert torch_all_close(sample, sample_2, atol=1e-2)
@parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def test_stable_diffusion_encode_sample(self, seed, expected_slice): model = self.get_sd_vae_model() image = self.get_sd_image(seed) generator = self.get_generator(seed)
with torch.no_grad(): dist = model.encode(image).latent_dist sample = dist.sample(generator=generator)
assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
output_slice = sample[0, -1, -3:, -3:].flatten().cpu() expected_output_slice = torch.tensor(expected_slice)
tolerance = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(output_slice, expected_output_slice, atol=tolerance)exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.pyAdded+17
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/dynamic_modules_utils.pyAdded+507
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/export_utils.pyAdded+209
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/hub_utils.pyAdded+573
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/import_utils.pyAdded+962
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/loading_utils.pyAdded+210
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/logging.pyAdded+340
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/model_card_template.mdAdded+24
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/outputs.pyAdded+138
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/peft_utils.pyAdded+376
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/pil_utils.pyAdded+67
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/remote_utils.pyAdded+425
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/source_code_parsing_utils.pyAdded+52
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/state_dict_utils.pyAdded+366
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/testing_utils.pyAdded+1601
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/torch_utils.pyAdded+334
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/typing_utils.pyAdded+91
exp_code/1_benchmark/diffusers-WanS2V/src/diffusers/utils/versions.pyAdded+117
exp_code/1_benchmark/diffusers-WanS2V/tests/__init__.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/conftest.pyAdded+48
exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/custom_pipeline/pipeline.pyAdded+102
exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/custom_pipeline/what_ever.pyAdded+103
exp_code/1_benchmark/diffusers-WanS2V/tests/fixtures/elise_format0.midAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/__init__.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/test_group_offloading.pyAdded+364
exp_code/1_benchmark/diffusers-WanS2V/tests/hooks/test_hooks.pyAdded+377
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/__init__.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_auraflow.pyAdded+137
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_cogvideox.pyAdded+174
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_cogview4.pyAdded+189
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_flux.pyAdded+1054
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_hunyuanvideo.pyAdded+264
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_ltx_video.pyAdded+148
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_lumina2.pyAdded+173
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_mochi.pyAdded+143
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_qwenimage.pyAdded+130
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sana.pyAdded+139
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sd.pyAdded+769
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sd3.pyAdded+191
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_sdxl.pyAdded+681
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_wan.pyAdded+144
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/test_lora_layers_wanvace.pyAdded+217
exp_code/1_benchmark/diffusers-WanS2V/tests/lora/utils.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/models/__init__.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/__init__.pyAdded
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_asymmetric_autoencoder_kl.pyAdded+276
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_cosmos.pyAdded+86
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_dc.pyAdded+87
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_hunyuan_video.pyAdded+210
exp_code/1_benchmark/diffusers-WanS2V/tests/models/autoencoders/test_models_autoencoder_kl.pyAdded+468