JOY-Huang commited on
Commit
62c110b
·
1 Parent(s): 9f954a0

add local diffusers

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. diffusers/commands/diffusers_cli.py +43 -0
  2. diffusers/commands/env.py +84 -0
  3. diffusers/commands/fp16_safetensors.py +132 -0
  4. diffusers/configuration_utils.py +704 -0
  5. diffusers/dependency_versions_check.py +34 -0
  6. diffusers/dependency_versions_table.py +46 -0
  7. diffusers/experimental/README.md +5 -0
  8. diffusers/experimental/rl/value_guided_sampling.py +153 -0
  9. diffusers/image_processor.py +1070 -0
  10. diffusers/loaders/autoencoder.py +146 -0
  11. diffusers/loaders/controlnet.py +136 -0
  12. diffusers/loaders/ip_adapter.py +339 -0
  13. diffusers/loaders/lora.py +1458 -0
  14. diffusers/loaders/lora_conversion_utils.py +287 -0
  15. diffusers/loaders/peft.py +187 -0
  16. diffusers/loaders/single_file.py +323 -0
  17. diffusers/loaders/single_file_utils.py +1609 -0
  18. diffusers/loaders/textual_inversion.py +582 -0
  19. diffusers/loaders/unet.py +1161 -0
  20. diffusers/loaders/unet_loader_utils.py +163 -0
  21. diffusers/loaders/utils.py +59 -0
  22. diffusers/models/README.md +3 -0
  23. diffusers/models/activations.py +131 -0
  24. diffusers/models/adapter.py +584 -0
  25. diffusers/models/attention.py +678 -0
  26. diffusers/models/attention_flax.py +494 -0
  27. diffusers/models/attention_processor.py +0 -0
  28. diffusers/models/autoencoders/autoencoder_asym_kl.py +186 -0
  29. diffusers/models/autoencoders/autoencoder_kl.py +490 -0
  30. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +399 -0
  31. diffusers/models/autoencoders/autoencoder_tiny.py +349 -0
  32. diffusers/models/autoencoders/consistency_decoder_vae.py +462 -0
  33. diffusers/models/autoencoders/vae.py +981 -0
  34. diffusers/models/controlnet.py +907 -0
  35. diffusers/models/controlnet_flax.py +395 -0
  36. diffusers/models/controlnet_xs.py +1915 -0
  37. diffusers/models/downsampling.py +333 -0
  38. diffusers/models/dual_transformer_2d.py +20 -0
  39. diffusers/models/embeddings.py +1037 -0
  40. diffusers/models/embeddings_flax.py +97 -0
  41. diffusers/models/lora.py +457 -0
  42. diffusers/models/modeling_flax_pytorch_utils.py +135 -0
  43. diffusers/models/modeling_flax_utils.py +566 -0
  44. diffusers/models/modeling_outputs.py +17 -0
  45. diffusers/models/modeling_pytorch_flax_utils.py +161 -0
  46. diffusers/models/modeling_utils.py +1141 -0
  47. diffusers/models/normalization.py +254 -0
  48. diffusers/models/prior_transformer.py +12 -0
  49. diffusers/models/resnet.py +797 -0
  50. diffusers/models/resnet_flax.py +124 -0
diffusers/commands/diffusers_cli.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from argparse import ArgumentParser
17
+
18
+ from .env import EnvironmentCommand
19
+ from .fp16_safetensors import FP16SafetensorsCommand
20
+
21
+
22
+ def main():
23
+ parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
24
+ commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
25
+
26
+ # Register commands
27
+ EnvironmentCommand.register_subcommand(commands_parser)
28
+ FP16SafetensorsCommand.register_subcommand(commands_parser)
29
+
30
+ # Let's go
31
+ args = parser.parse_args()
32
+
33
+ if not hasattr(args, "func"):
34
+ parser.print_help()
35
+ exit(1)
36
+
37
+ # Run
38
+ service = args.func(args)
39
+ service.run()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
diffusers/commands/env.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import platform
16
+ from argparse import ArgumentParser
17
+
18
+ import huggingface_hub
19
+
20
+ from .. import __version__ as version
21
+ from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
22
+ from . import BaseDiffusersCLICommand
23
+
24
+
25
+ def info_command_factory(_):
26
+ return EnvironmentCommand()
27
+
28
+
29
+ class EnvironmentCommand(BaseDiffusersCLICommand):
30
+ @staticmethod
31
+ def register_subcommand(parser: ArgumentParser):
32
+ download_parser = parser.add_parser("env")
33
+ download_parser.set_defaults(func=info_command_factory)
34
+
35
+ def run(self):
36
+ hub_version = huggingface_hub.__version__
37
+
38
+ pt_version = "not installed"
39
+ pt_cuda_available = "NA"
40
+ if is_torch_available():
41
+ import torch
42
+
43
+ pt_version = torch.__version__
44
+ pt_cuda_available = torch.cuda.is_available()
45
+
46
+ transformers_version = "not installed"
47
+ if is_transformers_available():
48
+ import transformers
49
+
50
+ transformers_version = transformers.__version__
51
+
52
+ accelerate_version = "not installed"
53
+ if is_accelerate_available():
54
+ import accelerate
55
+
56
+ accelerate_version = accelerate.__version__
57
+
58
+ xformers_version = "not installed"
59
+ if is_xformers_available():
60
+ import xformers
61
+
62
+ xformers_version = xformers.__version__
63
+
64
+ info = {
65
+ "`diffusers` version": version,
66
+ "Platform": platform.platform(),
67
+ "Python version": platform.python_version(),
68
+ "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
69
+ "Huggingface_hub version": hub_version,
70
+ "Transformers version": transformers_version,
71
+ "Accelerate version": accelerate_version,
72
+ "xFormers version": xformers_version,
73
+ "Using GPU in script?": "<fill in>",
74
+ "Using distributed or parallel set-up in script?": "<fill in>",
75
+ }
76
+
77
+ print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
78
+ print(self.format_dict(info))
79
+
80
+ return info
81
+
82
+ @staticmethod
83
+ def format_dict(d):
84
+ return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
diffusers/commands/fp16_safetensors.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Usage example:
17
+ diffusers-cli fp16_safetensors --ckpt_id=openai/shap-e --fp16 --use_safetensors
18
+ """
19
+
20
+ import glob
21
+ import json
22
+ import warnings
23
+ from argparse import ArgumentParser, Namespace
24
+ from importlib import import_module
25
+
26
+ import huggingface_hub
27
+ import torch
28
+ from huggingface_hub import hf_hub_download
29
+ from packaging import version
30
+
31
+ from ..utils import logging
32
+ from . import BaseDiffusersCLICommand
33
+
34
+
35
+ def conversion_command_factory(args: Namespace):
36
+ if args.use_auth_token:
37
+ warnings.warn(
38
+ "The `--use_auth_token` flag is deprecated and will be removed in a future version. Authentication is now"
39
+ " handled automatically if user is logged in."
40
+ )
41
+ return FP16SafetensorsCommand(args.ckpt_id, args.fp16, args.use_safetensors)
42
+
43
+
44
+ class FP16SafetensorsCommand(BaseDiffusersCLICommand):
45
+ @staticmethod
46
+ def register_subcommand(parser: ArgumentParser):
47
+ conversion_parser = parser.add_parser("fp16_safetensors")
48
+ conversion_parser.add_argument(
49
+ "--ckpt_id",
50
+ type=str,
51
+ help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
52
+ )
53
+ conversion_parser.add_argument(
54
+ "--fp16", action="store_true", help="If serializing the variables in FP16 precision."
55
+ )
56
+ conversion_parser.add_argument(
57
+ "--use_safetensors", action="store_true", help="If serializing in the safetensors format."
58
+ )
59
+ conversion_parser.add_argument(
60
+ "--use_auth_token",
61
+ action="store_true",
62
+ help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
63
+ )
64
+ conversion_parser.set_defaults(func=conversion_command_factory)
65
+
66
+ def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool):
67
+ self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
68
+ self.ckpt_id = ckpt_id
69
+ self.local_ckpt_dir = f"/tmp/{ckpt_id}"
70
+ self.fp16 = fp16
71
+
72
+ self.use_safetensors = use_safetensors
73
+
74
+ if not self.use_safetensors and not self.fp16:
75
+ raise NotImplementedError(
76
+ "When `use_safetensors` and `fp16` both are False, then this command is of no use."
77
+ )
78
+
79
+ def run(self):
80
+ if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
81
+ raise ImportError(
82
+ "The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
83
+ " installation."
84
+ )
85
+ else:
86
+ from huggingface_hub import create_commit
87
+ from huggingface_hub._commit_api import CommitOperationAdd
88
+
89
+ model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json")
90
+ with open(model_index, "r") as f:
91
+ pipeline_class_name = json.load(f)["_class_name"]
92
+ pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
93
+ self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
94
+
95
+ # Load the appropriate pipeline. We could have use `DiffusionPipeline`
96
+ # here, but just to avoid any rough edge cases.
97
+ pipeline = pipeline_class.from_pretrained(
98
+ self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32
99
+ )
100
+ pipeline.save_pretrained(
101
+ self.local_ckpt_dir,
102
+ safe_serialization=True if self.use_safetensors else False,
103
+ variant="fp16" if self.fp16 else None,
104
+ )
105
+ self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
106
+
107
+ # Fetch all the paths.
108
+ if self.fp16:
109
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
110
+ elif self.use_safetensors:
111
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
112
+
113
+ # Prepare for the PR.
114
+ commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
115
+ operations = []
116
+ for path in modified_paths:
117
+ operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
118
+
119
+ # Open the PR.
120
+ commit_description = (
121
+ "Variables converted by the [`diffusers`' `fp16_safetensors`"
122
+ " CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
123
+ )
124
+ hub_pr_url = create_commit(
125
+ repo_id=self.ckpt_id,
126
+ operations=operations,
127
+ commit_message=commit_message,
128
+ commit_description=commit_description,
129
+ repo_type="model",
130
+ create_pr=True,
131
+ ).pr_url
132
+ self.logger.info(f"PR created here: {hub_pr_url}.")
diffusers/configuration_utils.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ConfigMixin base class and utilities."""
17
+
18
+ import dataclasses
19
+ import functools
20
+ import importlib
21
+ import inspect
22
+ import json
23
+ import os
24
+ import re
25
+ from collections import OrderedDict
26
+ from pathlib import PosixPath
27
+ from typing import Any, Dict, Tuple, Union
28
+
29
+ import numpy as np
30
+ from huggingface_hub import create_repo, hf_hub_download
31
+ from huggingface_hub.utils import (
32
+ EntryNotFoundError,
33
+ RepositoryNotFoundError,
34
+ RevisionNotFoundError,
35
+ validate_hf_hub_args,
36
+ )
37
+ from requests import HTTPError
38
+
39
+ from . import __version__
40
+ from .utils import (
41
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
42
+ DummyObject,
43
+ deprecate,
44
+ extract_commit_hash,
45
+ http_user_agent,
46
+ logging,
47
+ )
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _re_configuration_file = re.compile(r"config\.(.*)\.json")
53
+
54
+
55
+ class FrozenDict(OrderedDict):
56
+ def __init__(self, *args, **kwargs):
57
+ super().__init__(*args, **kwargs)
58
+
59
+ for key, value in self.items():
60
+ setattr(self, key, value)
61
+
62
+ self.__frozen = True
63
+
64
+ def __delitem__(self, *args, **kwargs):
65
+ raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
66
+
67
+ def setdefault(self, *args, **kwargs):
68
+ raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
69
+
70
+ def pop(self, *args, **kwargs):
71
+ raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
72
+
73
+ def update(self, *args, **kwargs):
74
+ raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
75
+
76
+ def __setattr__(self, name, value):
77
+ if hasattr(self, "__frozen") and self.__frozen:
78
+ raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
79
+ super().__setattr__(name, value)
80
+
81
+ def __setitem__(self, name, value):
82
+ if hasattr(self, "__frozen") and self.__frozen:
83
+ raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
84
+ super().__setitem__(name, value)
85
+
86
+
87
+ class ConfigMixin:
88
+ r"""
89
+ Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
90
+ provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
91
+ saving classes that inherit from [`ConfigMixin`].
92
+
93
+ Class attributes:
94
+ - **config_name** (`str`) -- A filename under which the config should stored when calling
95
+ [`~ConfigMixin.save_config`] (should be overridden by parent class).
96
+ - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
97
+ overridden by subclass).
98
+ - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
99
+ - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
100
+ should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
101
+ subclass).
102
+ """
103
+
104
+ config_name = None
105
+ ignore_for_config = []
106
+ has_compatibles = False
107
+
108
+ _deprecated_kwargs = []
109
+
110
+ def register_to_config(self, **kwargs):
111
+ if self.config_name is None:
112
+ raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
113
+ # Special case for `kwargs` used in deprecation warning added to schedulers
114
+ # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
115
+ # or solve in a more general way.
116
+ kwargs.pop("kwargs", None)
117
+
118
+ if not hasattr(self, "_internal_dict"):
119
+ internal_dict = kwargs
120
+ else:
121
+ previous_dict = dict(self._internal_dict)
122
+ internal_dict = {**self._internal_dict, **kwargs}
123
+ logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
124
+
125
+ self._internal_dict = FrozenDict(internal_dict)
126
+
127
+ def __getattr__(self, name: str) -> Any:
128
+ """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
129
+ config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
130
+
131
+ This function is mostly copied from PyTorch's __getattr__ overwrite:
132
+ https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
133
+ """
134
+
135
+ is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
136
+ is_attribute = name in self.__dict__
137
+
138
+ if is_in_config and not is_attribute:
139
+ deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'."
140
+ deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
141
+ return self._internal_dict[name]
142
+
143
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
144
+
145
+ def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
146
+ """
147
+ Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
148
+ [`~ConfigMixin.from_config`] class method.
149
+
150
+ Args:
151
+ save_directory (`str` or `os.PathLike`):
152
+ Directory where the configuration JSON file is saved (will be created if it does not exist).
153
+ push_to_hub (`bool`, *optional*, defaults to `False`):
154
+ Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
155
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
156
+ namespace).
157
+ kwargs (`Dict[str, Any]`, *optional*):
158
+ Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
159
+ """
160
+ if os.path.isfile(save_directory):
161
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
162
+
163
+ os.makedirs(save_directory, exist_ok=True)
164
+
165
+ # If we save using the predefined names, we can load using `from_config`
166
+ output_config_file = os.path.join(save_directory, self.config_name)
167
+
168
+ self.to_json_file(output_config_file)
169
+ logger.info(f"Configuration saved in {output_config_file}")
170
+
171
+ if push_to_hub:
172
+ commit_message = kwargs.pop("commit_message", None)
173
+ private = kwargs.pop("private", False)
174
+ create_pr = kwargs.pop("create_pr", False)
175
+ token = kwargs.pop("token", None)
176
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
177
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
178
+
179
+ self._upload_folder(
180
+ save_directory,
181
+ repo_id,
182
+ token=token,
183
+ commit_message=commit_message,
184
+ create_pr=create_pr,
185
+ )
186
+
187
+ @classmethod
188
+ def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
189
+ r"""
190
+ Instantiate a Python class from a config dictionary.
191
+
192
+ Parameters:
193
+ config (`Dict[str, Any]`):
194
+ A config dictionary from which the Python class is instantiated. Make sure to only load configuration
195
+ files of compatible classes.
196
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
197
+ Whether kwargs that are not consumed by the Python class should be returned or not.
198
+ kwargs (remaining dictionary of keyword arguments, *optional*):
199
+ Can be used to update the configuration object (after it is loaded) and initiate the Python class.
200
+ `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
201
+ overwrite the same named arguments in `config`.
202
+
203
+ Returns:
204
+ [`ModelMixin`] or [`SchedulerMixin`]:
205
+ A model or scheduler object instantiated from a config dictionary.
206
+
207
+ Examples:
208
+
209
+ ```python
210
+ >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
211
+
212
+ >>> # Download scheduler from huggingface.co and cache.
213
+ >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
214
+
215
+ >>> # Instantiate DDIM scheduler class with same config as DDPM
216
+ >>> scheduler = DDIMScheduler.from_config(scheduler.config)
217
+
218
+ >>> # Instantiate PNDM scheduler class with same config as DDPM
219
+ >>> scheduler = PNDMScheduler.from_config(scheduler.config)
220
+ ```
221
+ """
222
+ # <===== TO BE REMOVED WITH DEPRECATION
223
+ # TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
224
+ if "pretrained_model_name_or_path" in kwargs:
225
+ config = kwargs.pop("pretrained_model_name_or_path")
226
+
227
+ if config is None:
228
+ raise ValueError("Please make sure to provide a config as the first positional argument.")
229
+ # ======>
230
+
231
+ if not isinstance(config, dict):
232
+ deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
233
+ if "Scheduler" in cls.__name__:
234
+ deprecation_message += (
235
+ f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
236
+ " Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
237
+ " be removed in v1.0.0."
238
+ )
239
+ elif "Model" in cls.__name__:
240
+ deprecation_message += (
241
+ f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
242
+ f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
243
+ " instead. This functionality will be removed in v1.0.0."
244
+ )
245
+ deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
246
+ config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
247
+
248
+ init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
249
+
250
+ # Allow dtype to be specified on initialization
251
+ if "dtype" in unused_kwargs:
252
+ init_dict["dtype"] = unused_kwargs.pop("dtype")
253
+
254
+ # add possible deprecated kwargs
255
+ for deprecated_kwarg in cls._deprecated_kwargs:
256
+ if deprecated_kwarg in unused_kwargs:
257
+ init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
258
+
259
+ # Return model and optionally state and/or unused_kwargs
260
+ model = cls(**init_dict)
261
+
262
+ # make sure to also save config parameters that might be used for compatible classes
263
+ # update _class_name
264
+ if "_class_name" in hidden_dict:
265
+ hidden_dict["_class_name"] = cls.__name__
266
+
267
+ model.register_to_config(**hidden_dict)
268
+
269
+ # add hidden kwargs of compatible classes to unused_kwargs
270
+ unused_kwargs = {**unused_kwargs, **hidden_dict}
271
+
272
+ if return_unused_kwargs:
273
+ return (model, unused_kwargs)
274
+ else:
275
+ return model
276
+
277
+ @classmethod
278
+ def get_config_dict(cls, *args, **kwargs):
279
+ deprecation_message = (
280
+ f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
281
+ " removed in version v1.0.0"
282
+ )
283
+ deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
284
+ return cls.load_config(*args, **kwargs)
285
+
286
+ @classmethod
287
+ @validate_hf_hub_args
288
+ def load_config(
289
+ cls,
290
+ pretrained_model_name_or_path: Union[str, os.PathLike],
291
+ return_unused_kwargs=False,
292
+ return_commit_hash=False,
293
+ **kwargs,
294
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
295
+ r"""
296
+ Load a model or scheduler configuration.
297
+
298
+ Parameters:
299
+ pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
300
+ Can be either:
301
+
302
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
303
+ the Hub.
304
+ - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
305
+ [`~ConfigMixin.save_config`].
306
+
307
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
308
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
309
+ is not used.
310
+ force_download (`bool`, *optional*, defaults to `False`):
311
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
312
+ cached versions if they exist.
313
+ resume_download:
314
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
315
+ of Diffusers.
316
+ proxies (`Dict[str, str]`, *optional*):
317
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
318
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
319
+ output_loading_info(`bool`, *optional*, defaults to `False`):
320
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
321
+ local_files_only (`bool`, *optional*, defaults to `False`):
322
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
323
+ won't be downloaded from the Hub.
324
+ token (`str` or *bool*, *optional*):
325
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
326
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
327
+ revision (`str`, *optional*, defaults to `"main"`):
328
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
329
+ allowed by Git.
330
+ subfolder (`str`, *optional*, defaults to `""`):
331
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
332
+ return_unused_kwargs (`bool`, *optional*, defaults to `False):
333
+ Whether unused keyword arguments of the config are returned.
334
+ return_commit_hash (`bool`, *optional*, defaults to `False):
335
+ Whether the `commit_hash` of the loaded configuration are returned.
336
+
337
+ Returns:
338
+ `dict`:
339
+ A dictionary of all the parameters stored in a JSON configuration file.
340
+
341
+ """
342
+ cache_dir = kwargs.pop("cache_dir", None)
343
+ force_download = kwargs.pop("force_download", False)
344
+ resume_download = kwargs.pop("resume_download", None)
345
+ proxies = kwargs.pop("proxies", None)
346
+ token = kwargs.pop("token", None)
347
+ local_files_only = kwargs.pop("local_files_only", False)
348
+ revision = kwargs.pop("revision", None)
349
+ _ = kwargs.pop("mirror", None)
350
+ subfolder = kwargs.pop("subfolder", None)
351
+ user_agent = kwargs.pop("user_agent", {})
352
+
353
+ user_agent = {**user_agent, "file_type": "config"}
354
+ user_agent = http_user_agent(user_agent)
355
+
356
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
357
+
358
+ if cls.config_name is None:
359
+ raise ValueError(
360
+ "`self.config_name` is not defined. Note that one should not load a config from "
361
+ "`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
362
+ )
363
+
364
+ if os.path.isfile(pretrained_model_name_or_path):
365
+ config_file = pretrained_model_name_or_path
366
+ elif os.path.isdir(pretrained_model_name_or_path):
367
+ if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
368
+ # Load from a PyTorch checkpoint
369
+ config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
370
+ elif subfolder is not None and os.path.isfile(
371
+ os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
372
+ ):
373
+ config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
374
+ else:
375
+ raise EnvironmentError(
376
+ f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
377
+ )
378
+ else:
379
+ try:
380
+ # Load from URL or cache if already cached
381
+ config_file = hf_hub_download(
382
+ pretrained_model_name_or_path,
383
+ filename=cls.config_name,
384
+ cache_dir=cache_dir,
385
+ force_download=force_download,
386
+ proxies=proxies,
387
+ resume_download=resume_download,
388
+ local_files_only=local_files_only,
389
+ token=token,
390
+ user_agent=user_agent,
391
+ subfolder=subfolder,
392
+ revision=revision,
393
+ )
394
+ except RepositoryNotFoundError:
395
+ raise EnvironmentError(
396
+ f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
397
+ " listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
398
+ " token having permission to this repo with `token` or log in with `huggingface-cli login`."
399
+ )
400
+ except RevisionNotFoundError:
401
+ raise EnvironmentError(
402
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
403
+ " this model name. Check the model page at"
404
+ f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
405
+ )
406
+ except EntryNotFoundError:
407
+ raise EnvironmentError(
408
+ f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
409
+ )
410
+ except HTTPError as err:
411
+ raise EnvironmentError(
412
+ "There was a specific connection error when trying to load"
413
+ f" {pretrained_model_name_or_path}:\n{err}"
414
+ )
415
+ except ValueError:
416
+ raise EnvironmentError(
417
+ f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
418
+ f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
419
+ f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
420
+ " run the library in offline mode at"
421
+ " 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
422
+ )
423
+ except EnvironmentError:
424
+ raise EnvironmentError(
425
+ f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
426
+ "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
427
+ f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
428
+ f"containing a {cls.config_name} file"
429
+ )
430
+
431
+ try:
432
+ # Load config dict
433
+ config_dict = cls._dict_from_json_file(config_file)
434
+
435
+ commit_hash = extract_commit_hash(config_file)
436
+ except (json.JSONDecodeError, UnicodeDecodeError):
437
+ raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
438
+
439
+ if not (return_unused_kwargs or return_commit_hash):
440
+ return config_dict
441
+
442
+ outputs = (config_dict,)
443
+
444
+ if return_unused_kwargs:
445
+ outputs += (kwargs,)
446
+
447
+ if return_commit_hash:
448
+ outputs += (commit_hash,)
449
+
450
+ return outputs
451
+
452
+ @staticmethod
453
+ def _get_init_keys(input_class):
454
+ return set(dict(inspect.signature(input_class.__init__).parameters).keys())
455
+
456
+ @classmethod
457
+ def extract_init_dict(cls, config_dict, **kwargs):
458
+ # Skip keys that were not present in the original config, so default __init__ values were used
459
+ used_defaults = config_dict.get("_use_default_values", [])
460
+ config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
461
+
462
+ # 0. Copy origin config dict
463
+ original_dict = dict(config_dict.items())
464
+
465
+ # 1. Retrieve expected config attributes from __init__ signature
466
+ expected_keys = cls._get_init_keys(cls)
467
+ expected_keys.remove("self")
468
+ # remove general kwargs if present in dict
469
+ if "kwargs" in expected_keys:
470
+ expected_keys.remove("kwargs")
471
+ # remove flax internal keys
472
+ if hasattr(cls, "_flax_internal_args"):
473
+ for arg in cls._flax_internal_args:
474
+ expected_keys.remove(arg)
475
+
476
+ # 2. Remove attributes that cannot be expected from expected config attributes
477
+ # remove keys to be ignored
478
+ if len(cls.ignore_for_config) > 0:
479
+ expected_keys = expected_keys - set(cls.ignore_for_config)
480
+
481
+ # load diffusers library to import compatible and original scheduler
482
+ diffusers_library = importlib.import_module(__name__.split(".")[0])
483
+
484
+ if cls.has_compatibles:
485
+ compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
486
+ else:
487
+ compatible_classes = []
488
+
489
+ expected_keys_comp_cls = set()
490
+ for c in compatible_classes:
491
+ expected_keys_c = cls._get_init_keys(c)
492
+ expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
493
+ expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
494
+ config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
495
+
496
+ # remove attributes from orig class that cannot be expected
497
+ orig_cls_name = config_dict.pop("_class_name", cls.__name__)
498
+ if (
499
+ isinstance(orig_cls_name, str)
500
+ and orig_cls_name != cls.__name__
501
+ and hasattr(diffusers_library, orig_cls_name)
502
+ ):
503
+ orig_cls = getattr(diffusers_library, orig_cls_name)
504
+ unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
505
+ config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
506
+ elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
507
+ raise ValueError(
508
+ "Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
509
+ )
510
+
511
+ # remove private attributes
512
+ config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
513
+
514
+ # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
515
+ init_dict = {}
516
+ for key in expected_keys:
517
+ # if config param is passed to kwarg and is present in config dict
518
+ # it should overwrite existing config dict key
519
+ if key in kwargs and key in config_dict:
520
+ config_dict[key] = kwargs.pop(key)
521
+
522
+ if key in kwargs:
523
+ # overwrite key
524
+ init_dict[key] = kwargs.pop(key)
525
+ elif key in config_dict:
526
+ # use value from config dict
527
+ init_dict[key] = config_dict.pop(key)
528
+
529
+ # 4. Give nice warning if unexpected values have been passed
530
+ if len(config_dict) > 0:
531
+ logger.warning(
532
+ f"The config attributes {config_dict} were passed to {cls.__name__}, "
533
+ "but are not expected and will be ignored. Please verify your "
534
+ f"{cls.config_name} configuration file."
535
+ )
536
+
537
+ # 5. Give nice info if config attributes are initialized to default because they have not been passed
538
+ passed_keys = set(init_dict.keys())
539
+ if len(expected_keys - passed_keys) > 0:
540
+ logger.info(
541
+ f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
542
+ )
543
+
544
+ # 6. Define unused keyword arguments
545
+ unused_kwargs = {**config_dict, **kwargs}
546
+
547
+ # 7. Define "hidden" config parameters that were saved for compatible classes
548
+ hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
549
+
550
+ return init_dict, unused_kwargs, hidden_config_dict
551
+
552
+ @classmethod
553
+ def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
554
+ with open(json_file, "r", encoding="utf-8") as reader:
555
+ text = reader.read()
556
+ return json.loads(text)
557
+
558
+ def __repr__(self):
559
+ return f"{self.__class__.__name__} {self.to_json_string()}"
560
+
561
+ @property
562
+ def config(self) -> Dict[str, Any]:
563
+ """
564
+ Returns the config of the class as a frozen dictionary
565
+
566
+ Returns:
567
+ `Dict[str, Any]`: Config of the class.
568
+ """
569
+ return self._internal_dict
570
+
571
+ def to_json_string(self) -> str:
572
+ """
573
+ Serializes the configuration instance to a JSON string.
574
+
575
+ Returns:
576
+ `str`:
577
+ String containing all the attributes that make up the configuration instance in JSON format.
578
+ """
579
+ config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
580
+ config_dict["_class_name"] = self.__class__.__name__
581
+ config_dict["_diffusers_version"] = __version__
582
+
583
+ def to_json_saveable(value):
584
+ if isinstance(value, np.ndarray):
585
+ value = value.tolist()
586
+ elif isinstance(value, PosixPath):
587
+ value = str(value)
588
+ return value
589
+
590
+ config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
591
+ # Don't save "_ignore_files" or "_use_default_values"
592
+ config_dict.pop("_ignore_files", None)
593
+ config_dict.pop("_use_default_values", None)
594
+
595
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
596
+
597
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
598
+ """
599
+ Save the configuration instance's parameters to a JSON file.
600
+
601
+ Args:
602
+ json_file_path (`str` or `os.PathLike`):
603
+ Path to the JSON file to save a configuration instance's parameters.
604
+ """
605
+ with open(json_file_path, "w", encoding="utf-8") as writer:
606
+ writer.write(self.to_json_string())
607
+
608
+
609
+ def register_to_config(init):
610
+ r"""
611
+ Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
612
+ automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
613
+ shouldn't be registered in the config, use the `ignore_for_config` class variable
614
+
615
+ Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
616
+ """
617
+
618
+ @functools.wraps(init)
619
+ def inner_init(self, *args, **kwargs):
620
+ # Ignore private kwargs in the init.
621
+ init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
622
+ config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
623
+ if not isinstance(self, ConfigMixin):
624
+ raise RuntimeError(
625
+ f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
626
+ "not inherit from `ConfigMixin`."
627
+ )
628
+
629
+ ignore = getattr(self, "ignore_for_config", [])
630
+ # Get positional arguments aligned with kwargs
631
+ new_kwargs = {}
632
+ signature = inspect.signature(init)
633
+ parameters = {
634
+ name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
635
+ }
636
+ for arg, name in zip(args, parameters.keys()):
637
+ new_kwargs[name] = arg
638
+
639
+ # Then add all kwargs
640
+ new_kwargs.update(
641
+ {
642
+ k: init_kwargs.get(k, default)
643
+ for k, default in parameters.items()
644
+ if k not in ignore and k not in new_kwargs
645
+ }
646
+ )
647
+
648
+ # Take note of the parameters that were not present in the loaded config
649
+ if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
650
+ new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
651
+
652
+ new_kwargs = {**config_init_kwargs, **new_kwargs}
653
+ getattr(self, "register_to_config")(**new_kwargs)
654
+ init(self, *args, **init_kwargs)
655
+
656
+ return inner_init
657
+
658
+
659
+ def flax_register_to_config(cls):
660
+ original_init = cls.__init__
661
+
662
+ @functools.wraps(original_init)
663
+ def init(self, *args, **kwargs):
664
+ if not isinstance(self, ConfigMixin):
665
+ raise RuntimeError(
666
+ f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
667
+ "not inherit from `ConfigMixin`."
668
+ )
669
+
670
+ # Ignore private kwargs in the init. Retrieve all passed attributes
671
+ init_kwargs = dict(kwargs.items())
672
+
673
+ # Retrieve default values
674
+ fields = dataclasses.fields(self)
675
+ default_kwargs = {}
676
+ for field in fields:
677
+ # ignore flax specific attributes
678
+ if field.name in self._flax_internal_args:
679
+ continue
680
+ if type(field.default) == dataclasses._MISSING_TYPE:
681
+ default_kwargs[field.name] = None
682
+ else:
683
+ default_kwargs[field.name] = getattr(self, field.name)
684
+
685
+ # Make sure init_kwargs override default kwargs
686
+ new_kwargs = {**default_kwargs, **init_kwargs}
687
+ # dtype should be part of `init_kwargs`, but not `new_kwargs`
688
+ if "dtype" in new_kwargs:
689
+ new_kwargs.pop("dtype")
690
+
691
+ # Get positional arguments aligned with kwargs
692
+ for i, arg in enumerate(args):
693
+ name = fields[i].name
694
+ new_kwargs[name] = arg
695
+
696
+ # Take note of the parameters that were not present in the loaded config
697
+ if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
698
+ new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
699
+
700
+ getattr(self, "register_to_config")(**new_kwargs)
701
+ original_init(self, *args, **kwargs)
702
+
703
+ cls.__init__ = init
704
+ return cls
diffusers/dependency_versions_check.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .dependency_versions_table import deps
16
+ from .utils.versions import require_version, require_version_core
17
+
18
+
19
+ # define which module versions we always want to check at run time
20
+ # (usually the ones defined in `install_requires` in setup.py)
21
+ #
22
+ # order specific notes:
23
+ # - tqdm must be checked before tokenizers
24
+
25
+ pkgs_to_check_at_runtime = "python requests filelock numpy".split()
26
+ for pkg in pkgs_to_check_at_runtime:
27
+ if pkg in deps:
28
+ require_version_core(deps[pkg])
29
+ else:
30
+ raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
31
+
32
+
33
+ def dep_version_check(pkg, hint=None):
34
+ require_version(deps[pkg], hint)
diffusers/dependency_versions_table.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # THIS FILE HAS BEEN AUTOGENERATED. To update:
2
+ # 1. modify the `_deps` dict in setup.py
3
+ # 2. run `make deps_table_update`
4
+ deps = {
5
+ "Pillow": "Pillow",
6
+ "accelerate": "accelerate>=0.29.3",
7
+ "compel": "compel==0.1.8",
8
+ "datasets": "datasets",
9
+ "filelock": "filelock",
10
+ "flax": "flax>=0.4.1",
11
+ "hf-doc-builder": "hf-doc-builder>=0.3.0",
12
+ "huggingface-hub": "huggingface-hub>=0.20.2",
13
+ "requests-mock": "requests-mock==1.10.0",
14
+ "importlib_metadata": "importlib_metadata",
15
+ "invisible-watermark": "invisible-watermark>=0.2.0",
16
+ "isort": "isort>=5.5.4",
17
+ "jax": "jax>=0.4.1",
18
+ "jaxlib": "jaxlib>=0.4.1",
19
+ "Jinja2": "Jinja2",
20
+ "k-diffusion": "k-diffusion>=0.0.12",
21
+ "torchsde": "torchsde",
22
+ "note_seq": "note_seq",
23
+ "librosa": "librosa",
24
+ "numpy": "numpy",
25
+ "parameterized": "parameterized",
26
+ "peft": "peft>=0.6.0",
27
+ "protobuf": "protobuf>=3.20.3,<4",
28
+ "pytest": "pytest",
29
+ "pytest-timeout": "pytest-timeout",
30
+ "pytest-xdist": "pytest-xdist",
31
+ "python": "python>=3.8.0",
32
+ "ruff": "ruff==0.1.5",
33
+ "safetensors": "safetensors>=0.3.1",
34
+ "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
35
+ "GitPython": "GitPython<3.1.19",
36
+ "scipy": "scipy",
37
+ "onnx": "onnx",
38
+ "regex": "regex!=2019.12.17",
39
+ "requests": "requests",
40
+ "tensorboard": "tensorboard",
41
+ "torch": "torch>=1.4",
42
+ "torchvision": "torchvision",
43
+ "transformers": "transformers>=4.25.1",
44
+ "urllib3": "urllib3<=2.0.0",
45
+ "black": "black",
46
+ }
diffusers/experimental/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # 🧨 Diffusers Experimental
2
+
3
+ We are adding experimental code to support novel applications and usages of the Diffusers library.
4
+ Currently, the following experiments are supported:
5
+ * Reinforcement learning via an implementation of the [Diffuser](https://arxiv.org/abs/2205.09991) model.
diffusers/experimental/rl/value_guided_sampling.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ import torch
17
+ import tqdm
18
+
19
+ from ...models.unets.unet_1d import UNet1DModel
20
+ from ...pipelines import DiffusionPipeline
21
+ from ...utils.dummy_pt_objects import DDPMScheduler
22
+ from ...utils.torch_utils import randn_tensor
23
+
24
+
25
+ class ValueGuidedRLPipeline(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states.
28
+
29
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
30
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
31
+
32
+ Parameters:
33
+ value_function ([`UNet1DModel`]):
34
+ A specialized UNet for fine-tuning trajectories base on reward.
35
+ unet ([`UNet1DModel`]):
36
+ UNet architecture to denoise the encoded trajectories.
37
+ scheduler ([`SchedulerMixin`]):
38
+ A scheduler to be used in combination with `unet` to denoise the encoded trajectories. Default for this
39
+ application is [`DDPMScheduler`].
40
+ env ():
41
+ An environment following the OpenAI gym API to act in. For now only Hopper has pretrained models.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ value_function: UNet1DModel,
47
+ unet: UNet1DModel,
48
+ scheduler: DDPMScheduler,
49
+ env,
50
+ ):
51
+ super().__init__()
52
+
53
+ self.register_modules(value_function=value_function, unet=unet, scheduler=scheduler, env=env)
54
+
55
+ self.data = env.get_dataset()
56
+ self.means = {}
57
+ for key in self.data.keys():
58
+ try:
59
+ self.means[key] = self.data[key].mean()
60
+ except: # noqa: E722
61
+ pass
62
+ self.stds = {}
63
+ for key in self.data.keys():
64
+ try:
65
+ self.stds[key] = self.data[key].std()
66
+ except: # noqa: E722
67
+ pass
68
+ self.state_dim = env.observation_space.shape[0]
69
+ self.action_dim = env.action_space.shape[0]
70
+
71
+ def normalize(self, x_in, key):
72
+ return (x_in - self.means[key]) / self.stds[key]
73
+
74
+ def de_normalize(self, x_in, key):
75
+ return x_in * self.stds[key] + self.means[key]
76
+
77
+ def to_torch(self, x_in):
78
+ if isinstance(x_in, dict):
79
+ return {k: self.to_torch(v) for k, v in x_in.items()}
80
+ elif torch.is_tensor(x_in):
81
+ return x_in.to(self.unet.device)
82
+ return torch.tensor(x_in, device=self.unet.device)
83
+
84
+ def reset_x0(self, x_in, cond, act_dim):
85
+ for key, val in cond.items():
86
+ x_in[:, key, act_dim:] = val.clone()
87
+ return x_in
88
+
89
+ def run_diffusion(self, x, conditions, n_guide_steps, scale):
90
+ batch_size = x.shape[0]
91
+ y = None
92
+ for i in tqdm.tqdm(self.scheduler.timesteps):
93
+ # create batch of timesteps to pass into model
94
+ timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
95
+ for _ in range(n_guide_steps):
96
+ with torch.enable_grad():
97
+ x.requires_grad_()
98
+
99
+ # permute to match dimension for pre-trained models
100
+ y = self.value_function(x.permute(0, 2, 1), timesteps).sample
101
+ grad = torch.autograd.grad([y.sum()], [x])[0]
102
+
103
+ posterior_variance = self.scheduler._get_variance(i)
104
+ model_std = torch.exp(0.5 * posterior_variance)
105
+ grad = model_std * grad
106
+
107
+ grad[timesteps < 2] = 0
108
+ x = x.detach()
109
+ x = x + scale * grad
110
+ x = self.reset_x0(x, conditions, self.action_dim)
111
+
112
+ prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
113
+
114
+ # TODO: verify deprecation of this kwarg
115
+ x = self.scheduler.step(prev_x, i, x)["prev_sample"]
116
+
117
+ # apply conditions to the trajectory (set the initial state)
118
+ x = self.reset_x0(x, conditions, self.action_dim)
119
+ x = self.to_torch(x)
120
+ return x, y
121
+
122
+ def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
123
+ # normalize the observations and create batch dimension
124
+ obs = self.normalize(obs, "observations")
125
+ obs = obs[None].repeat(batch_size, axis=0)
126
+
127
+ conditions = {0: self.to_torch(obs)}
128
+ shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
129
+
130
+ # generate initial noise and apply our conditions (to make the trajectories start at current state)
131
+ x1 = randn_tensor(shape, device=self.unet.device)
132
+ x = self.reset_x0(x1, conditions, self.action_dim)
133
+ x = self.to_torch(x)
134
+
135
+ # run the diffusion process
136
+ x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
137
+
138
+ # sort output trajectories by value
139
+ sorted_idx = y.argsort(0, descending=True).squeeze()
140
+ sorted_values = x[sorted_idx]
141
+ actions = sorted_values[:, :, : self.action_dim]
142
+ actions = actions.detach().cpu().numpy()
143
+ denorm_actions = self.de_normalize(actions, key="actions")
144
+
145
+ # select the action with the highest value
146
+ if y is not None:
147
+ selected_index = 0
148
+ else:
149
+ # if we didn't run value guiding, select a random action
150
+ selected_index = np.random.randint(0, batch_size)
151
+
152
+ denorm_actions = denorm_actions[selected_index, 0]
153
+ return denorm_actions
diffusers/image_processor.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ import warnings
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from PIL import Image, ImageFilter, ImageOps
24
+
25
+ from .configuration_utils import ConfigMixin, register_to_config
26
+ from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
27
+
28
+
29
+ PipelineImageInput = Union[
30
+ PIL.Image.Image,
31
+ np.ndarray,
32
+ torch.FloatTensor,
33
+ List[PIL.Image.Image],
34
+ List[np.ndarray],
35
+ List[torch.FloatTensor],
36
+ ]
37
+
38
+ PipelineDepthInput = PipelineImageInput
39
+
40
+
41
+ class VaeImageProcessor(ConfigMixin):
42
+ """
43
+ Image processor for VAE.
44
+
45
+ Args:
46
+ do_resize (`bool`, *optional*, defaults to `True`):
47
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
48
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
49
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
50
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
51
+ resample (`str`, *optional*, defaults to `lanczos`):
52
+ Resampling filter to use when resizing the image.
53
+ do_normalize (`bool`, *optional*, defaults to `True`):
54
+ Whether to normalize the image to [-1,1].
55
+ do_binarize (`bool`, *optional*, defaults to `False`):
56
+ Whether to binarize the image to 0/1.
57
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
58
+ Whether to convert the images to RGB format.
59
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
60
+ Whether to convert the images to grayscale format.
61
+ """
62
+
63
+ config_name = CONFIG_NAME
64
+
65
+ @register_to_config
66
+ def __init__(
67
+ self,
68
+ do_resize: bool = True,
69
+ vae_scale_factor: int = 8,
70
+ resample: str = "lanczos",
71
+ do_normalize: bool = True,
72
+ do_binarize: bool = False,
73
+ do_convert_rgb: bool = False,
74
+ do_convert_grayscale: bool = False,
75
+ ):
76
+ super().__init__()
77
+ if do_convert_rgb and do_convert_grayscale:
78
+ raise ValueError(
79
+ "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
80
+ " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
81
+ " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
82
+ )
83
+ self.config.do_convert_rgb = False
84
+
85
+ @staticmethod
86
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
87
+ """
88
+ Convert a numpy image or a batch of images to a PIL image.
89
+ """
90
+ if images.ndim == 3:
91
+ images = images[None, ...]
92
+ images = (images * 255).round().astype("uint8")
93
+ if images.shape[-1] == 1:
94
+ # special case for grayscale (single channel) images
95
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
96
+ else:
97
+ pil_images = [Image.fromarray(image) for image in images]
98
+
99
+ return pil_images
100
+
101
+ @staticmethod
102
+ def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
103
+ """
104
+ Convert a PIL image or a list of PIL images to NumPy arrays.
105
+ """
106
+ if not isinstance(images, list):
107
+ images = [images]
108
+ images = [np.array(image).astype(np.float32) / 255.0 for image in images]
109
+ images = np.stack(images, axis=0)
110
+
111
+ return images
112
+
113
+ @staticmethod
114
+ def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
115
+ """
116
+ Convert a NumPy image to a PyTorch tensor.
117
+ """
118
+ if images.ndim == 3:
119
+ images = images[..., None]
120
+
121
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
122
+ return images
123
+
124
+ @staticmethod
125
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
126
+ """
127
+ Convert a PyTorch tensor to a NumPy image.
128
+ """
129
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
130
+ return images
131
+
132
+ @staticmethod
133
+ def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
134
+ """
135
+ Normalize an image array to [-1,1].
136
+ """
137
+ return 2.0 * images - 1.0
138
+
139
+ @staticmethod
140
+ def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
141
+ """
142
+ Denormalize an image array to [0,1].
143
+ """
144
+ return (images / 2 + 0.5).clamp(0, 1)
145
+
146
+ @staticmethod
147
+ def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
148
+ """
149
+ Converts a PIL image to RGB format.
150
+ """
151
+ image = image.convert("RGB")
152
+
153
+ return image
154
+
155
+ @staticmethod
156
+ def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
157
+ """
158
+ Converts a PIL image to grayscale format.
159
+ """
160
+ image = image.convert("L")
161
+
162
+ return image
163
+
164
+ @staticmethod
165
+ def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
166
+ """
167
+ Applies Gaussian blur to an image.
168
+ """
169
+ image = image.filter(ImageFilter.GaussianBlur(blur_factor))
170
+
171
+ return image
172
+
173
+ @staticmethod
174
+ def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
175
+ """
176
+ Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect
177
+ ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for
178
+ processing are 512x512, the region will be expanded to 128x128.
179
+
180
+ Args:
181
+ mask_image (PIL.Image.Image): Mask image.
182
+ width (int): Width of the image to be processed.
183
+ height (int): Height of the image to be processed.
184
+ pad (int, optional): Padding to be added to the crop region. Defaults to 0.
185
+
186
+ Returns:
187
+ tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and
188
+ matches the original aspect ratio.
189
+ """
190
+
191
+ mask_image = mask_image.convert("L")
192
+ mask = np.array(mask_image)
193
+
194
+ # 1. find a rectangular region that contains all masked ares in an image
195
+ h, w = mask.shape
196
+ crop_left = 0
197
+ for i in range(w):
198
+ if not (mask[:, i] == 0).all():
199
+ break
200
+ crop_left += 1
201
+
202
+ crop_right = 0
203
+ for i in reversed(range(w)):
204
+ if not (mask[:, i] == 0).all():
205
+ break
206
+ crop_right += 1
207
+
208
+ crop_top = 0
209
+ for i in range(h):
210
+ if not (mask[i] == 0).all():
211
+ break
212
+ crop_top += 1
213
+
214
+ crop_bottom = 0
215
+ for i in reversed(range(h)):
216
+ if not (mask[i] == 0).all():
217
+ break
218
+ crop_bottom += 1
219
+
220
+ # 2. add padding to the crop region
221
+ x1, y1, x2, y2 = (
222
+ int(max(crop_left - pad, 0)),
223
+ int(max(crop_top - pad, 0)),
224
+ int(min(w - crop_right + pad, w)),
225
+ int(min(h - crop_bottom + pad, h)),
226
+ )
227
+
228
+ # 3. expands crop region to match the aspect ratio of the image to be processed
229
+ ratio_crop_region = (x2 - x1) / (y2 - y1)
230
+ ratio_processing = width / height
231
+
232
+ if ratio_crop_region > ratio_processing:
233
+ desired_height = (x2 - x1) / ratio_processing
234
+ desired_height_diff = int(desired_height - (y2 - y1))
235
+ y1 -= desired_height_diff // 2
236
+ y2 += desired_height_diff - desired_height_diff // 2
237
+ if y2 >= mask_image.height:
238
+ diff = y2 - mask_image.height
239
+ y2 -= diff
240
+ y1 -= diff
241
+ if y1 < 0:
242
+ y2 -= y1
243
+ y1 -= y1
244
+ if y2 >= mask_image.height:
245
+ y2 = mask_image.height
246
+ else:
247
+ desired_width = (y2 - y1) * ratio_processing
248
+ desired_width_diff = int(desired_width - (x2 - x1))
249
+ x1 -= desired_width_diff // 2
250
+ x2 += desired_width_diff - desired_width_diff // 2
251
+ if x2 >= mask_image.width:
252
+ diff = x2 - mask_image.width
253
+ x2 -= diff
254
+ x1 -= diff
255
+ if x1 < 0:
256
+ x2 -= x1
257
+ x1 -= x1
258
+ if x2 >= mask_image.width:
259
+ x2 = mask_image.width
260
+
261
+ return x1, y1, x2, y2
262
+
263
+ def _resize_and_fill(
264
+ self,
265
+ image: PIL.Image.Image,
266
+ width: int,
267
+ height: int,
268
+ ) -> PIL.Image.Image:
269
+ """
270
+ Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
271
+ the image within the dimensions, filling empty with data from image.
272
+
273
+ Args:
274
+ image: The image to resize.
275
+ width: The width to resize the image to.
276
+ height: The height to resize the image to.
277
+ """
278
+
279
+ ratio = width / height
280
+ src_ratio = image.width / image.height
281
+
282
+ src_w = width if ratio < src_ratio else image.width * height // image.height
283
+ src_h = height if ratio >= src_ratio else image.height * width // image.width
284
+
285
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
286
+ res = Image.new("RGB", (width, height))
287
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
288
+
289
+ if ratio < src_ratio:
290
+ fill_height = height // 2 - src_h // 2
291
+ if fill_height > 0:
292
+ res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
293
+ res.paste(
294
+ resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
295
+ box=(0, fill_height + src_h),
296
+ )
297
+ elif ratio > src_ratio:
298
+ fill_width = width // 2 - src_w // 2
299
+ if fill_width > 0:
300
+ res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
301
+ res.paste(
302
+ resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
303
+ box=(fill_width + src_w, 0),
304
+ )
305
+
306
+ return res
307
+
308
+ def _resize_and_crop(
309
+ self,
310
+ image: PIL.Image.Image,
311
+ width: int,
312
+ height: int,
313
+ ) -> PIL.Image.Image:
314
+ """
315
+ Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
316
+ the image within the dimensions, cropping the excess.
317
+
318
+ Args:
319
+ image: The image to resize.
320
+ width: The width to resize the image to.
321
+ height: The height to resize the image to.
322
+ """
323
+ ratio = width / height
324
+ src_ratio = image.width / image.height
325
+
326
+ src_w = width if ratio > src_ratio else image.width * height // image.height
327
+ src_h = height if ratio <= src_ratio else image.height * width // image.width
328
+
329
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
330
+ res = Image.new("RGB", (width, height))
331
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
332
+ return res
333
+
334
+ def resize(
335
+ self,
336
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
337
+ height: int,
338
+ width: int,
339
+ resize_mode: str = "default", # "default", "fill", "crop"
340
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
341
+ """
342
+ Resize image.
343
+
344
+ Args:
345
+ image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
346
+ The image input, can be a PIL image, numpy array or pytorch tensor.
347
+ height (`int`):
348
+ The height to resize to.
349
+ width (`int`):
350
+ The width to resize to.
351
+ resize_mode (`str`, *optional*, defaults to `default`):
352
+ The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
353
+ within the specified width and height, and it may not maintaining the original aspect ratio. If `fill`,
354
+ will resize the image to fit within the specified width and height, maintaining the aspect ratio, and
355
+ then center the image within the dimensions, filling empty with data from image. If `crop`, will resize
356
+ the image to fit within the specified width and height, maintaining the aspect ratio, and then center
357
+ the image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
358
+ supported for PIL image input.
359
+
360
+ Returns:
361
+ `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
362
+ The resized image.
363
+ """
364
+ if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
365
+ raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
366
+ if isinstance(image, PIL.Image.Image):
367
+ if resize_mode == "default":
368
+ image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
369
+ elif resize_mode == "fill":
370
+ image = self._resize_and_fill(image, width, height)
371
+ elif resize_mode == "crop":
372
+ image = self._resize_and_crop(image, width, height)
373
+ else:
374
+ raise ValueError(f"resize_mode {resize_mode} is not supported")
375
+
376
+ elif isinstance(image, torch.Tensor):
377
+ image = torch.nn.functional.interpolate(
378
+ image,
379
+ size=(height, width),
380
+ )
381
+ elif isinstance(image, np.ndarray):
382
+ image = self.numpy_to_pt(image)
383
+ image = torch.nn.functional.interpolate(
384
+ image,
385
+ size=(height, width),
386
+ )
387
+ image = self.pt_to_numpy(image)
388
+ return image
389
+
390
+ def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
391
+ """
392
+ Create a mask.
393
+
394
+ Args:
395
+ image (`PIL.Image.Image`):
396
+ The image input, should be a PIL image.
397
+
398
+ Returns:
399
+ `PIL.Image.Image`:
400
+ The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
401
+ """
402
+ image[image < 0.5] = 0
403
+ image[image >= 0.5] = 1
404
+
405
+ return image
406
+
407
+ def get_default_height_width(
408
+ self,
409
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
410
+ height: Optional[int] = None,
411
+ width: Optional[int] = None,
412
+ ) -> Tuple[int, int]:
413
+ """
414
+ This function return the height and width that are downscaled to the next integer multiple of
415
+ `vae_scale_factor`.
416
+
417
+ Args:
418
+ image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
419
+ The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
420
+ shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
421
+ have shape `[batch, channel, height, width]`.
422
+ height (`int`, *optional*, defaults to `None`):
423
+ The height in preprocessed image. If `None`, will use the height of `image` input.
424
+ width (`int`, *optional*`, defaults to `None`):
425
+ The width in preprocessed. If `None`, will use the width of the `image` input.
426
+ """
427
+
428
+ if height is None:
429
+ if isinstance(image, PIL.Image.Image):
430
+ height = image.height
431
+ elif isinstance(image, torch.Tensor):
432
+ height = image.shape[2]
433
+ else:
434
+ height = image.shape[1]
435
+
436
+ if width is None:
437
+ if isinstance(image, PIL.Image.Image):
438
+ width = image.width
439
+ elif isinstance(image, torch.Tensor):
440
+ width = image.shape[3]
441
+ else:
442
+ width = image.shape[2]
443
+
444
+ width, height = (
445
+ x - x % self.config.vae_scale_factor for x in (width, height)
446
+ ) # resize to integer multiple of vae_scale_factor
447
+
448
+ return height, width
449
+
450
+ def preprocess(
451
+ self,
452
+ image: PipelineImageInput,
453
+ height: Optional[int] = None,
454
+ width: Optional[int] = None,
455
+ resize_mode: str = "default", # "default", "fill", "crop"
456
+ crops_coords: Optional[Tuple[int, int, int, int]] = None,
457
+ ) -> torch.Tensor:
458
+ """
459
+ Preprocess the image input.
460
+
461
+ Args:
462
+ image (`pipeline_image_input`):
463
+ The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
464
+ supported formats.
465
+ height (`int`, *optional*, defaults to `None`):
466
+ The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default
467
+ height.
468
+ width (`int`, *optional*`, defaults to `None`):
469
+ The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
470
+ resize_mode (`str`, *optional*, defaults to `default`):
471
+ The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit within
472
+ the specified width and height, and it may not maintaining the original aspect ratio. If `fill`, will
473
+ resize the image to fit within the specified width and height, maintaining the aspect ratio, and then
474
+ center the image within the dimensions, filling empty with data from image. If `crop`, will resize the
475
+ image to fit within the specified width and height, maintaining the aspect ratio, and then center the
476
+ image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
477
+ supported for PIL image input.
478
+ crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
479
+ The crop coordinates for each image in the batch. If `None`, will not crop the image.
480
+ """
481
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
482
+
483
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
484
+ if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
485
+ if isinstance(image, torch.Tensor):
486
+ # if image is a pytorch tensor could have 2 possible shapes:
487
+ # 1. batch x height x width: we should insert the channel dimension at position 1
488
+ # 2. channel x height x width: we should insert batch dimension at position 0,
489
+ # however, since both channel and batch dimension has same size 1, it is same to insert at position 1
490
+ # for simplicity, we insert a dimension of size 1 at position 1 for both cases
491
+ image = image.unsqueeze(1)
492
+ else:
493
+ # if it is a numpy array, it could have 2 possible shapes:
494
+ # 1. batch x height x width: insert channel dimension on last position
495
+ # 2. height x width x channel: insert batch dimension on first position
496
+ if image.shape[-1] == 1:
497
+ image = np.expand_dims(image, axis=0)
498
+ else:
499
+ image = np.expand_dims(image, axis=-1)
500
+
501
+ if isinstance(image, supported_formats):
502
+ image = [image]
503
+ elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
504
+ raise ValueError(
505
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
506
+ )
507
+
508
+ if isinstance(image[0], PIL.Image.Image):
509
+ if crops_coords is not None:
510
+ image = [i.crop(crops_coords) for i in image]
511
+ if self.config.do_resize:
512
+ height, width = self.get_default_height_width(image[0], height, width)
513
+ image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
514
+ if self.config.do_convert_rgb:
515
+ image = [self.convert_to_rgb(i) for i in image]
516
+ elif self.config.do_convert_grayscale:
517
+ image = [self.convert_to_grayscale(i) for i in image]
518
+ image = self.pil_to_numpy(image) # to np
519
+ image = self.numpy_to_pt(image) # to pt
520
+
521
+ elif isinstance(image[0], np.ndarray):
522
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
523
+
524
+ image = self.numpy_to_pt(image)
525
+
526
+ height, width = self.get_default_height_width(image, height, width)
527
+ if self.config.do_resize:
528
+ image = self.resize(image, height, width)
529
+
530
+ elif isinstance(image[0], torch.Tensor):
531
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
532
+
533
+ if self.config.do_convert_grayscale and image.ndim == 3:
534
+ image = image.unsqueeze(1)
535
+
536
+ channel = image.shape[1]
537
+ # don't need any preprocess if the image is latents
538
+ if channel == 4:
539
+ return image
540
+
541
+ height, width = self.get_default_height_width(image, height, width)
542
+ if self.config.do_resize:
543
+ image = self.resize(image, height, width)
544
+
545
+ # expected range [0,1], normalize to [-1,1]
546
+ do_normalize = self.config.do_normalize
547
+ if do_normalize and image.min() < 0:
548
+ warnings.warn(
549
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
550
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
551
+ FutureWarning,
552
+ )
553
+ do_normalize = False
554
+
555
+ if do_normalize:
556
+ image = self.normalize(image)
557
+
558
+ if self.config.do_binarize:
559
+ image = self.binarize(image)
560
+
561
+ return image
562
+
563
+ def postprocess(
564
+ self,
565
+ image: torch.FloatTensor,
566
+ output_type: str = "pil",
567
+ do_denormalize: Optional[List[bool]] = None,
568
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
569
+ """
570
+ Postprocess the image output from tensor to `output_type`.
571
+
572
+ Args:
573
+ image (`torch.FloatTensor`):
574
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
575
+ output_type (`str`, *optional*, defaults to `pil`):
576
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
577
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
578
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
579
+ `VaeImageProcessor` config.
580
+
581
+ Returns:
582
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
583
+ The postprocessed image.
584
+ """
585
+ if not isinstance(image, torch.Tensor):
586
+ raise ValueError(
587
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
588
+ )
589
+ if output_type not in ["latent", "pt", "np", "pil"]:
590
+ deprecation_message = (
591
+ f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
592
+ "`pil`, `np`, `pt`, `latent`"
593
+ )
594
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
595
+ output_type = "np"
596
+
597
+ if output_type == "latent":
598
+ return image
599
+
600
+ if do_denormalize is None:
601
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
602
+
603
+ image = torch.stack(
604
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
605
+ )
606
+
607
+ if output_type == "pt":
608
+ return image
609
+
610
+ image = self.pt_to_numpy(image)
611
+
612
+ if output_type == "np":
613
+ return image
614
+
615
+ if output_type == "pil":
616
+ return self.numpy_to_pil(image)
617
+
618
+ def apply_overlay(
619
+ self,
620
+ mask: PIL.Image.Image,
621
+ init_image: PIL.Image.Image,
622
+ image: PIL.Image.Image,
623
+ crop_coords: Optional[Tuple[int, int, int, int]] = None,
624
+ ) -> PIL.Image.Image:
625
+ """
626
+ overlay the inpaint output to the original image
627
+ """
628
+
629
+ width, height = image.width, image.height
630
+
631
+ init_image = self.resize(init_image, width=width, height=height)
632
+ mask = self.resize(mask, width=width, height=height)
633
+
634
+ init_image_masked = PIL.Image.new("RGBa", (width, height))
635
+ init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
636
+ init_image_masked = init_image_masked.convert("RGBA")
637
+
638
+ if crop_coords is not None:
639
+ x, y, x2, y2 = crop_coords
640
+ w = x2 - x
641
+ h = y2 - y
642
+ base_image = PIL.Image.new("RGBA", (width, height))
643
+ image = self.resize(image, height=h, width=w, resize_mode="crop")
644
+ base_image.paste(image, (x, y))
645
+ image = base_image.convert("RGB")
646
+
647
+ image = image.convert("RGBA")
648
+ image.alpha_composite(init_image_masked)
649
+ image = image.convert("RGB")
650
+
651
+ return image
652
+
653
+
654
+ class VaeImageProcessorLDM3D(VaeImageProcessor):
655
+ """
656
+ Image processor for VAE LDM3D.
657
+
658
+ Args:
659
+ do_resize (`bool`, *optional*, defaults to `True`):
660
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
661
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
662
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
663
+ resample (`str`, *optional*, defaults to `lanczos`):
664
+ Resampling filter to use when resizing the image.
665
+ do_normalize (`bool`, *optional*, defaults to `True`):
666
+ Whether to normalize the image to [-1,1].
667
+ """
668
+
669
+ config_name = CONFIG_NAME
670
+
671
+ @register_to_config
672
+ def __init__(
673
+ self,
674
+ do_resize: bool = True,
675
+ vae_scale_factor: int = 8,
676
+ resample: str = "lanczos",
677
+ do_normalize: bool = True,
678
+ ):
679
+ super().__init__()
680
+
681
+ @staticmethod
682
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
683
+ """
684
+ Convert a NumPy image or a batch of images to a PIL image.
685
+ """
686
+ if images.ndim == 3:
687
+ images = images[None, ...]
688
+ images = (images * 255).round().astype("uint8")
689
+ if images.shape[-1] == 1:
690
+ # special case for grayscale (single channel) images
691
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
692
+ else:
693
+ pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
694
+
695
+ return pil_images
696
+
697
+ @staticmethod
698
+ def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
699
+ """
700
+ Convert a PIL image or a list of PIL images to NumPy arrays.
701
+ """
702
+ if not isinstance(images, list):
703
+ images = [images]
704
+
705
+ images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
706
+ images = np.stack(images, axis=0)
707
+ return images
708
+
709
+ @staticmethod
710
+ def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
711
+ """
712
+ Args:
713
+ image: RGB-like depth image
714
+
715
+ Returns: depth map
716
+
717
+ """
718
+ return image[:, :, 1] * 2**8 + image[:, :, 2]
719
+
720
+ def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
721
+ """
722
+ Convert a NumPy depth image or a batch of images to a PIL image.
723
+ """
724
+ if images.ndim == 3:
725
+ images = images[None, ...]
726
+ images_depth = images[:, :, :, 3:]
727
+ if images.shape[-1] == 6:
728
+ images_depth = (images_depth * 255).round().astype("uint8")
729
+ pil_images = [
730
+ Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
731
+ ]
732
+ elif images.shape[-1] == 4:
733
+ images_depth = (images_depth * 65535.0).astype(np.uint16)
734
+ pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
735
+ else:
736
+ raise Exception("Not supported")
737
+
738
+ return pil_images
739
+
740
+ def postprocess(
741
+ self,
742
+ image: torch.FloatTensor,
743
+ output_type: str = "pil",
744
+ do_denormalize: Optional[List[bool]] = None,
745
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
746
+ """
747
+ Postprocess the image output from tensor to `output_type`.
748
+
749
+ Args:
750
+ image (`torch.FloatTensor`):
751
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
752
+ output_type (`str`, *optional*, defaults to `pil`):
753
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
754
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
755
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
756
+ `VaeImageProcessor` config.
757
+
758
+ Returns:
759
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
760
+ The postprocessed image.
761
+ """
762
+ if not isinstance(image, torch.Tensor):
763
+ raise ValueError(
764
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
765
+ )
766
+ if output_type not in ["latent", "pt", "np", "pil"]:
767
+ deprecation_message = (
768
+ f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
769
+ "`pil`, `np`, `pt`, `latent`"
770
+ )
771
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
772
+ output_type = "np"
773
+
774
+ if do_denormalize is None:
775
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
776
+
777
+ image = torch.stack(
778
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
779
+ )
780
+
781
+ image = self.pt_to_numpy(image)
782
+
783
+ if output_type == "np":
784
+ if image.shape[-1] == 6:
785
+ image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
786
+ else:
787
+ image_depth = image[:, :, :, 3:]
788
+ return image[:, :, :, :3], image_depth
789
+
790
+ if output_type == "pil":
791
+ return self.numpy_to_pil(image), self.numpy_to_depth(image)
792
+ else:
793
+ raise Exception(f"This type {output_type} is not supported")
794
+
795
+ def preprocess(
796
+ self,
797
+ rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
798
+ depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
799
+ height: Optional[int] = None,
800
+ width: Optional[int] = None,
801
+ target_res: Optional[int] = None,
802
+ ) -> torch.Tensor:
803
+ """
804
+ Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
805
+ """
806
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
807
+
808
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
809
+ if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
810
+ raise Exception("This is not yet supported")
811
+
812
+ if isinstance(rgb, supported_formats):
813
+ rgb = [rgb]
814
+ depth = [depth]
815
+ elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
816
+ raise ValueError(
817
+ f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
818
+ )
819
+
820
+ if isinstance(rgb[0], PIL.Image.Image):
821
+ if self.config.do_convert_rgb:
822
+ raise Exception("This is not yet supported")
823
+ # rgb = [self.convert_to_rgb(i) for i in rgb]
824
+ # depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
825
+ if self.config.do_resize or target_res:
826
+ height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
827
+ rgb = [self.resize(i, height, width) for i in rgb]
828
+ depth = [self.resize(i, height, width) for i in depth]
829
+ rgb = self.pil_to_numpy(rgb) # to np
830
+ rgb = self.numpy_to_pt(rgb) # to pt
831
+
832
+ depth = self.depth_pil_to_numpy(depth) # to np
833
+ depth = self.numpy_to_pt(depth) # to pt
834
+
835
+ elif isinstance(rgb[0], np.ndarray):
836
+ rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
837
+ rgb = self.numpy_to_pt(rgb)
838
+ height, width = self.get_default_height_width(rgb, height, width)
839
+ if self.config.do_resize:
840
+ rgb = self.resize(rgb, height, width)
841
+
842
+ depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
843
+ depth = self.numpy_to_pt(depth)
844
+ height, width = self.get_default_height_width(depth, height, width)
845
+ if self.config.do_resize:
846
+ depth = self.resize(depth, height, width)
847
+
848
+ elif isinstance(rgb[0], torch.Tensor):
849
+ raise Exception("This is not yet supported")
850
+ # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
851
+
852
+ # if self.config.do_convert_grayscale and rgb.ndim == 3:
853
+ # rgb = rgb.unsqueeze(1)
854
+
855
+ # channel = rgb.shape[1]
856
+
857
+ # height, width = self.get_default_height_width(rgb, height, width)
858
+ # if self.config.do_resize:
859
+ # rgb = self.resize(rgb, height, width)
860
+
861
+ # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
862
+
863
+ # if self.config.do_convert_grayscale and depth.ndim == 3:
864
+ # depth = depth.unsqueeze(1)
865
+
866
+ # channel = depth.shape[1]
867
+ # # don't need any preprocess if the image is latents
868
+ # if depth == 4:
869
+ # return rgb, depth
870
+
871
+ # height, width = self.get_default_height_width(depth, height, width)
872
+ # if self.config.do_resize:
873
+ # depth = self.resize(depth, height, width)
874
+ # expected range [0,1], normalize to [-1,1]
875
+ do_normalize = self.config.do_normalize
876
+ if rgb.min() < 0 and do_normalize:
877
+ warnings.warn(
878
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
879
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
880
+ FutureWarning,
881
+ )
882
+ do_normalize = False
883
+
884
+ if do_normalize:
885
+ rgb = self.normalize(rgb)
886
+ depth = self.normalize(depth)
887
+
888
+ if self.config.do_binarize:
889
+ rgb = self.binarize(rgb)
890
+ depth = self.binarize(depth)
891
+
892
+ return rgb, depth
893
+
894
+
895
+ class IPAdapterMaskProcessor(VaeImageProcessor):
896
+ """
897
+ Image processor for IP Adapter image masks.
898
+
899
+ Args:
900
+ do_resize (`bool`, *optional*, defaults to `True`):
901
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
902
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
903
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
904
+ resample (`str`, *optional*, defaults to `lanczos`):
905
+ Resampling filter to use when resizing the image.
906
+ do_normalize (`bool`, *optional*, defaults to `False`):
907
+ Whether to normalize the image to [-1,1].
908
+ do_binarize (`bool`, *optional*, defaults to `True`):
909
+ Whether to binarize the image to 0/1.
910
+ do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
911
+ Whether to convert the images to grayscale format.
912
+
913
+ """
914
+
915
+ config_name = CONFIG_NAME
916
+
917
+ @register_to_config
918
+ def __init__(
919
+ self,
920
+ do_resize: bool = True,
921
+ vae_scale_factor: int = 8,
922
+ resample: str = "lanczos",
923
+ do_normalize: bool = False,
924
+ do_binarize: bool = True,
925
+ do_convert_grayscale: bool = True,
926
+ ):
927
+ super().__init__(
928
+ do_resize=do_resize,
929
+ vae_scale_factor=vae_scale_factor,
930
+ resample=resample,
931
+ do_normalize=do_normalize,
932
+ do_binarize=do_binarize,
933
+ do_convert_grayscale=do_convert_grayscale,
934
+ )
935
+
936
+ @staticmethod
937
+ def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
938
+ """
939
+ Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention. If the
940
+ aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
941
+
942
+ Args:
943
+ mask (`torch.FloatTensor`):
944
+ The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
945
+ batch_size (`int`):
946
+ The batch size.
947
+ num_queries (`int`):
948
+ The number of queries.
949
+ value_embed_dim (`int`):
950
+ The dimensionality of the value embeddings.
951
+
952
+ Returns:
953
+ `torch.FloatTensor`:
954
+ The downsampled mask tensor.
955
+
956
+ """
957
+ o_h = mask.shape[1]
958
+ o_w = mask.shape[2]
959
+ ratio = o_w / o_h
960
+ mask_h = int(math.sqrt(num_queries / ratio))
961
+ mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
962
+ mask_w = num_queries // mask_h
963
+
964
+ mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
965
+
966
+ # Repeat batch_size times
967
+ if mask_downsample.shape[0] < batch_size:
968
+ mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
969
+
970
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
971
+
972
+ downsampled_area = mask_h * mask_w
973
+ # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
974
+ # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
975
+ if downsampled_area < num_queries:
976
+ warnings.warn(
977
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
978
+ "Please update your masks or adjust the output size for optimal performance.",
979
+ UserWarning,
980
+ )
981
+ mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
982
+ # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
983
+ if downsampled_area > num_queries:
984
+ warnings.warn(
985
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
986
+ "Please update your masks or adjust the output size for optimal performance.",
987
+ UserWarning,
988
+ )
989
+ mask_downsample = mask_downsample[:, :num_queries]
990
+
991
+ # Repeat last dimension to match SDPA output shape
992
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
993
+ 1, 1, value_embed_dim
994
+ )
995
+
996
+ return mask_downsample
997
+
998
+
999
+ class PixArtImageProcessor(VaeImageProcessor):
1000
+ """
1001
+ Image processor for PixArt image resize and crop.
1002
+
1003
+ Args:
1004
+ do_resize (`bool`, *optional*, defaults to `True`):
1005
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
1006
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
1007
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
1008
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
1009
+ resample (`str`, *optional*, defaults to `lanczos`):
1010
+ Resampling filter to use when resizing the image.
1011
+ do_normalize (`bool`, *optional*, defaults to `True`):
1012
+ Whether to normalize the image to [-1,1].
1013
+ do_binarize (`bool`, *optional*, defaults to `False`):
1014
+ Whether to binarize the image to 0/1.
1015
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
1016
+ Whether to convert the images to RGB format.
1017
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
1018
+ Whether to convert the images to grayscale format.
1019
+ """
1020
+
1021
+ @register_to_config
1022
+ def __init__(
1023
+ self,
1024
+ do_resize: bool = True,
1025
+ vae_scale_factor: int = 8,
1026
+ resample: str = "lanczos",
1027
+ do_normalize: bool = True,
1028
+ do_binarize: bool = False,
1029
+ do_convert_grayscale: bool = False,
1030
+ ):
1031
+ super().__init__(
1032
+ do_resize=do_resize,
1033
+ vae_scale_factor=vae_scale_factor,
1034
+ resample=resample,
1035
+ do_normalize=do_normalize,
1036
+ do_binarize=do_binarize,
1037
+ do_convert_grayscale=do_convert_grayscale,
1038
+ )
1039
+
1040
+ @staticmethod
1041
+ def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
1042
+ """Returns binned height and width."""
1043
+ ar = float(height / width)
1044
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
1045
+ default_hw = ratios[closest_ratio]
1046
+ return int(default_hw[0]), int(default_hw[1])
1047
+
1048
+ @staticmethod
1049
+ def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int) -> torch.Tensor:
1050
+ orig_height, orig_width = samples.shape[2], samples.shape[3]
1051
+
1052
+ # Check if resizing is needed
1053
+ if orig_height != new_height or orig_width != new_width:
1054
+ ratio = max(new_height / orig_height, new_width / orig_width)
1055
+ resized_width = int(orig_width * ratio)
1056
+ resized_height = int(orig_height * ratio)
1057
+
1058
+ # Resize
1059
+ samples = F.interpolate(
1060
+ samples, size=(resized_height, resized_width), mode="bilinear", align_corners=False
1061
+ )
1062
+
1063
+ # Center Crop
1064
+ start_x = (resized_width - new_width) // 2
1065
+ end_x = start_x + new_width
1066
+ start_y = (resized_height - new_height) // 2
1067
+ end_y = start_y + new_height
1068
+ samples = samples[:, :, start_y:end_y, start_x:end_x]
1069
+
1070
+ return samples
diffusers/loaders/autoencoder.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from .single_file_utils import (
18
+ create_diffusers_vae_model_from_ldm,
19
+ fetch_ldm_config_and_checkpoint,
20
+ )
21
+
22
+
23
+ class FromOriginalVAEMixin:
24
+ """
25
+ Load pretrained AutoencoderKL weights saved in the `.ckpt` or `.safetensors` format into a [`AutoencoderKL`].
26
+ """
27
+
28
+ @classmethod
29
+ @validate_hf_hub_args
30
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
+ r"""
32
+ Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
+
35
+ Parameters:
36
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
+ Can be either:
38
+ - A link to the `.ckpt` file (for example
39
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
+ - A path to a *file* containing all pipeline weights.
41
+ config_file (`str`, *optional*):
42
+ Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
+ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
44
+ torch_dtype (`str` or `torch.dtype`, *optional*):
45
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
+ dtype is automatically derived from the model's weights.
47
+ force_download (`bool`, *optional*, defaults to `False`):
48
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
+ cached versions if they exist.
50
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
51
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
+ is not used.
53
+ resume_download:
54
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
55
+ of Diffusers.
56
+ proxies (`Dict[str, str]`, *optional*):
57
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
+ local_files_only (`bool`, *optional*, defaults to `False`):
60
+ Whether to only load local model weights and configuration files or not. If set to True, the model
61
+ won't be downloaded from the Hub.
62
+ token (`str` or *bool*, *optional*):
63
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
+ revision (`str`, *optional*, defaults to `"main"`):
66
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
+ allowed by Git.
68
+ image_size (`int`, *optional*, defaults to 512):
69
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
72
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
73
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
74
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
75
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
76
+ = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
77
+ Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
78
+ kwargs (remaining dictionary of keyword arguments, *optional*):
79
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
80
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
81
+ method. See example below for more information.
82
+
83
+ <Tip warning={true}>
84
+
85
+ Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
86
+ a VAE from SDXL or a Stable Diffusion v2 model or higher.
87
+
88
+ </Tip>
89
+
90
+ Examples:
91
+
92
+ ```py
93
+ from diffusers import AutoencoderKL
94
+
95
+ url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
96
+ model = AutoencoderKL.from_single_file(url)
97
+ ```
98
+ """
99
+
100
+ original_config_file = kwargs.pop("original_config_file", None)
101
+ config_file = kwargs.pop("config_file", None)
102
+ resume_download = kwargs.pop("resume_download", None)
103
+ force_download = kwargs.pop("force_download", False)
104
+ proxies = kwargs.pop("proxies", None)
105
+ token = kwargs.pop("token", None)
106
+ cache_dir = kwargs.pop("cache_dir", None)
107
+ local_files_only = kwargs.pop("local_files_only", None)
108
+ revision = kwargs.pop("revision", None)
109
+ torch_dtype = kwargs.pop("torch_dtype", None)
110
+
111
+ class_name = cls.__name__
112
+
113
+ if (config_file is not None) and (original_config_file is not None):
114
+ raise ValueError(
115
+ "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
116
+ )
117
+
118
+ original_config_file = original_config_file or config_file
119
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
120
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
121
+ class_name=class_name,
122
+ original_config_file=original_config_file,
123
+ resume_download=resume_download,
124
+ force_download=force_download,
125
+ proxies=proxies,
126
+ token=token,
127
+ revision=revision,
128
+ local_files_only=local_files_only,
129
+ cache_dir=cache_dir,
130
+ )
131
+
132
+ image_size = kwargs.pop("image_size", None)
133
+ scaling_factor = kwargs.pop("scaling_factor", None)
134
+ component = create_diffusers_vae_model_from_ldm(
135
+ class_name,
136
+ original_config,
137
+ checkpoint,
138
+ image_size=image_size,
139
+ scaling_factor=scaling_factor,
140
+ torch_dtype=torch_dtype,
141
+ )
142
+ vae = component["vae"]
143
+ if torch_dtype is not None:
144
+ vae = vae.to(torch_dtype)
145
+
146
+ return vae
diffusers/loaders/controlnet.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from .single_file_utils import (
18
+ create_diffusers_controlnet_model_from_ldm,
19
+ fetch_ldm_config_and_checkpoint,
20
+ )
21
+
22
+
23
+ class FromOriginalControlNetMixin:
24
+ """
25
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
26
+ """
27
+
28
+ @classmethod
29
+ @validate_hf_hub_args
30
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
+ r"""
32
+ Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
+
35
+ Parameters:
36
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
+ Can be either:
38
+ - A link to the `.ckpt` file (for example
39
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
+ - A path to a *file* containing all pipeline weights.
41
+ config_file (`str`, *optional*):
42
+ Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
+ https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml
44
+ torch_dtype (`str` or `torch.dtype`, *optional*):
45
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
+ dtype is automatically derived from the model's weights.
47
+ force_download (`bool`, *optional*, defaults to `False`):
48
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
+ cached versions if they exist.
50
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
51
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
+ is not used.
53
+ resume_download:
54
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
55
+ of Diffusers.
56
+ proxies (`Dict[str, str]`, *optional*):
57
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
+ local_files_only (`bool`, *optional*, defaults to `False`):
60
+ Whether to only load local model weights and configuration files or not. If set to True, the model
61
+ won't be downloaded from the Hub.
62
+ token (`str` or *bool*, *optional*):
63
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
+ revision (`str`, *optional*, defaults to `"main"`):
66
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
+ allowed by Git.
68
+ image_size (`int`, *optional*, defaults to 512):
69
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
+ upcast_attention (`bool`, *optional*, defaults to `None`):
72
+ Whether the attention computation should always be upcasted.
73
+ kwargs (remaining dictionary of keyword arguments, *optional*):
74
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
75
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
76
+ method. See example below for more information.
77
+
78
+ Examples:
79
+
80
+ ```py
81
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
82
+
83
+ url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
84
+ model = ControlNetModel.from_single_file(url)
85
+
86
+ url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
87
+ pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
88
+ ```
89
+ """
90
+ original_config_file = kwargs.pop("original_config_file", None)
91
+ config_file = kwargs.pop("config_file", None)
92
+ resume_download = kwargs.pop("resume_download", None)
93
+ force_download = kwargs.pop("force_download", False)
94
+ proxies = kwargs.pop("proxies", None)
95
+ token = kwargs.pop("token", None)
96
+ cache_dir = kwargs.pop("cache_dir", None)
97
+ local_files_only = kwargs.pop("local_files_only", None)
98
+ revision = kwargs.pop("revision", None)
99
+ torch_dtype = kwargs.pop("torch_dtype", None)
100
+
101
+ class_name = cls.__name__
102
+ if (config_file is not None) and (original_config_file is not None):
103
+ raise ValueError(
104
+ "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
105
+ )
106
+
107
+ original_config_file = config_file or original_config_file
108
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
109
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
110
+ class_name=class_name,
111
+ original_config_file=original_config_file,
112
+ resume_download=resume_download,
113
+ force_download=force_download,
114
+ proxies=proxies,
115
+ token=token,
116
+ revision=revision,
117
+ local_files_only=local_files_only,
118
+ cache_dir=cache_dir,
119
+ )
120
+
121
+ upcast_attention = kwargs.pop("upcast_attention", False)
122
+ image_size = kwargs.pop("image_size", None)
123
+
124
+ component = create_diffusers_controlnet_model_from_ldm(
125
+ class_name,
126
+ original_config,
127
+ checkpoint,
128
+ upcast_attention=upcast_attention,
129
+ image_size=image_size,
130
+ torch_dtype=torch_dtype,
131
+ )
132
+ controlnet = component["controlnet"]
133
+ if torch_dtype is not None:
134
+ controlnet = controlnet.to(torch_dtype)
135
+
136
+ return controlnet
diffusers/loaders/ip_adapter.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pathlib import Path
16
+ from typing import Dict, List, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from huggingface_hub.utils import validate_hf_hub_args
21
+ from safetensors import safe_open
22
+
23
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_state_dict
24
+ from ..utils import (
25
+ USE_PEFT_BACKEND,
26
+ _get_model_file,
27
+ is_accelerate_available,
28
+ is_torch_version,
29
+ is_transformers_available,
30
+ logging,
31
+ )
32
+ from .unet_loader_utils import _maybe_expand_lora_scales
33
+
34
+
35
+ if is_transformers_available():
36
+ from transformers import (
37
+ CLIPImageProcessor,
38
+ CLIPVisionModelWithProjection,
39
+ )
40
+
41
+ from ..models.attention_processor import (
42
+ AttnProcessor,
43
+ AttnProcessor2_0,
44
+ IPAdapterAttnProcessor,
45
+ IPAdapterAttnProcessor2_0,
46
+ )
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ class IPAdapterMixin:
52
+ """Mixin for handling IP Adapters."""
53
+
54
+ @validate_hf_hub_args
55
+ def load_ip_adapter(
56
+ self,
57
+ pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]],
58
+ subfolder: Union[str, List[str]],
59
+ weight_name: Union[str, List[str]],
60
+ image_encoder_folder: Optional[str] = "image_encoder",
61
+ **kwargs,
62
+ ):
63
+ """
64
+ Parameters:
65
+ pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
66
+ Can be either:
67
+
68
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
69
+ the Hub.
70
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
71
+ with [`ModelMixin.save_pretrained`].
72
+ - A [torch state
73
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
74
+ subfolder (`str` or `List[str]`):
75
+ The subfolder location of a model file within a larger model repository on the Hub or locally. If a
76
+ list is passed, it should have the same length as `weight_name`.
77
+ weight_name (`str` or `List[str]`):
78
+ The name of the weight file to load. If a list is passed, it should have the same length as
79
+ `weight_name`.
80
+ image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
81
+ The subfolder location of the image encoder within a larger model repository on the Hub or locally.
82
+ Pass `None` to not load the image encoder. If the image encoder is located in a folder inside
83
+ `subfolder`, you only need to pass the name of the folder that contains image encoder weights, e.g.
84
+ `image_encoder_folder="image_encoder"`. If the image encoder is located in a folder other than
85
+ `subfolder`, you should pass the path to the folder that contains image encoder weights, for example,
86
+ `image_encoder_folder="different_subfolder/image_encoder"`.
87
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
88
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
89
+ is not used.
90
+ force_download (`bool`, *optional*, defaults to `False`):
91
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
92
+ cached versions if they exist.
93
+ resume_download:
94
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
95
+ of Diffusers.
96
+ proxies (`Dict[str, str]`, *optional*):
97
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
98
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
99
+ local_files_only (`bool`, *optional*, defaults to `False`):
100
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
101
+ won't be downloaded from the Hub.
102
+ token (`str` or *bool*, *optional*):
103
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
104
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
105
+ revision (`str`, *optional*, defaults to `"main"`):
106
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
107
+ allowed by Git.
108
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
109
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
110
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
111
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
112
+ argument to `True` will raise an error.
113
+ """
114
+
115
+ # handle the list inputs for multiple IP Adapters
116
+ if not isinstance(weight_name, list):
117
+ weight_name = [weight_name]
118
+
119
+ if not isinstance(pretrained_model_name_or_path_or_dict, list):
120
+ pretrained_model_name_or_path_or_dict = [pretrained_model_name_or_path_or_dict]
121
+ if len(pretrained_model_name_or_path_or_dict) == 1:
122
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict * len(weight_name)
123
+
124
+ if not isinstance(subfolder, list):
125
+ subfolder = [subfolder]
126
+ if len(subfolder) == 1:
127
+ subfolder = subfolder * len(weight_name)
128
+
129
+ if len(weight_name) != len(pretrained_model_name_or_path_or_dict):
130
+ raise ValueError("`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.")
131
+
132
+ if len(weight_name) != len(subfolder):
133
+ raise ValueError("`weight_name` and `subfolder` must have the same length.")
134
+
135
+ # Load the main state dict first.
136
+ cache_dir = kwargs.pop("cache_dir", None)
137
+ force_download = kwargs.pop("force_download", False)
138
+ resume_download = kwargs.pop("resume_download", None)
139
+ proxies = kwargs.pop("proxies", None)
140
+ local_files_only = kwargs.pop("local_files_only", None)
141
+ token = kwargs.pop("token", None)
142
+ revision = kwargs.pop("revision", None)
143
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
144
+
145
+ if low_cpu_mem_usage and not is_accelerate_available():
146
+ low_cpu_mem_usage = False
147
+ logger.warning(
148
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
149
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
150
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
151
+ " install accelerate\n```\n."
152
+ )
153
+
154
+ if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
155
+ raise NotImplementedError(
156
+ "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
157
+ " `low_cpu_mem_usage=False`."
158
+ )
159
+
160
+ user_agent = {
161
+ "file_type": "attn_procs_weights",
162
+ "framework": "pytorch",
163
+ }
164
+ state_dicts = []
165
+ for pretrained_model_name_or_path_or_dict, weight_name, subfolder in zip(
166
+ pretrained_model_name_or_path_or_dict, weight_name, subfolder
167
+ ):
168
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
169
+ model_file = _get_model_file(
170
+ pretrained_model_name_or_path_or_dict,
171
+ weights_name=weight_name,
172
+ cache_dir=cache_dir,
173
+ force_download=force_download,
174
+ resume_download=resume_download,
175
+ proxies=proxies,
176
+ local_files_only=local_files_only,
177
+ token=token,
178
+ revision=revision,
179
+ subfolder=subfolder,
180
+ user_agent=user_agent,
181
+ )
182
+ if weight_name.endswith(".safetensors"):
183
+ state_dict = {"image_proj": {}, "ip_adapter": {}}
184
+ with safe_open(model_file, framework="pt", device="cpu") as f:
185
+ for key in f.keys():
186
+ if key.startswith("image_proj."):
187
+ state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
188
+ elif key.startswith("ip_adapter."):
189
+ state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
190
+ else:
191
+ state_dict = load_state_dict(model_file)
192
+ else:
193
+ state_dict = pretrained_model_name_or_path_or_dict
194
+
195
+ keys = list(state_dict.keys())
196
+ if keys != ["image_proj", "ip_adapter"]:
197
+ raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
198
+
199
+ state_dicts.append(state_dict)
200
+
201
+ # load CLIP image encoder here if it has not been registered to the pipeline yet
202
+ if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
203
+ if image_encoder_folder is not None:
204
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
205
+ logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
206
+ if image_encoder_folder.count("/") == 0:
207
+ image_encoder_subfolder = Path(subfolder, image_encoder_folder).as_posix()
208
+ else:
209
+ image_encoder_subfolder = Path(image_encoder_folder).as_posix()
210
+
211
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
212
+ pretrained_model_name_or_path_or_dict,
213
+ subfolder=image_encoder_subfolder,
214
+ low_cpu_mem_usage=low_cpu_mem_usage,
215
+ ).to(self.device, dtype=self.dtype)
216
+ self.register_modules(image_encoder=image_encoder)
217
+ else:
218
+ raise ValueError(
219
+ "`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict."
220
+ )
221
+ else:
222
+ logger.warning(
223
+ "image_encoder is not loaded since `image_encoder_folder=None` passed. You will not be able to use `ip_adapter_image` when calling the pipeline with IP-Adapter."
224
+ "Use `ip_adapter_image_embeds` to pass pre-generated image embedding instead."
225
+ )
226
+
227
+ # create feature extractor if it has not been registered to the pipeline yet
228
+ if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
229
+ feature_extractor = CLIPImageProcessor()
230
+ self.register_modules(feature_extractor=feature_extractor)
231
+
232
+ # load ip-adapter into unet
233
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
234
+ unet._load_ip_adapter_weights(state_dicts, low_cpu_mem_usage=low_cpu_mem_usage)
235
+
236
+ extra_loras = unet._load_ip_adapter_loras(state_dicts)
237
+ if extra_loras != {}:
238
+ if not USE_PEFT_BACKEND:
239
+ logger.warning("PEFT backend is required to load these weights.")
240
+ else:
241
+ # apply the IP Adapter Face ID LoRA weights
242
+ peft_config = getattr(unet, "peft_config", {})
243
+ for k, lora in extra_loras.items():
244
+ if f"faceid_{k}" not in peft_config:
245
+ self.load_lora_weights(lora, adapter_name=f"faceid_{k}")
246
+ self.set_adapters([f"faceid_{k}"], adapter_weights=[1.0])
247
+
248
+ def set_ip_adapter_scale(self, scale):
249
+ """
250
+ Set IP-Adapter scales per-transformer block. Input `scale` could be a single config or a list of configs for
251
+ granular control over each IP-Adapter behavior. A config can be a float or a dictionary.
252
+
253
+ Example:
254
+
255
+ ```py
256
+ # To use original IP-Adapter
257
+ scale = 1.0
258
+ pipeline.set_ip_adapter_scale(scale)
259
+
260
+ # To use style block only
261
+ scale = {
262
+ "up": {"block_0": [0.0, 1.0, 0.0]},
263
+ }
264
+ pipeline.set_ip_adapter_scale(scale)
265
+
266
+ # To use style+layout blocks
267
+ scale = {
268
+ "down": {"block_2": [0.0, 1.0]},
269
+ "up": {"block_0": [0.0, 1.0, 0.0]},
270
+ }
271
+ pipeline.set_ip_adapter_scale(scale)
272
+
273
+ # To use style and layout from 2 reference images
274
+ scales = [{"down": {"block_2": [0.0, 1.0]}}, {"up": {"block_0": [0.0, 1.0, 0.0]}}]
275
+ pipeline.set_ip_adapter_scale(scales)
276
+ ```
277
+ """
278
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
279
+ if not isinstance(scale, list):
280
+ scale = [scale]
281
+ scale_configs = _maybe_expand_lora_scales(unet, scale, default_scale=0.0)
282
+
283
+ for attn_name, attn_processor in unet.attn_processors.items():
284
+ if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
285
+ if len(scale_configs) != len(attn_processor.scale):
286
+ raise ValueError(
287
+ f"Cannot assign {len(scale_configs)} scale_configs to "
288
+ f"{len(attn_processor.scale)} IP-Adapter."
289
+ )
290
+ elif len(scale_configs) == 1:
291
+ scale_configs = scale_configs * len(attn_processor.scale)
292
+ for i, scale_config in enumerate(scale_configs):
293
+ if isinstance(scale_config, dict):
294
+ for k, s in scale_config.items():
295
+ if attn_name.startswith(k):
296
+ attn_processor.scale[i] = s
297
+ else:
298
+ attn_processor.scale[i] = scale_config
299
+
300
+ def unload_ip_adapter(self):
301
+ """
302
+ Unloads the IP Adapter weights
303
+
304
+ Examples:
305
+
306
+ ```python
307
+ >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
308
+ >>> pipeline.unload_ip_adapter()
309
+ >>> ...
310
+ ```
311
+ """
312
+ # remove CLIP image encoder
313
+ if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is not None:
314
+ self.image_encoder = None
315
+ self.register_to_config(image_encoder=[None, None])
316
+
317
+ # remove feature extractor only when safety_checker is None as safety_checker uses
318
+ # the feature_extractor later
319
+ if not hasattr(self, "safety_checker"):
320
+ if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is not None:
321
+ self.feature_extractor = None
322
+ self.register_to_config(feature_extractor=[None, None])
323
+
324
+ # remove hidden encoder
325
+ self.unet.encoder_hid_proj = None
326
+ self.config.encoder_hid_dim_type = None
327
+
328
+ # restore original Unet attention processors layers
329
+ attn_procs = {}
330
+ for name, value in self.unet.attn_processors.items():
331
+ attn_processor_class = (
332
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnProcessor()
333
+ )
334
+ attn_procs[name] = (
335
+ attn_processor_class
336
+ if isinstance(value, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0))
337
+ else value.__class__()
338
+ )
339
+ self.unet.set_attn_processor(attn_procs)
diffusers/loaders/lora.py ADDED
@@ -0,0 +1,1458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import copy
15
+ import inspect
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Callable, Dict, List, Optional, Union
19
+
20
+ import safetensors
21
+ import torch
22
+ from huggingface_hub import model_info
23
+ from huggingface_hub.constants import HF_HUB_OFFLINE
24
+ from huggingface_hub.utils import validate_hf_hub_args
25
+ from packaging import version
26
+ from torch import nn
27
+
28
+ from .. import __version__
29
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_state_dict
30
+ from ..utils import (
31
+ USE_PEFT_BACKEND,
32
+ _get_model_file,
33
+ convert_state_dict_to_diffusers,
34
+ convert_state_dict_to_peft,
35
+ convert_unet_state_dict_to_peft,
36
+ delete_adapter_layers,
37
+ get_adapter_name,
38
+ get_peft_kwargs,
39
+ is_accelerate_available,
40
+ is_peft_version,
41
+ is_transformers_available,
42
+ logging,
43
+ recurse_remove_peft_layers,
44
+ scale_lora_layers,
45
+ set_adapter_layers,
46
+ set_weights_and_activate_adapters,
47
+ )
48
+ from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
49
+
50
+
51
+ if is_transformers_available():
52
+ from transformers import PreTrainedModel
53
+
54
+ from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
55
+
56
+ if is_accelerate_available():
57
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ TEXT_ENCODER_NAME = "text_encoder"
62
+ UNET_NAME = "unet"
63
+ TRANSFORMER_NAME = "transformer"
64
+
65
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
66
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
67
+
68
+ LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
69
+
70
+
71
+ class LoraLoaderMixin:
72
+ r"""
73
+ Load LoRA layers into [`UNet2DConditionModel`] and
74
+ [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
75
+ """
76
+
77
+ text_encoder_name = TEXT_ENCODER_NAME
78
+ unet_name = UNET_NAME
79
+ transformer_name = TRANSFORMER_NAME
80
+ num_fused_loras = 0
81
+
82
+ def load_lora_weights(
83
+ self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
84
+ ):
85
+ """
86
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
87
+ `self.text_encoder`.
88
+
89
+ All kwargs are forwarded to `self.lora_state_dict`.
90
+
91
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
92
+
93
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
94
+ `self.unet`.
95
+
96
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
97
+ into `self.text_encoder`.
98
+
99
+ Parameters:
100
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
101
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
102
+ kwargs (`dict`, *optional*):
103
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
104
+ adapter_name (`str`, *optional*):
105
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
106
+ `default_{i}` where i is the total number of adapters being loaded.
107
+ """
108
+ if not USE_PEFT_BACKEND:
109
+ raise ValueError("PEFT backend is required for this method.")
110
+
111
+ # if a dict is passed, copy it instead of modifying it inplace
112
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
113
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
114
+
115
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
116
+ state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
117
+
118
+ is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
119
+ if not is_correct_format:
120
+ raise ValueError("Invalid LoRA checkpoint.")
121
+
122
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
123
+
124
+ self.load_lora_into_unet(
125
+ state_dict,
126
+ network_alphas=network_alphas,
127
+ unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
128
+ low_cpu_mem_usage=low_cpu_mem_usage,
129
+ adapter_name=adapter_name,
130
+ _pipeline=self,
131
+ )
132
+ self.load_lora_into_text_encoder(
133
+ state_dict,
134
+ network_alphas=network_alphas,
135
+ text_encoder=getattr(self, self.text_encoder_name)
136
+ if not hasattr(self, "text_encoder")
137
+ else self.text_encoder,
138
+ lora_scale=self.lora_scale,
139
+ low_cpu_mem_usage=low_cpu_mem_usage,
140
+ adapter_name=adapter_name,
141
+ _pipeline=self,
142
+ )
143
+
144
+ @classmethod
145
+ @validate_hf_hub_args
146
+ def lora_state_dict(
147
+ cls,
148
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
149
+ **kwargs,
150
+ ):
151
+ r"""
152
+ Return state dict for lora weights and the network alphas.
153
+
154
+ <Tip warning={true}>
155
+
156
+ We support loading A1111 formatted LoRA checkpoints in a limited capacity.
157
+
158
+ This function is experimental and might change in the future.
159
+
160
+ </Tip>
161
+
162
+ Parameters:
163
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
164
+ Can be either:
165
+
166
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
167
+ the Hub.
168
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
169
+ with [`ModelMixin.save_pretrained`].
170
+ - A [torch state
171
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
172
+
173
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
174
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
175
+ is not used.
176
+ force_download (`bool`, *optional*, defaults to `False`):
177
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
178
+ cached versions if they exist.
179
+ resume_download:
180
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
181
+ of Diffusers.
182
+ proxies (`Dict[str, str]`, *optional*):
183
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
184
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
185
+ local_files_only (`bool`, *optional*, defaults to `False`):
186
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
187
+ won't be downloaded from the Hub.
188
+ token (`str` or *bool*, *optional*):
189
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
190
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
191
+ revision (`str`, *optional*, defaults to `"main"`):
192
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
193
+ allowed by Git.
194
+ subfolder (`str`, *optional*, defaults to `""`):
195
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
196
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
197
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
198
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
199
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
200
+ argument to `True` will raise an error.
201
+ mirror (`str`, *optional*):
202
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
203
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
204
+ information.
205
+
206
+ """
207
+ # Load the main state dict first which has the LoRA layers for either of
208
+ # UNet and text encoder or both.
209
+ cache_dir = kwargs.pop("cache_dir", None)
210
+ force_download = kwargs.pop("force_download", False)
211
+ resume_download = kwargs.pop("resume_download", None)
212
+ proxies = kwargs.pop("proxies", None)
213
+ local_files_only = kwargs.pop("local_files_only", None)
214
+ token = kwargs.pop("token", None)
215
+ revision = kwargs.pop("revision", None)
216
+ subfolder = kwargs.pop("subfolder", None)
217
+ weight_name = kwargs.pop("weight_name", None)
218
+ unet_config = kwargs.pop("unet_config", None)
219
+ use_safetensors = kwargs.pop("use_safetensors", None)
220
+
221
+ allow_pickle = False
222
+ if use_safetensors is None:
223
+ use_safetensors = True
224
+ allow_pickle = True
225
+
226
+ user_agent = {
227
+ "file_type": "attn_procs_weights",
228
+ "framework": "pytorch",
229
+ }
230
+
231
+ model_file = None
232
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
233
+ # Let's first try to load .safetensors weights
234
+ if (use_safetensors and weight_name is None) or (
235
+ weight_name is not None and weight_name.endswith(".safetensors")
236
+ ):
237
+ try:
238
+ # Here we're relaxing the loading check to enable more Inference API
239
+ # friendliness where sometimes, it's not at all possible to automatically
240
+ # determine `weight_name`.
241
+ if weight_name is None:
242
+ weight_name = cls._best_guess_weight_name(
243
+ pretrained_model_name_or_path_or_dict,
244
+ file_extension=".safetensors",
245
+ local_files_only=local_files_only,
246
+ )
247
+ model_file = _get_model_file(
248
+ pretrained_model_name_or_path_or_dict,
249
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
250
+ cache_dir=cache_dir,
251
+ force_download=force_download,
252
+ resume_download=resume_download,
253
+ proxies=proxies,
254
+ local_files_only=local_files_only,
255
+ token=token,
256
+ revision=revision,
257
+ subfolder=subfolder,
258
+ user_agent=user_agent,
259
+ )
260
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
261
+ except (IOError, safetensors.SafetensorError) as e:
262
+ if not allow_pickle:
263
+ raise e
264
+ # try loading non-safetensors weights
265
+ model_file = None
266
+ pass
267
+
268
+ if model_file is None:
269
+ if weight_name is None:
270
+ weight_name = cls._best_guess_weight_name(
271
+ pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
272
+ )
273
+ model_file = _get_model_file(
274
+ pretrained_model_name_or_path_or_dict,
275
+ weights_name=weight_name or LORA_WEIGHT_NAME,
276
+ cache_dir=cache_dir,
277
+ force_download=force_download,
278
+ resume_download=resume_download,
279
+ proxies=proxies,
280
+ local_files_only=local_files_only,
281
+ token=token,
282
+ revision=revision,
283
+ subfolder=subfolder,
284
+ user_agent=user_agent,
285
+ )
286
+ state_dict = load_state_dict(model_file)
287
+ else:
288
+ state_dict = pretrained_model_name_or_path_or_dict
289
+
290
+ network_alphas = None
291
+ # TODO: replace it with a method from `state_dict_utils`
292
+ if all(
293
+ (
294
+ k.startswith("lora_te_")
295
+ or k.startswith("lora_unet_")
296
+ or k.startswith("lora_te1_")
297
+ or k.startswith("lora_te2_")
298
+ )
299
+ for k in state_dict.keys()
300
+ ):
301
+ # Map SDXL blocks correctly.
302
+ if unet_config is not None:
303
+ # use unet config to remap block numbers
304
+ state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
305
+ state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
306
+
307
+ return state_dict, network_alphas
308
+
309
+ @classmethod
310
+ def _best_guess_weight_name(
311
+ cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
312
+ ):
313
+ if local_files_only or HF_HUB_OFFLINE:
314
+ raise ValueError("When using the offline mode, you must specify a `weight_name`.")
315
+
316
+ targeted_files = []
317
+
318
+ if os.path.isfile(pretrained_model_name_or_path_or_dict):
319
+ return
320
+ elif os.path.isdir(pretrained_model_name_or_path_or_dict):
321
+ targeted_files = [
322
+ f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
323
+ ]
324
+ else:
325
+ files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
326
+ targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
327
+ if len(targeted_files) == 0:
328
+ return
329
+
330
+ # "scheduler" does not correspond to a LoRA checkpoint.
331
+ # "optimizer" does not correspond to a LoRA checkpoint
332
+ # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
333
+ unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
334
+ targeted_files = list(
335
+ filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
336
+ )
337
+
338
+ if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
339
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
340
+ elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
341
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
342
+
343
+ if len(targeted_files) > 1:
344
+ raise ValueError(
345
+ f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
346
+ )
347
+ weight_name = targeted_files[0]
348
+ return weight_name
349
+
350
+ @classmethod
351
+ def _optionally_disable_offloading(cls, _pipeline):
352
+ """
353
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
354
+
355
+ Args:
356
+ _pipeline (`DiffusionPipeline`):
357
+ The pipeline to disable offloading for.
358
+
359
+ Returns:
360
+ tuple:
361
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
362
+ """
363
+ is_model_cpu_offload = False
364
+ is_sequential_cpu_offload = False
365
+
366
+ if _pipeline is not None:
367
+ for _, component in _pipeline.components.items():
368
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
369
+ if not is_model_cpu_offload:
370
+ is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
371
+ if not is_sequential_cpu_offload:
372
+ is_sequential_cpu_offload = (
373
+ isinstance(component._hf_hook, AlignDevicesHook)
374
+ or hasattr(component._hf_hook, "hooks")
375
+ and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
376
+ )
377
+
378
+ logger.info(
379
+ "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
380
+ )
381
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
382
+
383
+ return (is_model_cpu_offload, is_sequential_cpu_offload)
384
+
385
+ @classmethod
386
+ def load_lora_into_unet(
387
+ cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
388
+ ):
389
+ """
390
+ This will load the LoRA layers specified in `state_dict` into `unet`.
391
+
392
+ Parameters:
393
+ state_dict (`dict`):
394
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
395
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
396
+ encoder lora layers.
397
+ network_alphas (`Dict[str, float]`):
398
+ See `LoRALinearLayer` for more details.
399
+ unet (`UNet2DConditionModel`):
400
+ The UNet model to load the LoRA layers into.
401
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
402
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
403
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
404
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
405
+ argument to `True` will raise an error.
406
+ adapter_name (`str`, *optional*):
407
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
408
+ `default_{i}` where i is the total number of adapters being loaded.
409
+ """
410
+ if not USE_PEFT_BACKEND:
411
+ raise ValueError("PEFT backend is required for this method.")
412
+
413
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
414
+
415
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
416
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
417
+ # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
418
+ # their prefixes.
419
+ keys = list(state_dict.keys())
420
+
421
+ if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
422
+ # Load the layers corresponding to UNet.
423
+ logger.info(f"Loading {cls.unet_name}.")
424
+
425
+ unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
426
+ state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
427
+
428
+ if network_alphas is not None:
429
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
430
+ network_alphas = {
431
+ k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
432
+ }
433
+
434
+ else:
435
+ # Otherwise, we're dealing with the old format. This means the `state_dict` should only
436
+ # contain the module names of the `unet` as its keys WITHOUT any prefix.
437
+ if not USE_PEFT_BACKEND:
438
+ warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
439
+ logger.warning(warn_message)
440
+
441
+ if len(state_dict.keys()) > 0:
442
+ if adapter_name in getattr(unet, "peft_config", {}):
443
+ raise ValueError(
444
+ f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
445
+ )
446
+
447
+ state_dict = convert_unet_state_dict_to_peft(state_dict)
448
+
449
+ if network_alphas is not None:
450
+ # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
451
+ # `convert_unet_state_dict_to_peft` method.
452
+ network_alphas = convert_unet_state_dict_to_peft(network_alphas)
453
+
454
+ rank = {}
455
+ for key, val in state_dict.items():
456
+ if "lora_B" in key:
457
+ rank[key] = val.shape[1]
458
+
459
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
460
+ if "use_dora" in lora_config_kwargs:
461
+ if lora_config_kwargs["use_dora"]:
462
+ if is_peft_version("<", "0.9.0"):
463
+ raise ValueError(
464
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
465
+ )
466
+ else:
467
+ if is_peft_version("<", "0.9.0"):
468
+ lora_config_kwargs.pop("use_dora")
469
+ lora_config = LoraConfig(**lora_config_kwargs)
470
+
471
+ # adapter_name
472
+ if adapter_name is None:
473
+ adapter_name = get_adapter_name(unet)
474
+
475
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
476
+ # otherwise loading LoRA weights will lead to an error
477
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
478
+
479
+ inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
480
+ incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
481
+
482
+ if incompatible_keys is not None:
483
+ # check only for unexpected keys
484
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
485
+ if unexpected_keys:
486
+ logger.warning(
487
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
488
+ f" {unexpected_keys}. "
489
+ )
490
+
491
+ # Offload back.
492
+ if is_model_cpu_offload:
493
+ _pipeline.enable_model_cpu_offload()
494
+ elif is_sequential_cpu_offload:
495
+ _pipeline.enable_sequential_cpu_offload()
496
+ # Unsafe code />
497
+
498
+ unet.load_attn_procs(
499
+ state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
500
+ )
501
+
502
+ @classmethod
503
+ def load_lora_into_text_encoder(
504
+ cls,
505
+ state_dict,
506
+ network_alphas,
507
+ text_encoder,
508
+ prefix=None,
509
+ lora_scale=1.0,
510
+ low_cpu_mem_usage=None,
511
+ adapter_name=None,
512
+ _pipeline=None,
513
+ ):
514
+ """
515
+ This will load the LoRA layers specified in `state_dict` into `text_encoder`
516
+
517
+ Parameters:
518
+ state_dict (`dict`):
519
+ A standard state dict containing the lora layer parameters. The key should be prefixed with an
520
+ additional `text_encoder` to distinguish between unet lora layers.
521
+ network_alphas (`Dict[str, float]`):
522
+ See `LoRALinearLayer` for more details.
523
+ text_encoder (`CLIPTextModel`):
524
+ The text encoder model to load the LoRA layers into.
525
+ prefix (`str`):
526
+ Expected prefix of the `text_encoder` in the `state_dict`.
527
+ lora_scale (`float`):
528
+ How much to scale the output of the lora linear layer before it is added with the output of the regular
529
+ lora layer.
530
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
531
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
532
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
533
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
534
+ argument to `True` will raise an error.
535
+ adapter_name (`str`, *optional*):
536
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
537
+ `default_{i}` where i is the total number of adapters being loaded.
538
+ """
539
+ if not USE_PEFT_BACKEND:
540
+ raise ValueError("PEFT backend is required for this method.")
541
+
542
+ from peft import LoraConfig
543
+
544
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
545
+
546
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
547
+ # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
548
+ # their prefixes.
549
+ keys = list(state_dict.keys())
550
+ prefix = cls.text_encoder_name if prefix is None else prefix
551
+
552
+ # Safe prefix to check with.
553
+ if any(cls.text_encoder_name in key for key in keys):
554
+ # Load the layers corresponding to text encoder and make necessary adjustments.
555
+ text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
556
+ text_encoder_lora_state_dict = {
557
+ k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
558
+ }
559
+
560
+ if len(text_encoder_lora_state_dict) > 0:
561
+ logger.info(f"Loading {prefix}.")
562
+ rank = {}
563
+ text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
564
+
565
+ # convert state dict
566
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
567
+
568
+ for name, _ in text_encoder_attn_modules(text_encoder):
569
+ rank_key = f"{name}.out_proj.lora_B.weight"
570
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
571
+
572
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
573
+ if patch_mlp:
574
+ for name, _ in text_encoder_mlp_modules(text_encoder):
575
+ rank_key_fc1 = f"{name}.fc1.lora_B.weight"
576
+ rank_key_fc2 = f"{name}.fc2.lora_B.weight"
577
+
578
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
579
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
580
+
581
+ if network_alphas is not None:
582
+ alpha_keys = [
583
+ k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
584
+ ]
585
+ network_alphas = {
586
+ k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
587
+ }
588
+
589
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
590
+ if "use_dora" in lora_config_kwargs:
591
+ if lora_config_kwargs["use_dora"]:
592
+ if is_peft_version("<", "0.9.0"):
593
+ raise ValueError(
594
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
595
+ )
596
+ else:
597
+ if is_peft_version("<", "0.9.0"):
598
+ lora_config_kwargs.pop("use_dora")
599
+ lora_config = LoraConfig(**lora_config_kwargs)
600
+
601
+ # adapter_name
602
+ if adapter_name is None:
603
+ adapter_name = get_adapter_name(text_encoder)
604
+
605
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
606
+
607
+ # inject LoRA layers and load the state dict
608
+ # in transformers we automatically check whether the adapter name is already in use or not
609
+ text_encoder.load_adapter(
610
+ adapter_name=adapter_name,
611
+ adapter_state_dict=text_encoder_lora_state_dict,
612
+ peft_config=lora_config,
613
+ )
614
+
615
+ # scale LoRA layers with `lora_scale`
616
+ scale_lora_layers(text_encoder, weight=lora_scale)
617
+
618
+ text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
619
+
620
+ # Offload back.
621
+ if is_model_cpu_offload:
622
+ _pipeline.enable_model_cpu_offload()
623
+ elif is_sequential_cpu_offload:
624
+ _pipeline.enable_sequential_cpu_offload()
625
+ # Unsafe code />
626
+
627
+ @classmethod
628
+ def load_lora_into_transformer(
629
+ cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
630
+ ):
631
+ """
632
+ This will load the LoRA layers specified in `state_dict` into `transformer`.
633
+
634
+ Parameters:
635
+ state_dict (`dict`):
636
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
637
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
638
+ encoder lora layers.
639
+ network_alphas (`Dict[str, float]`):
640
+ See `LoRALinearLayer` for more details.
641
+ unet (`UNet2DConditionModel`):
642
+ The UNet model to load the LoRA layers into.
643
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
644
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
645
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
646
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
647
+ argument to `True` will raise an error.
648
+ adapter_name (`str`, *optional*):
649
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
650
+ `default_{i}` where i is the total number of adapters being loaded.
651
+ """
652
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
653
+
654
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
655
+
656
+ keys = list(state_dict.keys())
657
+
658
+ transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
659
+ state_dict = {
660
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
661
+ }
662
+
663
+ if network_alphas is not None:
664
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
665
+ network_alphas = {
666
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
667
+ }
668
+
669
+ if len(state_dict.keys()) > 0:
670
+ if adapter_name in getattr(transformer, "peft_config", {}):
671
+ raise ValueError(
672
+ f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
673
+ )
674
+
675
+ rank = {}
676
+ for key, val in state_dict.items():
677
+ if "lora_B" in key:
678
+ rank[key] = val.shape[1]
679
+
680
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
681
+ if "use_dora" in lora_config_kwargs:
682
+ if lora_config_kwargs["use_dora"] and is_peft_version("<", "0.9.0"):
683
+ raise ValueError(
684
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
685
+ )
686
+ else:
687
+ lora_config_kwargs.pop("use_dora")
688
+ lora_config = LoraConfig(**lora_config_kwargs)
689
+
690
+ # adapter_name
691
+ if adapter_name is None:
692
+ adapter_name = get_adapter_name(transformer)
693
+
694
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
695
+ # otherwise loading LoRA weights will lead to an error
696
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
697
+
698
+ inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
699
+ incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
700
+
701
+ if incompatible_keys is not None:
702
+ # check only for unexpected keys
703
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
704
+ if unexpected_keys:
705
+ logger.warning(
706
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
707
+ f" {unexpected_keys}. "
708
+ )
709
+
710
+ # Offload back.
711
+ if is_model_cpu_offload:
712
+ _pipeline.enable_model_cpu_offload()
713
+ elif is_sequential_cpu_offload:
714
+ _pipeline.enable_sequential_cpu_offload()
715
+ # Unsafe code />
716
+
717
+ @property
718
+ def lora_scale(self) -> float:
719
+ # property function that returns the lora scale which can be set at run time by the pipeline.
720
+ # if _lora_scale has not been set, return 1
721
+ return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
722
+
723
+ def _remove_text_encoder_monkey_patch(self):
724
+ remove_method = recurse_remove_peft_layers
725
+ if hasattr(self, "text_encoder"):
726
+ remove_method(self.text_encoder)
727
+ # In case text encoder have no Lora attached
728
+ if getattr(self.text_encoder, "peft_config", None) is not None:
729
+ del self.text_encoder.peft_config
730
+ self.text_encoder._hf_peft_config_loaded = None
731
+
732
+ if hasattr(self, "text_encoder_2"):
733
+ remove_method(self.text_encoder_2)
734
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
735
+ del self.text_encoder_2.peft_config
736
+ self.text_encoder_2._hf_peft_config_loaded = None
737
+
738
+ @classmethod
739
+ def save_lora_weights(
740
+ cls,
741
+ save_directory: Union[str, os.PathLike],
742
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
743
+ text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
744
+ transformer_lora_layers: Dict[str, torch.nn.Module] = None,
745
+ is_main_process: bool = True,
746
+ weight_name: str = None,
747
+ save_function: Callable = None,
748
+ safe_serialization: bool = True,
749
+ ):
750
+ r"""
751
+ Save the LoRA parameters corresponding to the UNet and text encoder.
752
+
753
+ Arguments:
754
+ save_directory (`str` or `os.PathLike`):
755
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
756
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
757
+ State dict of the LoRA layers corresponding to the `unet`.
758
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
759
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
760
+ encoder LoRA state dict because it comes from 🤗 Transformers.
761
+ is_main_process (`bool`, *optional*, defaults to `True`):
762
+ Whether the process calling this is the main process or not. Useful during distributed training and you
763
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
764
+ process to avoid race conditions.
765
+ save_function (`Callable`):
766
+ The function to use to save the state dictionary. Useful during distributed training when you need to
767
+ replace `torch.save` with another method. Can be configured with the environment variable
768
+ `DIFFUSERS_SAVE_MODE`.
769
+ safe_serialization (`bool`, *optional*, defaults to `True`):
770
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
771
+ """
772
+ state_dict = {}
773
+
774
+ def pack_weights(layers, prefix):
775
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
776
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
777
+ return layers_state_dict
778
+
779
+ if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
780
+ raise ValueError(
781
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
782
+ )
783
+
784
+ if unet_lora_layers:
785
+ state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
786
+
787
+ if text_encoder_lora_layers:
788
+ state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
789
+
790
+ if transformer_lora_layers:
791
+ state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
792
+
793
+ # Save the model
794
+ cls.write_lora_layers(
795
+ state_dict=state_dict,
796
+ save_directory=save_directory,
797
+ is_main_process=is_main_process,
798
+ weight_name=weight_name,
799
+ save_function=save_function,
800
+ safe_serialization=safe_serialization,
801
+ )
802
+
803
+ @staticmethod
804
+ def write_lora_layers(
805
+ state_dict: Dict[str, torch.Tensor],
806
+ save_directory: str,
807
+ is_main_process: bool,
808
+ weight_name: str,
809
+ save_function: Callable,
810
+ safe_serialization: bool,
811
+ ):
812
+ if os.path.isfile(save_directory):
813
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
814
+ return
815
+
816
+ if save_function is None:
817
+ if safe_serialization:
818
+
819
+ def save_function(weights, filename):
820
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
821
+
822
+ else:
823
+ save_function = torch.save
824
+
825
+ os.makedirs(save_directory, exist_ok=True)
826
+
827
+ if weight_name is None:
828
+ if safe_serialization:
829
+ weight_name = LORA_WEIGHT_NAME_SAFE
830
+ else:
831
+ weight_name = LORA_WEIGHT_NAME
832
+
833
+ save_path = Path(save_directory, weight_name).as_posix()
834
+ save_function(state_dict, save_path)
835
+ logger.info(f"Model weights saved in {save_path}")
836
+
837
+ def unload_lora_weights(self):
838
+ """
839
+ Unloads the LoRA parameters.
840
+
841
+ Examples:
842
+
843
+ ```python
844
+ >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
845
+ >>> pipeline.unload_lora_weights()
846
+ >>> ...
847
+ ```
848
+ """
849
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
850
+
851
+ if not USE_PEFT_BACKEND:
852
+ if version.parse(__version__) > version.parse("0.23"):
853
+ logger.warning(
854
+ "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
855
+ "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
856
+ )
857
+
858
+ for _, module in unet.named_modules():
859
+ if hasattr(module, "set_lora_layer"):
860
+ module.set_lora_layer(None)
861
+ else:
862
+ recurse_remove_peft_layers(unet)
863
+ if hasattr(unet, "peft_config"):
864
+ del unet.peft_config
865
+
866
+ # Safe to call the following regardless of LoRA.
867
+ self._remove_text_encoder_monkey_patch()
868
+
869
+ def fuse_lora(
870
+ self,
871
+ fuse_unet: bool = True,
872
+ fuse_text_encoder: bool = True,
873
+ lora_scale: float = 1.0,
874
+ safe_fusing: bool = False,
875
+ adapter_names: Optional[List[str]] = None,
876
+ ):
877
+ r"""
878
+ Fuses the LoRA parameters into the original parameters of the corresponding blocks.
879
+
880
+ <Tip warning={true}>
881
+
882
+ This is an experimental API.
883
+
884
+ </Tip>
885
+
886
+ Args:
887
+ fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
888
+ fuse_text_encoder (`bool`, defaults to `True`):
889
+ Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
890
+ LoRA parameters then it won't have any effect.
891
+ lora_scale (`float`, defaults to 1.0):
892
+ Controls how much to influence the outputs with the LoRA parameters.
893
+ safe_fusing (`bool`, defaults to `False`):
894
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
895
+ adapter_names (`List[str]`, *optional*):
896
+ Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
897
+
898
+ Example:
899
+
900
+ ```py
901
+ from diffusers import DiffusionPipeline
902
+ import torch
903
+
904
+ pipeline = DiffusionPipeline.from_pretrained(
905
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
906
+ ).to("cuda")
907
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
908
+ pipeline.fuse_lora(lora_scale=0.7)
909
+ ```
910
+ """
911
+ from peft.tuners.tuners_utils import BaseTunerLayer
912
+
913
+ if fuse_unet or fuse_text_encoder:
914
+ self.num_fused_loras += 1
915
+ if self.num_fused_loras > 1:
916
+ logger.warning(
917
+ "The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
918
+ )
919
+
920
+ if fuse_unet:
921
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
922
+ unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
923
+
924
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
925
+ merge_kwargs = {"safe_merge": safe_fusing}
926
+
927
+ for module in text_encoder.modules():
928
+ if isinstance(module, BaseTunerLayer):
929
+ if lora_scale != 1.0:
930
+ module.scale_layer(lora_scale)
931
+
932
+ # For BC with previous PEFT versions, we need to check the signature
933
+ # of the `merge` method to see if it supports the `adapter_names` argument.
934
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
935
+ if "adapter_names" in supported_merge_kwargs:
936
+ merge_kwargs["adapter_names"] = adapter_names
937
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
938
+ raise ValueError(
939
+ "The `adapter_names` argument is not supported with your PEFT version. "
940
+ "Please upgrade to the latest version of PEFT. `pip install -U peft`"
941
+ )
942
+
943
+ module.merge(**merge_kwargs)
944
+
945
+ if fuse_text_encoder:
946
+ if hasattr(self, "text_encoder"):
947
+ fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
948
+ if hasattr(self, "text_encoder_2"):
949
+ fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
950
+
951
+ def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
952
+ r"""
953
+ Reverses the effect of
954
+ [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
955
+
956
+ <Tip warning={true}>
957
+
958
+ This is an experimental API.
959
+
960
+ </Tip>
961
+
962
+ Args:
963
+ unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
964
+ unfuse_text_encoder (`bool`, defaults to `True`):
965
+ Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
966
+ LoRA parameters then it won't have any effect.
967
+ """
968
+ from peft.tuners.tuners_utils import BaseTunerLayer
969
+
970
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
971
+ if unfuse_unet:
972
+ for module in unet.modules():
973
+ if isinstance(module, BaseTunerLayer):
974
+ module.unmerge()
975
+
976
+ def unfuse_text_encoder_lora(text_encoder):
977
+ for module in text_encoder.modules():
978
+ if isinstance(module, BaseTunerLayer):
979
+ module.unmerge()
980
+
981
+ if unfuse_text_encoder:
982
+ if hasattr(self, "text_encoder"):
983
+ unfuse_text_encoder_lora(self.text_encoder)
984
+ if hasattr(self, "text_encoder_2"):
985
+ unfuse_text_encoder_lora(self.text_encoder_2)
986
+
987
+ self.num_fused_loras -= 1
988
+
989
+ def set_adapters_for_text_encoder(
990
+ self,
991
+ adapter_names: Union[List[str], str],
992
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
993
+ text_encoder_weights: Optional[Union[float, List[float], List[None]]] = None,
994
+ ):
995
+ """
996
+ Sets the adapter layers for the text encoder.
997
+
998
+ Args:
999
+ adapter_names (`List[str]` or `str`):
1000
+ The names of the adapters to use.
1001
+ text_encoder (`torch.nn.Module`, *optional*):
1002
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
1003
+ attribute.
1004
+ text_encoder_weights (`List[float]`, *optional*):
1005
+ The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
1006
+ """
1007
+ if not USE_PEFT_BACKEND:
1008
+ raise ValueError("PEFT backend is required for this method.")
1009
+
1010
+ def process_weights(adapter_names, weights):
1011
+ # Expand weights into a list, one entry per adapter
1012
+ # e.g. for 2 adapters: 7 -> [7,7] ; [3, None] -> [3, None]
1013
+ if not isinstance(weights, list):
1014
+ weights = [weights] * len(adapter_names)
1015
+
1016
+ if len(adapter_names) != len(weights):
1017
+ raise ValueError(
1018
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
1019
+ )
1020
+
1021
+ # Set None values to default of 1.0
1022
+ # e.g. [7,7] -> [7,7] ; [3, None] -> [3,1]
1023
+ weights = [w if w is not None else 1.0 for w in weights]
1024
+
1025
+ return weights
1026
+
1027
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1028
+ text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
1029
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1030
+ if text_encoder is None:
1031
+ raise ValueError(
1032
+ "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
1033
+ )
1034
+ set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
1035
+
1036
+ def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1037
+ """
1038
+ Disables the LoRA layers for the text encoder.
1039
+
1040
+ Args:
1041
+ text_encoder (`torch.nn.Module`, *optional*):
1042
+ The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1043
+ `text_encoder` attribute.
1044
+ """
1045
+ if not USE_PEFT_BACKEND:
1046
+ raise ValueError("PEFT backend is required for this method.")
1047
+
1048
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1049
+ if text_encoder is None:
1050
+ raise ValueError("Text Encoder not found.")
1051
+ set_adapter_layers(text_encoder, enabled=False)
1052
+
1053
+ def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1054
+ """
1055
+ Enables the LoRA layers for the text encoder.
1056
+
1057
+ Args:
1058
+ text_encoder (`torch.nn.Module`, *optional*):
1059
+ The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1060
+ attribute.
1061
+ """
1062
+ if not USE_PEFT_BACKEND:
1063
+ raise ValueError("PEFT backend is required for this method.")
1064
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1065
+ if text_encoder is None:
1066
+ raise ValueError("Text Encoder not found.")
1067
+ set_adapter_layers(self.text_encoder, enabled=True)
1068
+
1069
+ def set_adapters(
1070
+ self,
1071
+ adapter_names: Union[List[str], str],
1072
+ adapter_weights: Optional[Union[float, Dict, List[float], List[Dict]]] = None,
1073
+ ):
1074
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1075
+
1076
+ adapter_weights = copy.deepcopy(adapter_weights)
1077
+
1078
+ # Expand weights into a list, one entry per adapter
1079
+ if not isinstance(adapter_weights, list):
1080
+ adapter_weights = [adapter_weights] * len(adapter_names)
1081
+
1082
+ if len(adapter_names) != len(adapter_weights):
1083
+ raise ValueError(
1084
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(adapter_weights)}"
1085
+ )
1086
+
1087
+ # Decompose weights into weights for unet, text_encoder and text_encoder_2
1088
+ unet_lora_weights, text_encoder_lora_weights, text_encoder_2_lora_weights = [], [], []
1089
+
1090
+ list_adapters = self.get_list_adapters() # eg {"unet": ["adapter1", "adapter2"], "text_encoder": ["adapter2"]}
1091
+ all_adapters = {
1092
+ adapter for adapters in list_adapters.values() for adapter in adapters
1093
+ } # eg ["adapter1", "adapter2"]
1094
+ invert_list_adapters = {
1095
+ adapter: [part for part, adapters in list_adapters.items() if adapter in adapters]
1096
+ for adapter in all_adapters
1097
+ } # eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]}
1098
+
1099
+ for adapter_name, weights in zip(adapter_names, adapter_weights):
1100
+ if isinstance(weights, dict):
1101
+ unet_lora_weight = weights.pop("unet", None)
1102
+ text_encoder_lora_weight = weights.pop("text_encoder", None)
1103
+ text_encoder_2_lora_weight = weights.pop("text_encoder_2", None)
1104
+
1105
+ if len(weights) > 0:
1106
+ raise ValueError(
1107
+ f"Got invalid key '{weights.keys()}' in lora weight dict for adapter {adapter_name}."
1108
+ )
1109
+
1110
+ if text_encoder_2_lora_weight is not None and not hasattr(self, "text_encoder_2"):
1111
+ logger.warning(
1112
+ "Lora weight dict contains text_encoder_2 weights but will be ignored because pipeline does not have text_encoder_2."
1113
+ )
1114
+
1115
+ # warn if adapter doesn't have parts specified by adapter_weights
1116
+ for part_weight, part_name in zip(
1117
+ [unet_lora_weight, text_encoder_lora_weight, text_encoder_2_lora_weight],
1118
+ ["unet", "text_encoder", "text_encoder_2"],
1119
+ ):
1120
+ if part_weight is not None and part_name not in invert_list_adapters[adapter_name]:
1121
+ logger.warning(
1122
+ f"Lora weight dict for adapter '{adapter_name}' contains {part_name}, but this will be ignored because {adapter_name} does not contain weights for {part_name}. Valid parts for {adapter_name} are: {invert_list_adapters[adapter_name]}."
1123
+ )
1124
+
1125
+ else:
1126
+ unet_lora_weight = weights
1127
+ text_encoder_lora_weight = weights
1128
+ text_encoder_2_lora_weight = weights
1129
+
1130
+ unet_lora_weights.append(unet_lora_weight)
1131
+ text_encoder_lora_weights.append(text_encoder_lora_weight)
1132
+ text_encoder_2_lora_weights.append(text_encoder_2_lora_weight)
1133
+
1134
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1135
+ # Handle the UNET
1136
+ unet.set_adapters(adapter_names, unet_lora_weights)
1137
+
1138
+ # Handle the Text Encoder
1139
+ if hasattr(self, "text_encoder"):
1140
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, text_encoder_lora_weights)
1141
+ if hasattr(self, "text_encoder_2"):
1142
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, text_encoder_2_lora_weights)
1143
+
1144
+ def disable_lora(self):
1145
+ if not USE_PEFT_BACKEND:
1146
+ raise ValueError("PEFT backend is required for this method.")
1147
+
1148
+ # Disable unet adapters
1149
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1150
+ unet.disable_lora()
1151
+
1152
+ # Disable text encoder adapters
1153
+ if hasattr(self, "text_encoder"):
1154
+ self.disable_lora_for_text_encoder(self.text_encoder)
1155
+ if hasattr(self, "text_encoder_2"):
1156
+ self.disable_lora_for_text_encoder(self.text_encoder_2)
1157
+
1158
+ def enable_lora(self):
1159
+ if not USE_PEFT_BACKEND:
1160
+ raise ValueError("PEFT backend is required for this method.")
1161
+
1162
+ # Enable unet adapters
1163
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1164
+ unet.enable_lora()
1165
+
1166
+ # Enable text encoder adapters
1167
+ if hasattr(self, "text_encoder"):
1168
+ self.enable_lora_for_text_encoder(self.text_encoder)
1169
+ if hasattr(self, "text_encoder_2"):
1170
+ self.enable_lora_for_text_encoder(self.text_encoder_2)
1171
+
1172
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
1173
+ """
1174
+ Args:
1175
+ Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1176
+ adapter_names (`Union[List[str], str]`):
1177
+ The names of the adapter to delete. Can be a single string or a list of strings
1178
+ """
1179
+ if not USE_PEFT_BACKEND:
1180
+ raise ValueError("PEFT backend is required for this method.")
1181
+
1182
+ if isinstance(adapter_names, str):
1183
+ adapter_names = [adapter_names]
1184
+
1185
+ # Delete unet adapters
1186
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1187
+ unet.delete_adapters(adapter_names)
1188
+
1189
+ for adapter_name in adapter_names:
1190
+ # Delete text encoder adapters
1191
+ if hasattr(self, "text_encoder"):
1192
+ delete_adapter_layers(self.text_encoder, adapter_name)
1193
+ if hasattr(self, "text_encoder_2"):
1194
+ delete_adapter_layers(self.text_encoder_2, adapter_name)
1195
+
1196
+ def get_active_adapters(self) -> List[str]:
1197
+ """
1198
+ Gets the list of the current active adapters.
1199
+
1200
+ Example:
1201
+
1202
+ ```python
1203
+ from diffusers import DiffusionPipeline
1204
+
1205
+ pipeline = DiffusionPipeline.from_pretrained(
1206
+ "stabilityai/stable-diffusion-xl-base-1.0",
1207
+ ).to("cuda")
1208
+ pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1209
+ pipeline.get_active_adapters()
1210
+ ```
1211
+ """
1212
+ if not USE_PEFT_BACKEND:
1213
+ raise ValueError(
1214
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1215
+ )
1216
+
1217
+ from peft.tuners.tuners_utils import BaseTunerLayer
1218
+
1219
+ active_adapters = []
1220
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1221
+ for module in unet.modules():
1222
+ if isinstance(module, BaseTunerLayer):
1223
+ active_adapters = module.active_adapters
1224
+ break
1225
+
1226
+ return active_adapters
1227
+
1228
+ def get_list_adapters(self) -> Dict[str, List[str]]:
1229
+ """
1230
+ Gets the current list of all available adapters in the pipeline.
1231
+ """
1232
+ if not USE_PEFT_BACKEND:
1233
+ raise ValueError(
1234
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1235
+ )
1236
+
1237
+ set_adapters = {}
1238
+
1239
+ if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1240
+ set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1241
+
1242
+ if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1243
+ set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1244
+
1245
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1246
+ if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1247
+ set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1248
+
1249
+ return set_adapters
1250
+
1251
+ def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1252
+ """
1253
+ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1254
+ you want to load multiple adapters and free some GPU memory.
1255
+
1256
+ Args:
1257
+ adapter_names (`List[str]`):
1258
+ List of adapters to send device to.
1259
+ device (`Union[torch.device, str, int]`):
1260
+ Device to send the adapters to. Can be either a torch device, a str or an integer.
1261
+ """
1262
+ if not USE_PEFT_BACKEND:
1263
+ raise ValueError("PEFT backend is required for this method.")
1264
+
1265
+ from peft.tuners.tuners_utils import BaseTunerLayer
1266
+
1267
+ # Handle the UNET
1268
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1269
+ for unet_module in unet.modules():
1270
+ if isinstance(unet_module, BaseTunerLayer):
1271
+ for adapter_name in adapter_names:
1272
+ unet_module.lora_A[adapter_name].to(device)
1273
+ unet_module.lora_B[adapter_name].to(device)
1274
+ # this is a param, not a module, so device placement is not in-place -> re-assign
1275
+ if hasattr(unet_module, "lora_magnitude_vector") and unet_module.lora_magnitude_vector is not None:
1276
+ unet_module.lora_magnitude_vector[adapter_name] = unet_module.lora_magnitude_vector[
1277
+ adapter_name
1278
+ ].to(device)
1279
+
1280
+ # Handle the text encoder
1281
+ modules_to_process = []
1282
+ if hasattr(self, "text_encoder"):
1283
+ modules_to_process.append(self.text_encoder)
1284
+
1285
+ if hasattr(self, "text_encoder_2"):
1286
+ modules_to_process.append(self.text_encoder_2)
1287
+
1288
+ for text_encoder in modules_to_process:
1289
+ # loop over submodules
1290
+ for text_encoder_module in text_encoder.modules():
1291
+ if isinstance(text_encoder_module, BaseTunerLayer):
1292
+ for adapter_name in adapter_names:
1293
+ text_encoder_module.lora_A[adapter_name].to(device)
1294
+ text_encoder_module.lora_B[adapter_name].to(device)
1295
+ # this is a param, not a module, so device placement is not in-place -> re-assign
1296
+ if (
1297
+ hasattr(text_encoder, "lora_magnitude_vector")
1298
+ and text_encoder_module.lora_magnitude_vector is not None
1299
+ ):
1300
+ text_encoder_module.lora_magnitude_vector[
1301
+ adapter_name
1302
+ ] = text_encoder_module.lora_magnitude_vector[adapter_name].to(device)
1303
+
1304
+
1305
+ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1306
+ """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1307
+
1308
+ # Override to properly handle the loading and unloading of the additional text encoder.
1309
+ def load_lora_weights(
1310
+ self,
1311
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1312
+ adapter_name: Optional[str] = None,
1313
+ **kwargs,
1314
+ ):
1315
+ """
1316
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1317
+ `self.text_encoder`.
1318
+
1319
+ All kwargs are forwarded to `self.lora_state_dict`.
1320
+
1321
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1322
+
1323
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1324
+ `self.unet`.
1325
+
1326
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1327
+ into `self.text_encoder`.
1328
+
1329
+ Parameters:
1330
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1331
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1332
+ adapter_name (`str`, *optional*):
1333
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1334
+ `default_{i}` where i is the total number of adapters being loaded.
1335
+ kwargs (`dict`, *optional*):
1336
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1337
+ """
1338
+ if not USE_PEFT_BACKEND:
1339
+ raise ValueError("PEFT backend is required for this method.")
1340
+
1341
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1342
+ # it here explicitly to be able to tell that it's coming from an SDXL
1343
+ # pipeline.
1344
+
1345
+ # if a dict is passed, copy it instead of modifying it inplace
1346
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
1347
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1348
+
1349
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1350
+ state_dict, network_alphas = self.lora_state_dict(
1351
+ pretrained_model_name_or_path_or_dict,
1352
+ unet_config=self.unet.config,
1353
+ **kwargs,
1354
+ )
1355
+ is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
1356
+ if not is_correct_format:
1357
+ raise ValueError("Invalid LoRA checkpoint.")
1358
+
1359
+ self.load_lora_into_unet(
1360
+ state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1361
+ )
1362
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1363
+ if len(text_encoder_state_dict) > 0:
1364
+ self.load_lora_into_text_encoder(
1365
+ text_encoder_state_dict,
1366
+ network_alphas=network_alphas,
1367
+ text_encoder=self.text_encoder,
1368
+ prefix="text_encoder",
1369
+ lora_scale=self.lora_scale,
1370
+ adapter_name=adapter_name,
1371
+ _pipeline=self,
1372
+ )
1373
+
1374
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1375
+ if len(text_encoder_2_state_dict) > 0:
1376
+ self.load_lora_into_text_encoder(
1377
+ text_encoder_2_state_dict,
1378
+ network_alphas=network_alphas,
1379
+ text_encoder=self.text_encoder_2,
1380
+ prefix="text_encoder_2",
1381
+ lora_scale=self.lora_scale,
1382
+ adapter_name=adapter_name,
1383
+ _pipeline=self,
1384
+ )
1385
+
1386
+ @classmethod
1387
+ def save_lora_weights(
1388
+ cls,
1389
+ save_directory: Union[str, os.PathLike],
1390
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1391
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1392
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1393
+ is_main_process: bool = True,
1394
+ weight_name: str = None,
1395
+ save_function: Callable = None,
1396
+ safe_serialization: bool = True,
1397
+ ):
1398
+ r"""
1399
+ Save the LoRA parameters corresponding to the UNet and text encoder.
1400
+
1401
+ Arguments:
1402
+ save_directory (`str` or `os.PathLike`):
1403
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
1404
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1405
+ State dict of the LoRA layers corresponding to the `unet`.
1406
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1407
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1408
+ encoder LoRA state dict because it comes from 🤗 Transformers.
1409
+ is_main_process (`bool`, *optional*, defaults to `True`):
1410
+ Whether the process calling this is the main process or not. Useful during distributed training and you
1411
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1412
+ process to avoid race conditions.
1413
+ save_function (`Callable`):
1414
+ The function to use to save the state dictionary. Useful during distributed training when you need to
1415
+ replace `torch.save` with another method. Can be configured with the environment variable
1416
+ `DIFFUSERS_SAVE_MODE`.
1417
+ safe_serialization (`bool`, *optional*, defaults to `True`):
1418
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1419
+ """
1420
+ state_dict = {}
1421
+
1422
+ def pack_weights(layers, prefix):
1423
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1424
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1425
+ return layers_state_dict
1426
+
1427
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1428
+ raise ValueError(
1429
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1430
+ )
1431
+
1432
+ if unet_lora_layers:
1433
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1434
+
1435
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1436
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1437
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1438
+
1439
+ cls.write_lora_layers(
1440
+ state_dict=state_dict,
1441
+ save_directory=save_directory,
1442
+ is_main_process=is_main_process,
1443
+ weight_name=weight_name,
1444
+ save_function=save_function,
1445
+ safe_serialization=safe_serialization,
1446
+ )
1447
+
1448
+ def _remove_text_encoder_monkey_patch(self):
1449
+ recurse_remove_peft_layers(self.text_encoder)
1450
+ # TODO: @younesbelkada handle this in transformers side
1451
+ if getattr(self.text_encoder, "peft_config", None) is not None:
1452
+ del self.text_encoder.peft_config
1453
+ self.text_encoder._hf_peft_config_loaded = None
1454
+
1455
+ recurse_remove_peft_layers(self.text_encoder_2)
1456
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
1457
+ del self.text_encoder_2.peft_config
1458
+ self.text_encoder_2._hf_peft_config_loaded = None
diffusers/loaders/lora_conversion_utils.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+
17
+ from ..utils import is_peft_version, logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter="_", block_slice_pos=5):
24
+ # 1. get all state_dict_keys
25
+ all_keys = list(state_dict.keys())
26
+ sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
27
+
28
+ # 2. check if needs remapping, if not return original dict
29
+ is_in_sgm_format = False
30
+ for key in all_keys:
31
+ if any(p in key for p in sgm_patterns):
32
+ is_in_sgm_format = True
33
+ break
34
+
35
+ if not is_in_sgm_format:
36
+ return state_dict
37
+
38
+ # 3. Else remap from SGM patterns
39
+ new_state_dict = {}
40
+ inner_block_map = ["resnets", "attentions", "upsamplers"]
41
+
42
+ # Retrieves # of down, mid and up blocks
43
+ input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
44
+
45
+ for layer in all_keys:
46
+ if "text" in layer:
47
+ new_state_dict[layer] = state_dict.pop(layer)
48
+ else:
49
+ layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
50
+ if sgm_patterns[0] in layer:
51
+ input_block_ids.add(layer_id)
52
+ elif sgm_patterns[1] in layer:
53
+ middle_block_ids.add(layer_id)
54
+ elif sgm_patterns[2] in layer:
55
+ output_block_ids.add(layer_id)
56
+ else:
57
+ raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
58
+
59
+ input_blocks = {
60
+ layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
61
+ for layer_id in input_block_ids
62
+ }
63
+ middle_blocks = {
64
+ layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
65
+ for layer_id in middle_block_ids
66
+ }
67
+ output_blocks = {
68
+ layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
69
+ for layer_id in output_block_ids
70
+ }
71
+
72
+ # Rename keys accordingly
73
+ for i in input_block_ids:
74
+ block_id = (i - 1) // (unet_config.layers_per_block + 1)
75
+ layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
76
+
77
+ for key in input_blocks[i]:
78
+ inner_block_id = int(key.split(delimiter)[block_slice_pos])
79
+ inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
80
+ inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
81
+ new_key = delimiter.join(
82
+ key.split(delimiter)[: block_slice_pos - 1]
83
+ + [str(block_id), inner_block_key, inner_layers_in_block]
84
+ + key.split(delimiter)[block_slice_pos + 1 :]
85
+ )
86
+ new_state_dict[new_key] = state_dict.pop(key)
87
+
88
+ for i in middle_block_ids:
89
+ key_part = None
90
+ if i == 0:
91
+ key_part = [inner_block_map[0], "0"]
92
+ elif i == 1:
93
+ key_part = [inner_block_map[1], "0"]
94
+ elif i == 2:
95
+ key_part = [inner_block_map[0], "1"]
96
+ else:
97
+ raise ValueError(f"Invalid middle block id {i}.")
98
+
99
+ for key in middle_blocks[i]:
100
+ new_key = delimiter.join(
101
+ key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
102
+ )
103
+ new_state_dict[new_key] = state_dict.pop(key)
104
+
105
+ for i in output_block_ids:
106
+ block_id = i // (unet_config.layers_per_block + 1)
107
+ layer_in_block_id = i % (unet_config.layers_per_block + 1)
108
+
109
+ for key in output_blocks[i]:
110
+ inner_block_id = int(key.split(delimiter)[block_slice_pos])
111
+ inner_block_key = inner_block_map[inner_block_id]
112
+ inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
113
+ new_key = delimiter.join(
114
+ key.split(delimiter)[: block_slice_pos - 1]
115
+ + [str(block_id), inner_block_key, inner_layers_in_block]
116
+ + key.split(delimiter)[block_slice_pos + 1 :]
117
+ )
118
+ new_state_dict[new_key] = state_dict.pop(key)
119
+
120
+ if len(state_dict) > 0:
121
+ raise ValueError("At this point all state dict entries have to be converted.")
122
+
123
+ return new_state_dict
124
+
125
+
126
+ def _convert_kohya_lora_to_diffusers(state_dict, unet_name="unet", text_encoder_name="text_encoder"):
127
+ unet_state_dict = {}
128
+ te_state_dict = {}
129
+ te2_state_dict = {}
130
+ network_alphas = {}
131
+ is_unet_dora_lora = any("dora_scale" in k and "lora_unet_" in k for k in state_dict)
132
+ is_te_dora_lora = any("dora_scale" in k and ("lora_te_" in k or "lora_te1_" in k) for k in state_dict)
133
+ is_te2_dora_lora = any("dora_scale" in k and "lora_te2_" in k for k in state_dict)
134
+
135
+ if is_unet_dora_lora or is_te_dora_lora or is_te2_dora_lora:
136
+ if is_peft_version("<", "0.9.0"):
137
+ raise ValueError(
138
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
139
+ )
140
+
141
+ # every down weight has a corresponding up weight and potentially an alpha weight
142
+ lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
143
+ for key in lora_keys:
144
+ lora_name = key.split(".")[0]
145
+ lora_name_up = lora_name + ".lora_up.weight"
146
+ lora_name_alpha = lora_name + ".alpha"
147
+
148
+ if lora_name.startswith("lora_unet_"):
149
+ diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
150
+
151
+ if "input.blocks" in diffusers_name:
152
+ diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
153
+ else:
154
+ diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
155
+
156
+ if "middle.block" in diffusers_name:
157
+ diffusers_name = diffusers_name.replace("middle.block", "mid_block")
158
+ else:
159
+ diffusers_name = diffusers_name.replace("mid.block", "mid_block")
160
+ if "output.blocks" in diffusers_name:
161
+ diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
162
+ else:
163
+ diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
164
+
165
+ diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
166
+ diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
167
+ diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
168
+ diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
169
+ diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
170
+ diffusers_name = diffusers_name.replace("proj.in", "proj_in")
171
+ diffusers_name = diffusers_name.replace("proj.out", "proj_out")
172
+ diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
173
+
174
+ # SDXL specificity.
175
+ if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
176
+ pattern = r"\.\d+(?=\D*$)"
177
+ diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
178
+ if ".in." in diffusers_name:
179
+ diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
180
+ if ".out." in diffusers_name:
181
+ diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
182
+ if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
183
+ diffusers_name = diffusers_name.replace("op", "conv")
184
+ if "skip" in diffusers_name:
185
+ diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
186
+
187
+ # LyCORIS specificity.
188
+ if "time.emb.proj" in diffusers_name:
189
+ diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
190
+ if "conv.shortcut" in diffusers_name:
191
+ diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
192
+
193
+ # General coverage.
194
+ if "transformer_blocks" in diffusers_name:
195
+ if "attn1" in diffusers_name or "attn2" in diffusers_name:
196
+ diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
197
+ diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
198
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
199
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
200
+ elif "ff" in diffusers_name:
201
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
202
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
203
+ elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
204
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
205
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
206
+ else:
207
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
208
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
209
+
210
+ if is_unet_dora_lora:
211
+ dora_scale_key_to_replace = "_lora.down." if "_lora.down." in diffusers_name else ".lora.down."
212
+ unet_state_dict[
213
+ diffusers_name.replace(dora_scale_key_to_replace, ".lora_magnitude_vector.")
214
+ ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
215
+
216
+ elif lora_name.startswith(("lora_te_", "lora_te1_", "lora_te2_")):
217
+ if lora_name.startswith(("lora_te_", "lora_te1_")):
218
+ key_to_replace = "lora_te_" if lora_name.startswith("lora_te_") else "lora_te1_"
219
+ else:
220
+ key_to_replace = "lora_te2_"
221
+
222
+ diffusers_name = key.replace(key_to_replace, "").replace("_", ".")
223
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
224
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
225
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
226
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
227
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
228
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
229
+ if "self_attn" in diffusers_name:
230
+ if lora_name.startswith(("lora_te_", "lora_te1_")):
231
+ te_state_dict[diffusers_name] = state_dict.pop(key)
232
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
233
+ else:
234
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
235
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
236
+ elif "mlp" in diffusers_name:
237
+ # Be aware that this is the new diffusers convention and the rest of the code might
238
+ # not utilize it yet.
239
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
240
+ if lora_name.startswith(("lora_te_", "lora_te1_")):
241
+ te_state_dict[diffusers_name] = state_dict.pop(key)
242
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
243
+ else:
244
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
245
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
246
+
247
+ if (is_te_dora_lora or is_te2_dora_lora) and lora_name.startswith(("lora_te_", "lora_te1_", "lora_te2_")):
248
+ dora_scale_key_to_replace_te = (
249
+ "_lora.down." if "_lora.down." in diffusers_name else ".lora_linear_layer."
250
+ )
251
+ if lora_name.startswith(("lora_te_", "lora_te1_")):
252
+ te_state_dict[
253
+ diffusers_name.replace(dora_scale_key_to_replace_te, ".lora_magnitude_vector.")
254
+ ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
255
+ elif lora_name.startswith("lora_te2_"):
256
+ te2_state_dict[
257
+ diffusers_name.replace(dora_scale_key_to_replace_te, ".lora_magnitude_vector.")
258
+ ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
259
+
260
+ # Rename the alphas so that they can be mapped appropriately.
261
+ if lora_name_alpha in state_dict:
262
+ alpha = state_dict.pop(lora_name_alpha).item()
263
+ if lora_name_alpha.startswith("lora_unet_"):
264
+ prefix = "unet."
265
+ elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
266
+ prefix = "text_encoder."
267
+ else:
268
+ prefix = "text_encoder_2."
269
+ new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
270
+ network_alphas.update({new_name: alpha})
271
+
272
+ if len(state_dict) > 0:
273
+ raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
274
+
275
+ logger.info("Kohya-style checkpoint detected.")
276
+ unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
277
+ te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
278
+ te2_state_dict = (
279
+ {f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
280
+ if len(te2_state_dict) > 0
281
+ else None
282
+ )
283
+ if te2_state_dict is not None:
284
+ te_state_dict.update(te2_state_dict)
285
+
286
+ new_state_dict = {**unet_state_dict, **te_state_dict}
287
+ return new_state_dict, network_alphas
diffusers/loaders/peft.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from typing import List, Union
16
+
17
+ from ..utils import MIN_PEFT_VERSION, check_peft_version, is_peft_available
18
+
19
+
20
+ class PeftAdapterMixin:
21
+ """
22
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
23
+ more details about adapters and injecting them in a transformer-based model, check out the PEFT
24
+ [documentation](https://huggingface.co/docs/peft/index).
25
+
26
+ Install the latest version of PEFT, and use this mixin to:
27
+
28
+ - Attach new adapters in the model.
29
+ - Attach multiple adapters and iteratively activate/deactivate them.
30
+ - Activate/deactivate all adapters from the model.
31
+ - Get a list of the active adapters.
32
+ """
33
+
34
+ _hf_peft_config_loaded = False
35
+
36
+ def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
37
+ r"""
38
+ Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
39
+ to the adapter to follow the convention of the PEFT library.
40
+
41
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
42
+ [documentation](https://huggingface.co/docs/peft).
43
+
44
+ Args:
45
+ adapter_config (`[~peft.PeftConfig]`):
46
+ The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
47
+ methods.
48
+ adapter_name (`str`, *optional*, defaults to `"default"`):
49
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
50
+ """
51
+ check_peft_version(min_version=MIN_PEFT_VERSION)
52
+
53
+ if not is_peft_available():
54
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
55
+
56
+ from peft import PeftConfig, inject_adapter_in_model
57
+
58
+ if not self._hf_peft_config_loaded:
59
+ self._hf_peft_config_loaded = True
60
+ elif adapter_name in self.peft_config:
61
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
62
+
63
+ if not isinstance(adapter_config, PeftConfig):
64
+ raise ValueError(
65
+ f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
66
+ )
67
+
68
+ # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
69
+ # handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.
70
+ adapter_config.base_model_name_or_path = None
71
+ inject_adapter_in_model(adapter_config, self, adapter_name)
72
+ self.set_adapter(adapter_name)
73
+
74
+ def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
75
+ """
76
+ Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
77
+
78
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
79
+ [documentation](https://huggingface.co/docs/peft).
80
+
81
+ Args:
82
+ adapter_name (Union[str, List[str]])):
83
+ The list of adapters to set or the adapter name in the case of a single adapter.
84
+ """
85
+ check_peft_version(min_version=MIN_PEFT_VERSION)
86
+
87
+ if not self._hf_peft_config_loaded:
88
+ raise ValueError("No adapter loaded. Please load an adapter first.")
89
+
90
+ if isinstance(adapter_name, str):
91
+ adapter_name = [adapter_name]
92
+
93
+ missing = set(adapter_name) - set(self.peft_config)
94
+ if len(missing) > 0:
95
+ raise ValueError(
96
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
97
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
98
+ )
99
+
100
+ from peft.tuners.tuners_utils import BaseTunerLayer
101
+
102
+ _adapters_has_been_set = False
103
+
104
+ for _, module in self.named_modules():
105
+ if isinstance(module, BaseTunerLayer):
106
+ if hasattr(module, "set_adapter"):
107
+ module.set_adapter(adapter_name)
108
+ # Previous versions of PEFT does not support multi-adapter inference
109
+ elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
110
+ raise ValueError(
111
+ "You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT."
112
+ " `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
113
+ )
114
+ else:
115
+ module.active_adapter = adapter_name
116
+ _adapters_has_been_set = True
117
+
118
+ if not _adapters_has_been_set:
119
+ raise ValueError(
120
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
121
+ )
122
+
123
+ def disable_adapters(self) -> None:
124
+ r"""
125
+ Disable all adapters attached to the model and fallback to inference with the base model only.
126
+
127
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
128
+ [documentation](https://huggingface.co/docs/peft).
129
+ """
130
+ check_peft_version(min_version=MIN_PEFT_VERSION)
131
+
132
+ if not self._hf_peft_config_loaded:
133
+ raise ValueError("No adapter loaded. Please load an adapter first.")
134
+
135
+ from peft.tuners.tuners_utils import BaseTunerLayer
136
+
137
+ for _, module in self.named_modules():
138
+ if isinstance(module, BaseTunerLayer):
139
+ if hasattr(module, "enable_adapters"):
140
+ module.enable_adapters(enabled=False)
141
+ else:
142
+ # support for older PEFT versions
143
+ module.disable_adapters = True
144
+
145
+ def enable_adapters(self) -> None:
146
+ """
147
+ Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
148
+ adapters to enable.
149
+
150
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
151
+ [documentation](https://huggingface.co/docs/peft).
152
+ """
153
+ check_peft_version(min_version=MIN_PEFT_VERSION)
154
+
155
+ if not self._hf_peft_config_loaded:
156
+ raise ValueError("No adapter loaded. Please load an adapter first.")
157
+
158
+ from peft.tuners.tuners_utils import BaseTunerLayer
159
+
160
+ for _, module in self.named_modules():
161
+ if isinstance(module, BaseTunerLayer):
162
+ if hasattr(module, "enable_adapters"):
163
+ module.enable_adapters(enabled=True)
164
+ else:
165
+ # support for older PEFT versions
166
+ module.disable_adapters = False
167
+
168
+ def active_adapters(self) -> List[str]:
169
+ """
170
+ Gets the current list of active adapters of the model.
171
+
172
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
173
+ [documentation](https://huggingface.co/docs/peft).
174
+ """
175
+ check_peft_version(min_version=MIN_PEFT_VERSION)
176
+
177
+ if not is_peft_available():
178
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
179
+
180
+ if not self._hf_peft_config_loaded:
181
+ raise ValueError("No adapter loaded. Please load an adapter first.")
182
+
183
+ from peft.tuners.tuners_utils import BaseTunerLayer
184
+
185
+ for _, module in self.named_modules():
186
+ if isinstance(module, BaseTunerLayer):
187
+ return module.active_adapter
diffusers/loaders/single_file.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from ..utils import is_transformers_available, logging
18
+ from .single_file_utils import (
19
+ create_diffusers_unet_model_from_ldm,
20
+ create_diffusers_vae_model_from_ldm,
21
+ create_scheduler_from_ldm,
22
+ create_text_encoders_and_tokenizers_from_ldm,
23
+ fetch_ldm_config_and_checkpoint,
24
+ infer_model_type,
25
+ )
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ # Pipelines that support the SDXL Refiner checkpoint
31
+ REFINER_PIPELINES = [
32
+ "StableDiffusionXLImg2ImgPipeline",
33
+ "StableDiffusionXLInpaintPipeline",
34
+ "StableDiffusionXLControlNetImg2ImgPipeline",
35
+ ]
36
+
37
+ if is_transformers_available():
38
+ from transformers import AutoFeatureExtractor
39
+
40
+
41
+ def build_sub_model_components(
42
+ pipeline_components,
43
+ pipeline_class_name,
44
+ component_name,
45
+ original_config,
46
+ checkpoint,
47
+ local_files_only=False,
48
+ load_safety_checker=False,
49
+ model_type=None,
50
+ image_size=None,
51
+ torch_dtype=None,
52
+ **kwargs,
53
+ ):
54
+ if component_name in pipeline_components:
55
+ return {}
56
+
57
+ if component_name == "unet":
58
+ num_in_channels = kwargs.pop("num_in_channels", None)
59
+ upcast_attention = kwargs.pop("upcast_attention", None)
60
+
61
+ unet_components = create_diffusers_unet_model_from_ldm(
62
+ pipeline_class_name,
63
+ original_config,
64
+ checkpoint,
65
+ num_in_channels=num_in_channels,
66
+ image_size=image_size,
67
+ torch_dtype=torch_dtype,
68
+ model_type=model_type,
69
+ upcast_attention=upcast_attention,
70
+ )
71
+ return unet_components
72
+
73
+ if component_name == "vae":
74
+ scaling_factor = kwargs.get("scaling_factor", None)
75
+ vae_components = create_diffusers_vae_model_from_ldm(
76
+ pipeline_class_name,
77
+ original_config,
78
+ checkpoint,
79
+ image_size,
80
+ scaling_factor,
81
+ torch_dtype,
82
+ model_type=model_type,
83
+ )
84
+ return vae_components
85
+
86
+ if component_name == "scheduler":
87
+ scheduler_type = kwargs.get("scheduler_type", "ddim")
88
+ prediction_type = kwargs.get("prediction_type", None)
89
+
90
+ scheduler_components = create_scheduler_from_ldm(
91
+ pipeline_class_name,
92
+ original_config,
93
+ checkpoint,
94
+ scheduler_type=scheduler_type,
95
+ prediction_type=prediction_type,
96
+ model_type=model_type,
97
+ )
98
+
99
+ return scheduler_components
100
+
101
+ if component_name in ["text_encoder", "text_encoder_2", "tokenizer", "tokenizer_2"]:
102
+ text_encoder_components = create_text_encoders_and_tokenizers_from_ldm(
103
+ original_config,
104
+ checkpoint,
105
+ model_type=model_type,
106
+ local_files_only=local_files_only,
107
+ torch_dtype=torch_dtype,
108
+ )
109
+ return text_encoder_components
110
+
111
+ if component_name == "safety_checker":
112
+ if load_safety_checker:
113
+ from ..pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
114
+
115
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(
116
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only, torch_dtype=torch_dtype
117
+ )
118
+ else:
119
+ safety_checker = None
120
+ return {"safety_checker": safety_checker}
121
+
122
+ if component_name == "feature_extractor":
123
+ if load_safety_checker:
124
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
125
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
126
+ )
127
+ else:
128
+ feature_extractor = None
129
+ return {"feature_extractor": feature_extractor}
130
+
131
+ return
132
+
133
+
134
+ def set_additional_components(
135
+ pipeline_class_name,
136
+ original_config,
137
+ checkpoint=None,
138
+ model_type=None,
139
+ ):
140
+ components = {}
141
+ if pipeline_class_name in REFINER_PIPELINES:
142
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
143
+ is_refiner = model_type == "SDXL-Refiner"
144
+ components.update(
145
+ {
146
+ "requires_aesthetics_score": is_refiner,
147
+ "force_zeros_for_empty_prompt": False if is_refiner else True,
148
+ }
149
+ )
150
+
151
+ return components
152
+
153
+
154
+ class FromSingleFileMixin:
155
+ """
156
+ Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
157
+ """
158
+
159
+ @classmethod
160
+ @validate_hf_hub_args
161
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
162
+ r"""
163
+ Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
164
+ format. The pipeline is set in evaluation mode (`model.eval()`) by default.
165
+
166
+ Parameters:
167
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
168
+ Can be either:
169
+ - A link to the `.ckpt` file (for example
170
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
171
+ - A path to a *file* containing all pipeline weights.
172
+ torch_dtype (`str` or `torch.dtype`, *optional*):
173
+ Override the default `torch.dtype` and load the model with another dtype.
174
+ force_download (`bool`, *optional*, defaults to `False`):
175
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
176
+ cached versions if they exist.
177
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
178
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
179
+ is not used.
180
+ resume_download:
181
+ Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
182
+ of Diffusers.
183
+ proxies (`Dict[str, str]`, *optional*):
184
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
185
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
186
+ local_files_only (`bool`, *optional*, defaults to `False`):
187
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
188
+ won't be downloaded from the Hub.
189
+ token (`str` or *bool*, *optional*):
190
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
191
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
192
+ revision (`str`, *optional*, defaults to `"main"`):
193
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
194
+ allowed by Git.
195
+ original_config_file (`str`, *optional*):
196
+ The path to the original config file that was used to train the model. If not provided, the config file
197
+ will be inferred from the checkpoint file.
198
+ model_type (`str`, *optional*):
199
+ The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
200
+ image_size (`int`, *optional*):
201
+ The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE
202
+ model.
203
+ load_safety_checker (`bool`, *optional*, defaults to `False`):
204
+ Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a
205
+ `safety_checker` component is passed to the `kwargs`.
206
+ num_in_channels (`int`, *optional*):
207
+ Specify the number of input channels for the UNet model. Read more about how to configure UNet model
208
+ with this parameter
209
+ [here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
210
+ scaling_factor (`float`, *optional*):
211
+ The scaling factor to use for the VAE model. If not provided, it is inferred from the config file
212
+ first. If the scaling factor is not found in the config file, the default value 0.18215 is used.
213
+ scheduler_type (`str`, *optional*):
214
+ The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint
215
+ file.
216
+ prediction_type (`str`, *optional*):
217
+ The type of prediction to load. If not provided, the prediction type will be inferred from the
218
+ checkpoint file.
219
+ kwargs (remaining dictionary of keyword arguments, *optional*):
220
+ Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
221
+ class). The overwritten components are passed directly to the pipelines `__init__` method. See example
222
+ below for more information.
223
+
224
+ Examples:
225
+
226
+ ```py
227
+ >>> from diffusers import StableDiffusionPipeline
228
+
229
+ >>> # Download pipeline from huggingface.co and cache.
230
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
231
+ ... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
232
+ ... )
233
+
234
+ >>> # Download pipeline from local file
235
+ >>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
236
+ >>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
237
+
238
+ >>> # Enable float16 and move to GPU
239
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
240
+ ... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
241
+ ... torch_dtype=torch.float16,
242
+ ... )
243
+ >>> pipeline.to("cuda")
244
+ ```
245
+ """
246
+ original_config_file = kwargs.pop("original_config_file", None)
247
+ resume_download = kwargs.pop("resume_download", None)
248
+ force_download = kwargs.pop("force_download", False)
249
+ proxies = kwargs.pop("proxies", None)
250
+ token = kwargs.pop("token", None)
251
+ cache_dir = kwargs.pop("cache_dir", None)
252
+ local_files_only = kwargs.pop("local_files_only", False)
253
+ revision = kwargs.pop("revision", None)
254
+ torch_dtype = kwargs.pop("torch_dtype", None)
255
+
256
+ class_name = cls.__name__
257
+
258
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
259
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
260
+ class_name=class_name,
261
+ original_config_file=original_config_file,
262
+ resume_download=resume_download,
263
+ force_download=force_download,
264
+ proxies=proxies,
265
+ token=token,
266
+ revision=revision,
267
+ local_files_only=local_files_only,
268
+ cache_dir=cache_dir,
269
+ )
270
+
271
+ from ..pipelines.pipeline_utils import _get_pipeline_class
272
+
273
+ pipeline_class = _get_pipeline_class(
274
+ cls,
275
+ config=None,
276
+ cache_dir=cache_dir,
277
+ )
278
+
279
+ expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class)
280
+ passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
281
+ passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
282
+
283
+ model_type = kwargs.pop("model_type", None)
284
+ image_size = kwargs.pop("image_size", None)
285
+ load_safety_checker = (kwargs.pop("load_safety_checker", False)) or (
286
+ passed_class_obj.get("safety_checker", None) is not None
287
+ )
288
+
289
+ init_kwargs = {}
290
+ for name in expected_modules:
291
+ if name in passed_class_obj:
292
+ init_kwargs[name] = passed_class_obj[name]
293
+ else:
294
+ components = build_sub_model_components(
295
+ init_kwargs,
296
+ class_name,
297
+ name,
298
+ original_config,
299
+ checkpoint,
300
+ model_type=model_type,
301
+ image_size=image_size,
302
+ load_safety_checker=load_safety_checker,
303
+ local_files_only=local_files_only,
304
+ torch_dtype=torch_dtype,
305
+ **kwargs,
306
+ )
307
+ if not components:
308
+ continue
309
+ init_kwargs.update(components)
310
+
311
+ additional_components = set_additional_components(
312
+ class_name, original_config, checkpoint=checkpoint, model_type=model_type
313
+ )
314
+ if additional_components:
315
+ init_kwargs.update(additional_components)
316
+
317
+ init_kwargs.update(passed_pipe_kwargs)
318
+ pipe = pipeline_class(**init_kwargs)
319
+
320
+ if torch_dtype is not None:
321
+ pipe.to(dtype=torch_dtype)
322
+
323
+ return pipe
diffusers/loaders/single_file_utils.py ADDED
@@ -0,0 +1,1609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Conversion script for the Stable Diffusion checkpoints."""
16
+
17
+ import os
18
+ import re
19
+ from contextlib import nullcontext
20
+ from io import BytesIO
21
+ from urllib.parse import urlparse
22
+
23
+ import requests
24
+ import yaml
25
+
26
+ from ..models.modeling_utils import load_state_dict
27
+ from ..schedulers import (
28
+ DDIMScheduler,
29
+ DDPMScheduler,
30
+ DPMSolverMultistepScheduler,
31
+ EDMDPMSolverMultistepScheduler,
32
+ EulerAncestralDiscreteScheduler,
33
+ EulerDiscreteScheduler,
34
+ HeunDiscreteScheduler,
35
+ LMSDiscreteScheduler,
36
+ PNDMScheduler,
37
+ )
38
+ from ..utils import is_accelerate_available, is_transformers_available, logging
39
+ from ..utils.hub_utils import _get_model_file
40
+
41
+
42
+ if is_transformers_available():
43
+ from transformers import (
44
+ CLIPTextConfig,
45
+ CLIPTextModel,
46
+ CLIPTextModelWithProjection,
47
+ CLIPTokenizer,
48
+ )
49
+
50
+ if is_accelerate_available():
51
+ from accelerate import init_empty_weights
52
+
53
+ from ..models.modeling_utils import load_model_dict_into_meta
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+ CONFIG_URLS = {
58
+ "v1": "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml",
59
+ "v2": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml",
60
+ "xl": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml",
61
+ "xl_refiner": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml",
62
+ "upscale": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml",
63
+ "controlnet": "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml",
64
+ }
65
+
66
+ CHECKPOINT_KEY_NAMES = {
67
+ "v2": "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight",
68
+ "xl_base": "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias",
69
+ "xl_refiner": "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias",
70
+ }
71
+
72
+ SCHEDULER_DEFAULT_CONFIG = {
73
+ "beta_schedule": "scaled_linear",
74
+ "beta_start": 0.00085,
75
+ "beta_end": 0.012,
76
+ "interpolation_type": "linear",
77
+ "num_train_timesteps": 1000,
78
+ "prediction_type": "epsilon",
79
+ "sample_max_value": 1.0,
80
+ "set_alpha_to_one": False,
81
+ "skip_prk_steps": True,
82
+ "steps_offset": 1,
83
+ "timestep_spacing": "leading",
84
+ }
85
+
86
+
87
+ STABLE_CASCADE_DEFAULT_CONFIGS = {
88
+ "stage_c": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior"},
89
+ "stage_c_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior_lite"},
90
+ "stage_b": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder"},
91
+ "stage_b_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder_lite"},
92
+ }
93
+
94
+
95
+ def convert_stable_cascade_unet_single_file_to_diffusers(original_state_dict):
96
+ is_stage_c = "clip_txt_mapper.weight" in original_state_dict
97
+
98
+ if is_stage_c:
99
+ state_dict = {}
100
+ for key in original_state_dict.keys():
101
+ if key.endswith("in_proj_weight"):
102
+ weights = original_state_dict[key].chunk(3, 0)
103
+ state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
104
+ state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
105
+ state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
106
+ elif key.endswith("in_proj_bias"):
107
+ weights = original_state_dict[key].chunk(3, 0)
108
+ state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
109
+ state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
110
+ state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
111
+ elif key.endswith("out_proj.weight"):
112
+ weights = original_state_dict[key]
113
+ state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
114
+ elif key.endswith("out_proj.bias"):
115
+ weights = original_state_dict[key]
116
+ state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
117
+ else:
118
+ state_dict[key] = original_state_dict[key]
119
+ else:
120
+ state_dict = {}
121
+ for key in original_state_dict.keys():
122
+ if key.endswith("in_proj_weight"):
123
+ weights = original_state_dict[key].chunk(3, 0)
124
+ state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
125
+ state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
126
+ state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
127
+ elif key.endswith("in_proj_bias"):
128
+ weights = original_state_dict[key].chunk(3, 0)
129
+ state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
130
+ state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
131
+ state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
132
+ elif key.endswith("out_proj.weight"):
133
+ weights = original_state_dict[key]
134
+ state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
135
+ elif key.endswith("out_proj.bias"):
136
+ weights = original_state_dict[key]
137
+ state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
138
+ # rename clip_mapper to clip_txt_pooled_mapper
139
+ elif key.endswith("clip_mapper.weight"):
140
+ weights = original_state_dict[key]
141
+ state_dict[key.replace("clip_mapper.weight", "clip_txt_pooled_mapper.weight")] = weights
142
+ elif key.endswith("clip_mapper.bias"):
143
+ weights = original_state_dict[key]
144
+ state_dict[key.replace("clip_mapper.bias", "clip_txt_pooled_mapper.bias")] = weights
145
+ else:
146
+ state_dict[key] = original_state_dict[key]
147
+
148
+ return state_dict
149
+
150
+
151
+ def infer_stable_cascade_single_file_config(checkpoint):
152
+ is_stage_c = "clip_txt_mapper.weight" in checkpoint
153
+ is_stage_b = "down_blocks.1.0.channelwise.0.weight" in checkpoint
154
+
155
+ if is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 1536):
156
+ config_type = "stage_c_lite"
157
+ elif is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 2048):
158
+ config_type = "stage_c"
159
+ elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 576:
160
+ config_type = "stage_b_lite"
161
+ elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 640:
162
+ config_type = "stage_b"
163
+
164
+ return STABLE_CASCADE_DEFAULT_CONFIGS[config_type]
165
+
166
+
167
+ DIFFUSERS_TO_LDM_MAPPING = {
168
+ "unet": {
169
+ "layers": {
170
+ "time_embedding.linear_1.weight": "time_embed.0.weight",
171
+ "time_embedding.linear_1.bias": "time_embed.0.bias",
172
+ "time_embedding.linear_2.weight": "time_embed.2.weight",
173
+ "time_embedding.linear_2.bias": "time_embed.2.bias",
174
+ "conv_in.weight": "input_blocks.0.0.weight",
175
+ "conv_in.bias": "input_blocks.0.0.bias",
176
+ "conv_norm_out.weight": "out.0.weight",
177
+ "conv_norm_out.bias": "out.0.bias",
178
+ "conv_out.weight": "out.2.weight",
179
+ "conv_out.bias": "out.2.bias",
180
+ },
181
+ "class_embed_type": {
182
+ "class_embedding.linear_1.weight": "label_emb.0.0.weight",
183
+ "class_embedding.linear_1.bias": "label_emb.0.0.bias",
184
+ "class_embedding.linear_2.weight": "label_emb.0.2.weight",
185
+ "class_embedding.linear_2.bias": "label_emb.0.2.bias",
186
+ },
187
+ "addition_embed_type": {
188
+ "add_embedding.linear_1.weight": "label_emb.0.0.weight",
189
+ "add_embedding.linear_1.bias": "label_emb.0.0.bias",
190
+ "add_embedding.linear_2.weight": "label_emb.0.2.weight",
191
+ "add_embedding.linear_2.bias": "label_emb.0.2.bias",
192
+ },
193
+ },
194
+ "controlnet": {
195
+ "layers": {
196
+ "time_embedding.linear_1.weight": "time_embed.0.weight",
197
+ "time_embedding.linear_1.bias": "time_embed.0.bias",
198
+ "time_embedding.linear_2.weight": "time_embed.2.weight",
199
+ "time_embedding.linear_2.bias": "time_embed.2.bias",
200
+ "conv_in.weight": "input_blocks.0.0.weight",
201
+ "conv_in.bias": "input_blocks.0.0.bias",
202
+ "controlnet_cond_embedding.conv_in.weight": "input_hint_block.0.weight",
203
+ "controlnet_cond_embedding.conv_in.bias": "input_hint_block.0.bias",
204
+ "controlnet_cond_embedding.conv_out.weight": "input_hint_block.14.weight",
205
+ "controlnet_cond_embedding.conv_out.bias": "input_hint_block.14.bias",
206
+ },
207
+ "class_embed_type": {
208
+ "class_embedding.linear_1.weight": "label_emb.0.0.weight",
209
+ "class_embedding.linear_1.bias": "label_emb.0.0.bias",
210
+ "class_embedding.linear_2.weight": "label_emb.0.2.weight",
211
+ "class_embedding.linear_2.bias": "label_emb.0.2.bias",
212
+ },
213
+ "addition_embed_type": {
214
+ "add_embedding.linear_1.weight": "label_emb.0.0.weight",
215
+ "add_embedding.linear_1.bias": "label_emb.0.0.bias",
216
+ "add_embedding.linear_2.weight": "label_emb.0.2.weight",
217
+ "add_embedding.linear_2.bias": "label_emb.0.2.bias",
218
+ },
219
+ },
220
+ "vae": {
221
+ "encoder.conv_in.weight": "encoder.conv_in.weight",
222
+ "encoder.conv_in.bias": "encoder.conv_in.bias",
223
+ "encoder.conv_out.weight": "encoder.conv_out.weight",
224
+ "encoder.conv_out.bias": "encoder.conv_out.bias",
225
+ "encoder.conv_norm_out.weight": "encoder.norm_out.weight",
226
+ "encoder.conv_norm_out.bias": "encoder.norm_out.bias",
227
+ "decoder.conv_in.weight": "decoder.conv_in.weight",
228
+ "decoder.conv_in.bias": "decoder.conv_in.bias",
229
+ "decoder.conv_out.weight": "decoder.conv_out.weight",
230
+ "decoder.conv_out.bias": "decoder.conv_out.bias",
231
+ "decoder.conv_norm_out.weight": "decoder.norm_out.weight",
232
+ "decoder.conv_norm_out.bias": "decoder.norm_out.bias",
233
+ "quant_conv.weight": "quant_conv.weight",
234
+ "quant_conv.bias": "quant_conv.bias",
235
+ "post_quant_conv.weight": "post_quant_conv.weight",
236
+ "post_quant_conv.bias": "post_quant_conv.bias",
237
+ },
238
+ "openclip": {
239
+ "layers": {
240
+ "text_model.embeddings.position_embedding.weight": "positional_embedding",
241
+ "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
242
+ "text_model.final_layer_norm.weight": "ln_final.weight",
243
+ "text_model.final_layer_norm.bias": "ln_final.bias",
244
+ "text_projection.weight": "text_projection",
245
+ },
246
+ "transformer": {
247
+ "text_model.encoder.layers.": "resblocks.",
248
+ "layer_norm1": "ln_1",
249
+ "layer_norm2": "ln_2",
250
+ ".fc1.": ".c_fc.",
251
+ ".fc2.": ".c_proj.",
252
+ ".self_attn": ".attn",
253
+ "transformer.text_model.final_layer_norm.": "ln_final.",
254
+ "transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
255
+ "transformer.text_model.embeddings.position_embedding.weight": "positional_embedding",
256
+ },
257
+ },
258
+ }
259
+
260
+ LDM_VAE_KEY = "first_stage_model."
261
+ LDM_VAE_DEFAULT_SCALING_FACTOR = 0.18215
262
+ PLAYGROUND_VAE_SCALING_FACTOR = 0.5
263
+ LDM_UNET_KEY = "model.diffusion_model."
264
+ LDM_CONTROLNET_KEY = "control_model."
265
+ LDM_CLIP_PREFIX_TO_REMOVE = ["cond_stage_model.transformer.", "conditioner.embedders.0.transformer."]
266
+ LDM_OPEN_CLIP_TEXT_PROJECTION_DIM = 1024
267
+
268
+ SD_2_TEXT_ENCODER_KEYS_TO_IGNORE = [
269
+ "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_bias",
270
+ "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_weight",
271
+ "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.bias",
272
+ "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.weight",
273
+ "cond_stage_model.model.transformer.resblocks.23.ln_1.bias",
274
+ "cond_stage_model.model.transformer.resblocks.23.ln_1.weight",
275
+ "cond_stage_model.model.transformer.resblocks.23.ln_2.bias",
276
+ "cond_stage_model.model.transformer.resblocks.23.ln_2.weight",
277
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.bias",
278
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.weight",
279
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.bias",
280
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.weight",
281
+ "cond_stage_model.model.text_projection",
282
+ ]
283
+
284
+
285
+ VALID_URL_PREFIXES = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
286
+
287
+
288
+ def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
289
+ pattern = r"([^/]+)/([^/]+)/(?:blob/main/)?(.+)"
290
+ weights_name = None
291
+ repo_id = (None,)
292
+ for prefix in VALID_URL_PREFIXES:
293
+ pretrained_model_name_or_path = pretrained_model_name_or_path.replace(prefix, "")
294
+ match = re.match(pattern, pretrained_model_name_or_path)
295
+ if not match:
296
+ return repo_id, weights_name
297
+
298
+ repo_id = f"{match.group(1)}/{match.group(2)}"
299
+ weights_name = match.group(3)
300
+
301
+ return repo_id, weights_name
302
+
303
+
304
+ def fetch_ldm_config_and_checkpoint(
305
+ pretrained_model_link_or_path,
306
+ class_name,
307
+ original_config_file=None,
308
+ resume_download=None,
309
+ force_download=False,
310
+ proxies=None,
311
+ token=None,
312
+ cache_dir=None,
313
+ local_files_only=None,
314
+ revision=None,
315
+ ):
316
+ checkpoint = load_single_file_model_checkpoint(
317
+ pretrained_model_link_or_path,
318
+ resume_download=resume_download,
319
+ force_download=force_download,
320
+ proxies=proxies,
321
+ token=token,
322
+ cache_dir=cache_dir,
323
+ local_files_only=local_files_only,
324
+ revision=revision,
325
+ )
326
+ original_config = fetch_original_config(class_name, checkpoint, original_config_file)
327
+
328
+ return original_config, checkpoint
329
+
330
+
331
+ def load_single_file_model_checkpoint(
332
+ pretrained_model_link_or_path,
333
+ resume_download=False,
334
+ force_download=False,
335
+ proxies=None,
336
+ token=None,
337
+ cache_dir=None,
338
+ local_files_only=None,
339
+ revision=None,
340
+ ):
341
+ if os.path.isfile(pretrained_model_link_or_path):
342
+ checkpoint = load_state_dict(pretrained_model_link_or_path)
343
+ else:
344
+ repo_id, weights_name = _extract_repo_id_and_weights_name(pretrained_model_link_or_path)
345
+ checkpoint_path = _get_model_file(
346
+ repo_id,
347
+ weights_name=weights_name,
348
+ force_download=force_download,
349
+ cache_dir=cache_dir,
350
+ resume_download=resume_download,
351
+ proxies=proxies,
352
+ local_files_only=local_files_only,
353
+ token=token,
354
+ revision=revision,
355
+ )
356
+ checkpoint = load_state_dict(checkpoint_path)
357
+
358
+ # some checkpoints contain the model state dict under a "state_dict" key
359
+ while "state_dict" in checkpoint:
360
+ checkpoint = checkpoint["state_dict"]
361
+
362
+ return checkpoint
363
+
364
+
365
+ def infer_original_config_file(class_name, checkpoint):
366
+ if CHECKPOINT_KEY_NAMES["v2"] in checkpoint and checkpoint[CHECKPOINT_KEY_NAMES["v2"]].shape[-1] == 1024:
367
+ config_url = CONFIG_URLS["v2"]
368
+
369
+ elif CHECKPOINT_KEY_NAMES["xl_base"] in checkpoint:
370
+ config_url = CONFIG_URLS["xl"]
371
+
372
+ elif CHECKPOINT_KEY_NAMES["xl_refiner"] in checkpoint:
373
+ config_url = CONFIG_URLS["xl_refiner"]
374
+
375
+ elif class_name == "StableDiffusionUpscalePipeline":
376
+ config_url = CONFIG_URLS["upscale"]
377
+
378
+ elif class_name == "ControlNetModel":
379
+ config_url = CONFIG_URLS["controlnet"]
380
+
381
+ else:
382
+ config_url = CONFIG_URLS["v1"]
383
+
384
+ original_config_file = BytesIO(requests.get(config_url).content)
385
+
386
+ return original_config_file
387
+
388
+
389
+ def fetch_original_config(pipeline_class_name, checkpoint, original_config_file=None):
390
+ def is_valid_url(url):
391
+ result = urlparse(url)
392
+ if result.scheme and result.netloc:
393
+ return True
394
+
395
+ return False
396
+
397
+ if original_config_file is None:
398
+ original_config_file = infer_original_config_file(pipeline_class_name, checkpoint)
399
+
400
+ elif os.path.isfile(original_config_file):
401
+ with open(original_config_file, "r") as fp:
402
+ original_config_file = fp.read()
403
+
404
+ elif is_valid_url(original_config_file):
405
+ original_config_file = BytesIO(requests.get(original_config_file).content)
406
+
407
+ else:
408
+ raise ValueError("Invalid `original_config_file` provided. Please set it to a valid file path or URL.")
409
+
410
+ original_config = yaml.safe_load(original_config_file)
411
+
412
+ return original_config
413
+
414
+
415
+ def infer_model_type(original_config, checkpoint, model_type=None):
416
+ if model_type is not None:
417
+ return model_type
418
+
419
+ has_cond_stage_config = (
420
+ "cond_stage_config" in original_config["model"]["params"]
421
+ and original_config["model"]["params"]["cond_stage_config"] is not None
422
+ )
423
+ has_network_config = (
424
+ "network_config" in original_config["model"]["params"]
425
+ and original_config["model"]["params"]["network_config"] is not None
426
+ )
427
+
428
+ if has_cond_stage_config:
429
+ model_type = original_config["model"]["params"]["cond_stage_config"]["target"].split(".")[-1]
430
+
431
+ elif has_network_config:
432
+ context_dim = original_config["model"]["params"]["network_config"]["params"]["context_dim"]
433
+ if "edm_mean" in checkpoint and "edm_std" in checkpoint:
434
+ model_type = "Playground"
435
+ elif context_dim == 2048:
436
+ model_type = "SDXL"
437
+ else:
438
+ model_type = "SDXL-Refiner"
439
+ else:
440
+ raise ValueError("Unable to infer model type from config")
441
+
442
+ logger.debug(f"No `model_type` given, `model_type` inferred as: {model_type}")
443
+
444
+ return model_type
445
+
446
+
447
+ def get_default_scheduler_config():
448
+ return SCHEDULER_DEFAULT_CONFIG
449
+
450
+
451
+ def set_image_size(pipeline_class_name, original_config, checkpoint, image_size=None, model_type=None):
452
+ if image_size:
453
+ return image_size
454
+
455
+ global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
456
+ model_type = infer_model_type(original_config, checkpoint, model_type)
457
+
458
+ if pipeline_class_name == "StableDiffusionUpscalePipeline":
459
+ image_size = original_config["model"]["params"]["unet_config"]["params"]["image_size"]
460
+ return image_size
461
+
462
+ elif model_type in ["SDXL", "SDXL-Refiner", "Playground"]:
463
+ image_size = 1024
464
+ return image_size
465
+
466
+ elif (
467
+ "parameterization" in original_config["model"]["params"]
468
+ and original_config["model"]["params"]["parameterization"] == "v"
469
+ ):
470
+ # NOTE: For stable diffusion 2 base one has to pass `image_size==512`
471
+ # as it relies on a brittle global step parameter here
472
+ image_size = 512 if global_step == 875000 else 768
473
+ return image_size
474
+
475
+ else:
476
+ image_size = 512
477
+ return image_size
478
+
479
+
480
+ # Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.conv_attn_to_linear
481
+ def conv_attn_to_linear(checkpoint):
482
+ keys = list(checkpoint.keys())
483
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
484
+ for key in keys:
485
+ if ".".join(key.split(".")[-2:]) in attn_keys:
486
+ if checkpoint[key].ndim > 2:
487
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
488
+ elif "proj_attn.weight" in key:
489
+ if checkpoint[key].ndim > 2:
490
+ checkpoint[key] = checkpoint[key][:, :, 0]
491
+
492
+
493
+ def create_unet_diffusers_config(original_config, image_size: int):
494
+ """
495
+ Creates a config for the diffusers based on the config of the LDM model.
496
+ """
497
+ if (
498
+ "unet_config" in original_config["model"]["params"]
499
+ and original_config["model"]["params"]["unet_config"] is not None
500
+ ):
501
+ unet_params = original_config["model"]["params"]["unet_config"]["params"]
502
+ else:
503
+ unet_params = original_config["model"]["params"]["network_config"]["params"]
504
+
505
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
506
+ block_out_channels = [unet_params["model_channels"] * mult for mult in unet_params["channel_mult"]]
507
+
508
+ down_block_types = []
509
+ resolution = 1
510
+ for i in range(len(block_out_channels)):
511
+ block_type = "CrossAttnDownBlock2D" if resolution in unet_params["attention_resolutions"] else "DownBlock2D"
512
+ down_block_types.append(block_type)
513
+ if i != len(block_out_channels) - 1:
514
+ resolution *= 2
515
+
516
+ up_block_types = []
517
+ for i in range(len(block_out_channels)):
518
+ block_type = "CrossAttnUpBlock2D" if resolution in unet_params["attention_resolutions"] else "UpBlock2D"
519
+ up_block_types.append(block_type)
520
+ resolution //= 2
521
+
522
+ if unet_params["transformer_depth"] is not None:
523
+ transformer_layers_per_block = (
524
+ unet_params["transformer_depth"]
525
+ if isinstance(unet_params["transformer_depth"], int)
526
+ else list(unet_params["transformer_depth"])
527
+ )
528
+ else:
529
+ transformer_layers_per_block = 1
530
+
531
+ vae_scale_factor = 2 ** (len(vae_params["ch_mult"]) - 1)
532
+
533
+ head_dim = unet_params["num_heads"] if "num_heads" in unet_params else None
534
+ use_linear_projection = (
535
+ unet_params["use_linear_in_transformer"] if "use_linear_in_transformer" in unet_params else False
536
+ )
537
+ if use_linear_projection:
538
+ # stable diffusion 2-base-512 and 2-768
539
+ if head_dim is None:
540
+ head_dim_mult = unet_params["model_channels"] // unet_params["num_head_channels"]
541
+ head_dim = [head_dim_mult * c for c in list(unet_params["channel_mult"])]
542
+
543
+ class_embed_type = None
544
+ addition_embed_type = None
545
+ addition_time_embed_dim = None
546
+ projection_class_embeddings_input_dim = None
547
+ context_dim = None
548
+
549
+ if unet_params["context_dim"] is not None:
550
+ context_dim = (
551
+ unet_params["context_dim"]
552
+ if isinstance(unet_params["context_dim"], int)
553
+ else unet_params["context_dim"][0]
554
+ )
555
+
556
+ if "num_classes" in unet_params:
557
+ if unet_params["num_classes"] == "sequential":
558
+ if context_dim in [2048, 1280]:
559
+ # SDXL
560
+ addition_embed_type = "text_time"
561
+ addition_time_embed_dim = 256
562
+ else:
563
+ class_embed_type = "projection"
564
+ assert "adm_in_channels" in unet_params
565
+ projection_class_embeddings_input_dim = unet_params["adm_in_channels"]
566
+
567
+ config = {
568
+ "sample_size": image_size // vae_scale_factor,
569
+ "in_channels": unet_params["in_channels"],
570
+ "down_block_types": down_block_types,
571
+ "block_out_channels": block_out_channels,
572
+ "layers_per_block": unet_params["num_res_blocks"],
573
+ "cross_attention_dim": context_dim,
574
+ "attention_head_dim": head_dim,
575
+ "use_linear_projection": use_linear_projection,
576
+ "class_embed_type": class_embed_type,
577
+ "addition_embed_type": addition_embed_type,
578
+ "addition_time_embed_dim": addition_time_embed_dim,
579
+ "projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
580
+ "transformer_layers_per_block": transformer_layers_per_block,
581
+ }
582
+
583
+ if "disable_self_attentions" in unet_params:
584
+ config["only_cross_attention"] = unet_params["disable_self_attentions"]
585
+
586
+ if "num_classes" in unet_params and isinstance(unet_params["num_classes"], int):
587
+ config["num_class_embeds"] = unet_params["num_classes"]
588
+
589
+ config["out_channels"] = unet_params["out_channels"]
590
+ config["up_block_types"] = up_block_types
591
+
592
+ return config
593
+
594
+
595
+ def create_controlnet_diffusers_config(original_config, image_size: int):
596
+ unet_params = original_config["model"]["params"]["control_stage_config"]["params"]
597
+ diffusers_unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
598
+
599
+ controlnet_config = {
600
+ "conditioning_channels": unet_params["hint_channels"],
601
+ "in_channels": diffusers_unet_config["in_channels"],
602
+ "down_block_types": diffusers_unet_config["down_block_types"],
603
+ "block_out_channels": diffusers_unet_config["block_out_channels"],
604
+ "layers_per_block": diffusers_unet_config["layers_per_block"],
605
+ "cross_attention_dim": diffusers_unet_config["cross_attention_dim"],
606
+ "attention_head_dim": diffusers_unet_config["attention_head_dim"],
607
+ "use_linear_projection": diffusers_unet_config["use_linear_projection"],
608
+ "class_embed_type": diffusers_unet_config["class_embed_type"],
609
+ "addition_embed_type": diffusers_unet_config["addition_embed_type"],
610
+ "addition_time_embed_dim": diffusers_unet_config["addition_time_embed_dim"],
611
+ "projection_class_embeddings_input_dim": diffusers_unet_config["projection_class_embeddings_input_dim"],
612
+ "transformer_layers_per_block": diffusers_unet_config["transformer_layers_per_block"],
613
+ }
614
+
615
+ return controlnet_config
616
+
617
+
618
+ def create_vae_diffusers_config(original_config, image_size, scaling_factor=None, latents_mean=None, latents_std=None):
619
+ """
620
+ Creates a config for the diffusers based on the config of the LDM model.
621
+ """
622
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
623
+ if (scaling_factor is None) and (latents_mean is not None) and (latents_std is not None):
624
+ scaling_factor = PLAYGROUND_VAE_SCALING_FACTOR
625
+ elif (scaling_factor is None) and ("scale_factor" in original_config["model"]["params"]):
626
+ scaling_factor = original_config["model"]["params"]["scale_factor"]
627
+ elif scaling_factor is None:
628
+ scaling_factor = LDM_VAE_DEFAULT_SCALING_FACTOR
629
+
630
+ block_out_channels = [vae_params["ch"] * mult for mult in vae_params["ch_mult"]]
631
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
632
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
633
+
634
+ config = {
635
+ "sample_size": image_size,
636
+ "in_channels": vae_params["in_channels"],
637
+ "out_channels": vae_params["out_ch"],
638
+ "down_block_types": down_block_types,
639
+ "up_block_types": up_block_types,
640
+ "block_out_channels": block_out_channels,
641
+ "latent_channels": vae_params["z_channels"],
642
+ "layers_per_block": vae_params["num_res_blocks"],
643
+ "scaling_factor": scaling_factor,
644
+ }
645
+ if latents_mean is not None and latents_std is not None:
646
+ config.update({"latents_mean": latents_mean, "latents_std": latents_std})
647
+
648
+ return config
649
+
650
+
651
+ def update_unet_resnet_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping=None):
652
+ for ldm_key in ldm_keys:
653
+ diffusers_key = (
654
+ ldm_key.replace("in_layers.0", "norm1")
655
+ .replace("in_layers.2", "conv1")
656
+ .replace("out_layers.0", "norm2")
657
+ .replace("out_layers.3", "conv2")
658
+ .replace("emb_layers.1", "time_emb_proj")
659
+ .replace("skip_connection", "conv_shortcut")
660
+ )
661
+ if mapping:
662
+ diffusers_key = diffusers_key.replace(mapping["old"], mapping["new"])
663
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
664
+
665
+
666
+ def update_unet_attention_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping):
667
+ for ldm_key in ldm_keys:
668
+ diffusers_key = ldm_key.replace(mapping["old"], mapping["new"])
669
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
670
+
671
+
672
+ def convert_ldm_unet_checkpoint(checkpoint, config, extract_ema=False):
673
+ """
674
+ Takes a state dict and a config, and returns a converted checkpoint.
675
+ """
676
+ # extract state_dict for UNet
677
+ unet_state_dict = {}
678
+ keys = list(checkpoint.keys())
679
+ unet_key = LDM_UNET_KEY
680
+
681
+ # at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
682
+ if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
683
+ logger.warning("Checkpoint has both EMA and non-EMA weights.")
684
+ logger.warning(
685
+ "In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
686
+ " weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
687
+ )
688
+ for key in keys:
689
+ if key.startswith("model.diffusion_model"):
690
+ flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
691
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
692
+ else:
693
+ if sum(k.startswith("model_ema") for k in keys) > 100:
694
+ logger.warning(
695
+ "In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
696
+ " weights (usually better for inference), please make sure to add the `--extract_ema` flag."
697
+ )
698
+ for key in keys:
699
+ if key.startswith(unet_key):
700
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
701
+
702
+ new_checkpoint = {}
703
+ ldm_unet_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["layers"]
704
+ for diffusers_key, ldm_key in ldm_unet_keys.items():
705
+ if ldm_key not in unet_state_dict:
706
+ continue
707
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
708
+
709
+ if ("class_embed_type" in config) and (config["class_embed_type"] in ["timestep", "projection"]):
710
+ class_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["class_embed_type"]
711
+ for diffusers_key, ldm_key in class_embed_keys.items():
712
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
713
+
714
+ if ("addition_embed_type" in config) and (config["addition_embed_type"] == "text_time"):
715
+ addition_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["addition_embed_type"]
716
+ for diffusers_key, ldm_key in addition_embed_keys.items():
717
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
718
+
719
+ # Relevant to StableDiffusionUpscalePipeline
720
+ if "num_class_embeds" in config:
721
+ if (config["num_class_embeds"] is not None) and ("label_emb.weight" in unet_state_dict):
722
+ new_checkpoint["class_embedding.weight"] = unet_state_dict["label_emb.weight"]
723
+
724
+ # Retrieves the keys for the input blocks only
725
+ num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
726
+ input_blocks = {
727
+ layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
728
+ for layer_id in range(num_input_blocks)
729
+ }
730
+
731
+ # Retrieves the keys for the middle blocks only
732
+ num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
733
+ middle_blocks = {
734
+ layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
735
+ for layer_id in range(num_middle_blocks)
736
+ }
737
+
738
+ # Retrieves the keys for the output blocks only
739
+ num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
740
+ output_blocks = {
741
+ layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
742
+ for layer_id in range(num_output_blocks)
743
+ }
744
+
745
+ # Down blocks
746
+ for i in range(1, num_input_blocks):
747
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
748
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
749
+
750
+ resnets = [
751
+ key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
752
+ ]
753
+ update_unet_resnet_ldm_to_diffusers(
754
+ resnets,
755
+ new_checkpoint,
756
+ unet_state_dict,
757
+ {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
758
+ )
759
+
760
+ if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
761
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
762
+ f"input_blocks.{i}.0.op.weight"
763
+ )
764
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
765
+ f"input_blocks.{i}.0.op.bias"
766
+ )
767
+
768
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
769
+ if attentions:
770
+ update_unet_attention_ldm_to_diffusers(
771
+ attentions,
772
+ new_checkpoint,
773
+ unet_state_dict,
774
+ {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
775
+ )
776
+
777
+ # Mid blocks
778
+ resnet_0 = middle_blocks[0]
779
+ attentions = middle_blocks[1]
780
+ resnet_1 = middle_blocks[2]
781
+
782
+ update_unet_resnet_ldm_to_diffusers(
783
+ resnet_0, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"}
784
+ )
785
+ update_unet_resnet_ldm_to_diffusers(
786
+ resnet_1, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"}
787
+ )
788
+ update_unet_attention_ldm_to_diffusers(
789
+ attentions, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"}
790
+ )
791
+
792
+ # Up Blocks
793
+ for i in range(num_output_blocks):
794
+ block_id = i // (config["layers_per_block"] + 1)
795
+ layer_in_block_id = i % (config["layers_per_block"] + 1)
796
+
797
+ resnets = [
798
+ key for key in output_blocks[i] if f"output_blocks.{i}.0" in key and f"output_blocks.{i}.0.op" not in key
799
+ ]
800
+ update_unet_resnet_ldm_to_diffusers(
801
+ resnets,
802
+ new_checkpoint,
803
+ unet_state_dict,
804
+ {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"},
805
+ )
806
+
807
+ attentions = [
808
+ key for key in output_blocks[i] if f"output_blocks.{i}.1" in key and f"output_blocks.{i}.1.conv" not in key
809
+ ]
810
+ if attentions:
811
+ update_unet_attention_ldm_to_diffusers(
812
+ attentions,
813
+ new_checkpoint,
814
+ unet_state_dict,
815
+ {"old": f"output_blocks.{i}.1", "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}"},
816
+ )
817
+
818
+ if f"output_blocks.{i}.1.conv.weight" in unet_state_dict:
819
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
820
+ f"output_blocks.{i}.1.conv.weight"
821
+ ]
822
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
823
+ f"output_blocks.{i}.1.conv.bias"
824
+ ]
825
+ if f"output_blocks.{i}.2.conv.weight" in unet_state_dict:
826
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
827
+ f"output_blocks.{i}.2.conv.weight"
828
+ ]
829
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
830
+ f"output_blocks.{i}.2.conv.bias"
831
+ ]
832
+
833
+ return new_checkpoint
834
+
835
+
836
+ def convert_controlnet_checkpoint(
837
+ checkpoint,
838
+ config,
839
+ ):
840
+ # Some controlnet ckpt files are distributed independently from the rest of the
841
+ # model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
842
+ if "time_embed.0.weight" in checkpoint:
843
+ controlnet_state_dict = checkpoint
844
+
845
+ else:
846
+ controlnet_state_dict = {}
847
+ keys = list(checkpoint.keys())
848
+ controlnet_key = LDM_CONTROLNET_KEY
849
+ for key in keys:
850
+ if key.startswith(controlnet_key):
851
+ controlnet_state_dict[key.replace(controlnet_key, "")] = checkpoint.pop(key)
852
+
853
+ new_checkpoint = {}
854
+ ldm_controlnet_keys = DIFFUSERS_TO_LDM_MAPPING["controlnet"]["layers"]
855
+ for diffusers_key, ldm_key in ldm_controlnet_keys.items():
856
+ if ldm_key not in controlnet_state_dict:
857
+ continue
858
+ new_checkpoint[diffusers_key] = controlnet_state_dict[ldm_key]
859
+
860
+ # Retrieves the keys for the input blocks only
861
+ num_input_blocks = len(
862
+ {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "input_blocks" in layer}
863
+ )
864
+ input_blocks = {
865
+ layer_id: [key for key in controlnet_state_dict if f"input_blocks.{layer_id}" in key]
866
+ for layer_id in range(num_input_blocks)
867
+ }
868
+
869
+ # Down blocks
870
+ for i in range(1, num_input_blocks):
871
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
872
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
873
+
874
+ resnets = [
875
+ key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
876
+ ]
877
+ update_unet_resnet_ldm_to_diffusers(
878
+ resnets,
879
+ new_checkpoint,
880
+ controlnet_state_dict,
881
+ {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
882
+ )
883
+
884
+ if f"input_blocks.{i}.0.op.weight" in controlnet_state_dict:
885
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = controlnet_state_dict.pop(
886
+ f"input_blocks.{i}.0.op.weight"
887
+ )
888
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = controlnet_state_dict.pop(
889
+ f"input_blocks.{i}.0.op.bias"
890
+ )
891
+
892
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
893
+ if attentions:
894
+ update_unet_attention_ldm_to_diffusers(
895
+ attentions,
896
+ new_checkpoint,
897
+ controlnet_state_dict,
898
+ {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
899
+ )
900
+
901
+ # controlnet down blocks
902
+ for i in range(num_input_blocks):
903
+ new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.weight")
904
+ new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.bias")
905
+
906
+ # Retrieves the keys for the middle blocks only
907
+ num_middle_blocks = len(
908
+ {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "middle_block" in layer}
909
+ )
910
+ middle_blocks = {
911
+ layer_id: [key for key in controlnet_state_dict if f"middle_block.{layer_id}" in key]
912
+ for layer_id in range(num_middle_blocks)
913
+ }
914
+ if middle_blocks:
915
+ resnet_0 = middle_blocks[0]
916
+ attentions = middle_blocks[1]
917
+ resnet_1 = middle_blocks[2]
918
+
919
+ update_unet_resnet_ldm_to_diffusers(
920
+ resnet_0,
921
+ new_checkpoint,
922
+ controlnet_state_dict,
923
+ mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"},
924
+ )
925
+ update_unet_resnet_ldm_to_diffusers(
926
+ resnet_1,
927
+ new_checkpoint,
928
+ controlnet_state_dict,
929
+ mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"},
930
+ )
931
+ update_unet_attention_ldm_to_diffusers(
932
+ attentions,
933
+ new_checkpoint,
934
+ controlnet_state_dict,
935
+ mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"},
936
+ )
937
+
938
+ # mid block
939
+ new_checkpoint["controlnet_mid_block.weight"] = controlnet_state_dict.pop("middle_block_out.0.weight")
940
+ new_checkpoint["controlnet_mid_block.bias"] = controlnet_state_dict.pop("middle_block_out.0.bias")
941
+
942
+ # controlnet cond embedding blocks
943
+ cond_embedding_blocks = {
944
+ ".".join(layer.split(".")[:2])
945
+ for layer in controlnet_state_dict
946
+ if "input_hint_block" in layer and ("input_hint_block.0" not in layer) and ("input_hint_block.14" not in layer)
947
+ }
948
+ num_cond_embedding_blocks = len(cond_embedding_blocks)
949
+
950
+ for idx in range(1, num_cond_embedding_blocks + 1):
951
+ diffusers_idx = idx - 1
952
+ cond_block_id = 2 * idx
953
+
954
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.weight"] = controlnet_state_dict.pop(
955
+ f"input_hint_block.{cond_block_id}.weight"
956
+ )
957
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.bias"] = controlnet_state_dict.pop(
958
+ f"input_hint_block.{cond_block_id}.bias"
959
+ )
960
+
961
+ return new_checkpoint
962
+
963
+
964
+ def create_diffusers_controlnet_model_from_ldm(
965
+ pipeline_class_name, original_config, checkpoint, upcast_attention=False, image_size=None, torch_dtype=None
966
+ ):
967
+ # import here to avoid circular imports
968
+ from ..models import ControlNetModel
969
+
970
+ image_size = set_image_size(pipeline_class_name, original_config, checkpoint, image_size=image_size)
971
+
972
+ diffusers_config = create_controlnet_diffusers_config(original_config, image_size=image_size)
973
+ diffusers_config["upcast_attention"] = upcast_attention
974
+
975
+ diffusers_format_controlnet_checkpoint = convert_controlnet_checkpoint(checkpoint, diffusers_config)
976
+
977
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
978
+ with ctx():
979
+ controlnet = ControlNetModel(**diffusers_config)
980
+
981
+ if is_accelerate_available():
982
+ unexpected_keys = load_model_dict_into_meta(
983
+ controlnet, diffusers_format_controlnet_checkpoint, dtype=torch_dtype
984
+ )
985
+ if controlnet._keys_to_ignore_on_load_unexpected is not None:
986
+ for pat in controlnet._keys_to_ignore_on_load_unexpected:
987
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
988
+
989
+ if len(unexpected_keys) > 0:
990
+ logger.warning(
991
+ f"Some weights of the model checkpoint were not used when initializing {controlnet.__name__}: \n {[', '.join(unexpected_keys)]}"
992
+ )
993
+ else:
994
+ controlnet.load_state_dict(diffusers_format_controlnet_checkpoint)
995
+
996
+ if torch_dtype is not None:
997
+ controlnet = controlnet.to(torch_dtype)
998
+
999
+ return {"controlnet": controlnet}
1000
+
1001
+
1002
+ def update_vae_resnet_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1003
+ for ldm_key in keys:
1004
+ diffusers_key = ldm_key.replace(mapping["old"], mapping["new"]).replace("nin_shortcut", "conv_shortcut")
1005
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1006
+
1007
+
1008
+ def update_vae_attentions_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1009
+ for ldm_key in keys:
1010
+ diffusers_key = (
1011
+ ldm_key.replace(mapping["old"], mapping["new"])
1012
+ .replace("norm.weight", "group_norm.weight")
1013
+ .replace("norm.bias", "group_norm.bias")
1014
+ .replace("q.weight", "to_q.weight")
1015
+ .replace("q.bias", "to_q.bias")
1016
+ .replace("k.weight", "to_k.weight")
1017
+ .replace("k.bias", "to_k.bias")
1018
+ .replace("v.weight", "to_v.weight")
1019
+ .replace("v.bias", "to_v.bias")
1020
+ .replace("proj_out.weight", "to_out.0.weight")
1021
+ .replace("proj_out.bias", "to_out.0.bias")
1022
+ )
1023
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1024
+
1025
+ # proj_attn.weight has to be converted from conv 1D to linear
1026
+ shape = new_checkpoint[diffusers_key].shape
1027
+
1028
+ if len(shape) == 3:
1029
+ new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0]
1030
+ elif len(shape) == 4:
1031
+ new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0, 0]
1032
+
1033
+
1034
+ def convert_ldm_vae_checkpoint(checkpoint, config):
1035
+ # extract state dict for VAE
1036
+ # remove the LDM_VAE_KEY prefix from the ldm checkpoint keys so that it is easier to map them to diffusers keys
1037
+ vae_state_dict = {}
1038
+ keys = list(checkpoint.keys())
1039
+ vae_key = LDM_VAE_KEY if any(k.startswith(LDM_VAE_KEY) for k in keys) else ""
1040
+ for key in keys:
1041
+ if key.startswith(vae_key):
1042
+ vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
1043
+
1044
+ new_checkpoint = {}
1045
+ vae_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["vae"]
1046
+ for diffusers_key, ldm_key in vae_diffusers_ldm_map.items():
1047
+ if ldm_key not in vae_state_dict:
1048
+ continue
1049
+ new_checkpoint[diffusers_key] = vae_state_dict[ldm_key]
1050
+
1051
+ # Retrieves the keys for the encoder down blocks only
1052
+ num_down_blocks = len(config["down_block_types"])
1053
+ down_blocks = {
1054
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
1055
+ }
1056
+
1057
+ for i in range(num_down_blocks):
1058
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
1059
+ update_vae_resnet_ldm_to_diffusers(
1060
+ resnets,
1061
+ new_checkpoint,
1062
+ vae_state_dict,
1063
+ mapping={"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"},
1064
+ )
1065
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
1066
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
1067
+ f"encoder.down.{i}.downsample.conv.weight"
1068
+ )
1069
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
1070
+ f"encoder.down.{i}.downsample.conv.bias"
1071
+ )
1072
+
1073
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
1074
+ num_mid_res_blocks = 2
1075
+ for i in range(1, num_mid_res_blocks + 1):
1076
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
1077
+ update_vae_resnet_ldm_to_diffusers(
1078
+ resnets,
1079
+ new_checkpoint,
1080
+ vae_state_dict,
1081
+ mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1082
+ )
1083
+
1084
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
1085
+ update_vae_attentions_ldm_to_diffusers(
1086
+ mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1087
+ )
1088
+
1089
+ # Retrieves the keys for the decoder up blocks only
1090
+ num_up_blocks = len(config["up_block_types"])
1091
+ up_blocks = {
1092
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
1093
+ }
1094
+
1095
+ for i in range(num_up_blocks):
1096
+ block_id = num_up_blocks - 1 - i
1097
+ resnets = [
1098
+ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
1099
+ ]
1100
+ update_vae_resnet_ldm_to_diffusers(
1101
+ resnets,
1102
+ new_checkpoint,
1103
+ vae_state_dict,
1104
+ mapping={"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"},
1105
+ )
1106
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
1107
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
1108
+ f"decoder.up.{block_id}.upsample.conv.weight"
1109
+ ]
1110
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
1111
+ f"decoder.up.{block_id}.upsample.conv.bias"
1112
+ ]
1113
+
1114
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
1115
+ num_mid_res_blocks = 2
1116
+ for i in range(1, num_mid_res_blocks + 1):
1117
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
1118
+ update_vae_resnet_ldm_to_diffusers(
1119
+ resnets,
1120
+ new_checkpoint,
1121
+ vae_state_dict,
1122
+ mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1123
+ )
1124
+
1125
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
1126
+ update_vae_attentions_ldm_to_diffusers(
1127
+ mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1128
+ )
1129
+ conv_attn_to_linear(new_checkpoint)
1130
+
1131
+ return new_checkpoint
1132
+
1133
+
1134
+ def create_text_encoder_from_ldm_clip_checkpoint(config_name, checkpoint, local_files_only=False, torch_dtype=None):
1135
+ try:
1136
+ config = CLIPTextConfig.from_pretrained(config_name, local_files_only=local_files_only)
1137
+ except Exception:
1138
+ raise ValueError(
1139
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: 'openai/clip-vit-large-patch14'."
1140
+ )
1141
+
1142
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1143
+ with ctx():
1144
+ text_model = CLIPTextModel(config)
1145
+
1146
+ keys = list(checkpoint.keys())
1147
+ text_model_dict = {}
1148
+
1149
+ remove_prefixes = LDM_CLIP_PREFIX_TO_REMOVE
1150
+
1151
+ for key in keys:
1152
+ for prefix in remove_prefixes:
1153
+ if key.startswith(prefix):
1154
+ diffusers_key = key.replace(prefix, "")
1155
+ text_model_dict[diffusers_key] = checkpoint[key]
1156
+
1157
+ if is_accelerate_available():
1158
+ unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1159
+ if text_model._keys_to_ignore_on_load_unexpected is not None:
1160
+ for pat in text_model._keys_to_ignore_on_load_unexpected:
1161
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1162
+
1163
+ if len(unexpected_keys) > 0:
1164
+ logger.warning(
1165
+ f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1166
+ )
1167
+ else:
1168
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1169
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
1170
+
1171
+ text_model.load_state_dict(text_model_dict)
1172
+
1173
+ if torch_dtype is not None:
1174
+ text_model = text_model.to(torch_dtype)
1175
+
1176
+ return text_model
1177
+
1178
+
1179
+ def create_text_encoder_from_open_clip_checkpoint(
1180
+ config_name,
1181
+ checkpoint,
1182
+ prefix="cond_stage_model.model.",
1183
+ has_projection=False,
1184
+ local_files_only=False,
1185
+ torch_dtype=None,
1186
+ **config_kwargs,
1187
+ ):
1188
+ try:
1189
+ config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs, local_files_only=local_files_only)
1190
+ except Exception:
1191
+ raise ValueError(
1192
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: '{config_name}'."
1193
+ )
1194
+
1195
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1196
+ with ctx():
1197
+ text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config)
1198
+
1199
+ text_model_dict = {}
1200
+ text_proj_key = prefix + "text_projection"
1201
+ text_proj_dim = (
1202
+ int(checkpoint[text_proj_key].shape[0]) if text_proj_key in checkpoint else LDM_OPEN_CLIP_TEXT_PROJECTION_DIM
1203
+ )
1204
+ text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids")
1205
+
1206
+ keys = list(checkpoint.keys())
1207
+ keys_to_ignore = SD_2_TEXT_ENCODER_KEYS_TO_IGNORE
1208
+
1209
+ openclip_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["layers"]
1210
+ for diffusers_key, ldm_key in openclip_diffusers_ldm_map.items():
1211
+ ldm_key = prefix + ldm_key
1212
+ if ldm_key not in checkpoint:
1213
+ continue
1214
+ if ldm_key in keys_to_ignore:
1215
+ continue
1216
+ if ldm_key.endswith("text_projection"):
1217
+ text_model_dict[diffusers_key] = checkpoint[ldm_key].T.contiguous()
1218
+ else:
1219
+ text_model_dict[diffusers_key] = checkpoint[ldm_key]
1220
+
1221
+ for key in keys:
1222
+ if key in keys_to_ignore:
1223
+ continue
1224
+
1225
+ if not key.startswith(prefix + "transformer."):
1226
+ continue
1227
+
1228
+ diffusers_key = key.replace(prefix + "transformer.", "")
1229
+ transformer_diffusers_to_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["transformer"]
1230
+ for new_key, old_key in transformer_diffusers_to_ldm_map.items():
1231
+ diffusers_key = (
1232
+ diffusers_key.replace(old_key, new_key).replace(".in_proj_weight", "").replace(".in_proj_bias", "")
1233
+ )
1234
+
1235
+ if key.endswith(".in_proj_weight"):
1236
+ weight_value = checkpoint[key]
1237
+
1238
+ text_model_dict[diffusers_key + ".q_proj.weight"] = weight_value[:text_proj_dim, :]
1239
+ text_model_dict[diffusers_key + ".k_proj.weight"] = weight_value[text_proj_dim : text_proj_dim * 2, :]
1240
+ text_model_dict[diffusers_key + ".v_proj.weight"] = weight_value[text_proj_dim * 2 :, :]
1241
+
1242
+ elif key.endswith(".in_proj_bias"):
1243
+ weight_value = checkpoint[key]
1244
+ text_model_dict[diffusers_key + ".q_proj.bias"] = weight_value[:text_proj_dim]
1245
+ text_model_dict[diffusers_key + ".k_proj.bias"] = weight_value[text_proj_dim : text_proj_dim * 2]
1246
+ text_model_dict[diffusers_key + ".v_proj.bias"] = weight_value[text_proj_dim * 2 :]
1247
+ else:
1248
+ text_model_dict[diffusers_key] = checkpoint[key]
1249
+
1250
+ if is_accelerate_available():
1251
+ unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1252
+ if text_model._keys_to_ignore_on_load_unexpected is not None:
1253
+ for pat in text_model._keys_to_ignore_on_load_unexpected:
1254
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1255
+
1256
+ if len(unexpected_keys) > 0:
1257
+ logger.warning(
1258
+ f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1259
+ )
1260
+
1261
+ else:
1262
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1263
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
1264
+
1265
+ text_model.load_state_dict(text_model_dict)
1266
+
1267
+ if torch_dtype is not None:
1268
+ text_model = text_model.to(torch_dtype)
1269
+
1270
+ return text_model
1271
+
1272
+
1273
+ def create_diffusers_unet_model_from_ldm(
1274
+ pipeline_class_name,
1275
+ original_config,
1276
+ checkpoint,
1277
+ num_in_channels=None,
1278
+ upcast_attention=None,
1279
+ extract_ema=False,
1280
+ image_size=None,
1281
+ torch_dtype=None,
1282
+ model_type=None,
1283
+ ):
1284
+ from ..models import UNet2DConditionModel
1285
+
1286
+ if num_in_channels is None:
1287
+ if pipeline_class_name in [
1288
+ "StableDiffusionInpaintPipeline",
1289
+ "StableDiffusionControlNetInpaintPipeline",
1290
+ "StableDiffusionXLInpaintPipeline",
1291
+ "StableDiffusionXLControlNetInpaintPipeline",
1292
+ ]:
1293
+ num_in_channels = 9
1294
+
1295
+ elif pipeline_class_name == "StableDiffusionUpscalePipeline":
1296
+ num_in_channels = 7
1297
+
1298
+ else:
1299
+ num_in_channels = 4
1300
+
1301
+ image_size = set_image_size(
1302
+ pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1303
+ )
1304
+ unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
1305
+ unet_config["in_channels"] = num_in_channels
1306
+ if upcast_attention is not None:
1307
+ unet_config["upcast_attention"] = upcast_attention
1308
+
1309
+ diffusers_format_unet_checkpoint = convert_ldm_unet_checkpoint(checkpoint, unet_config, extract_ema=extract_ema)
1310
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1311
+
1312
+ with ctx():
1313
+ unet = UNet2DConditionModel(**unet_config)
1314
+
1315
+ if is_accelerate_available():
1316
+ unexpected_keys = load_model_dict_into_meta(unet, diffusers_format_unet_checkpoint, dtype=torch_dtype)
1317
+ if unet._keys_to_ignore_on_load_unexpected is not None:
1318
+ for pat in unet._keys_to_ignore_on_load_unexpected:
1319
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1320
+
1321
+ if len(unexpected_keys) > 0:
1322
+ logger.warning(
1323
+ f"Some weights of the model checkpoint were not used when initializing {unet.__name__}: \n {[', '.join(unexpected_keys)]}"
1324
+ )
1325
+ else:
1326
+ unet.load_state_dict(diffusers_format_unet_checkpoint)
1327
+
1328
+ if torch_dtype is not None:
1329
+ unet = unet.to(torch_dtype)
1330
+
1331
+ return {"unet": unet}
1332
+
1333
+
1334
+ def create_diffusers_vae_model_from_ldm(
1335
+ pipeline_class_name,
1336
+ original_config,
1337
+ checkpoint,
1338
+ image_size=None,
1339
+ scaling_factor=None,
1340
+ torch_dtype=None,
1341
+ model_type=None,
1342
+ ):
1343
+ # import here to avoid circular imports
1344
+ from ..models import AutoencoderKL
1345
+
1346
+ image_size = set_image_size(
1347
+ pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1348
+ )
1349
+ model_type = infer_model_type(original_config, checkpoint, model_type)
1350
+
1351
+ if model_type == "Playground":
1352
+ edm_mean = (
1353
+ checkpoint["edm_mean"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_mean"].tolist()
1354
+ )
1355
+ edm_std = (
1356
+ checkpoint["edm_std"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_std"].tolist()
1357
+ )
1358
+ else:
1359
+ edm_mean = None
1360
+ edm_std = None
1361
+
1362
+ vae_config = create_vae_diffusers_config(
1363
+ original_config,
1364
+ image_size=image_size,
1365
+ scaling_factor=scaling_factor,
1366
+ latents_mean=edm_mean,
1367
+ latents_std=edm_std,
1368
+ )
1369
+ diffusers_format_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
1370
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1371
+
1372
+ with ctx():
1373
+ vae = AutoencoderKL(**vae_config)
1374
+
1375
+ if is_accelerate_available():
1376
+ unexpected_keys = load_model_dict_into_meta(vae, diffusers_format_vae_checkpoint, dtype=torch_dtype)
1377
+ if vae._keys_to_ignore_on_load_unexpected is not None:
1378
+ for pat in vae._keys_to_ignore_on_load_unexpected:
1379
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1380
+
1381
+ if len(unexpected_keys) > 0:
1382
+ logger.warning(
1383
+ f"Some weights of the model checkpoint were not used when initializing {vae.__name__}: \n {[', '.join(unexpected_keys)]}"
1384
+ )
1385
+ else:
1386
+ vae.load_state_dict(diffusers_format_vae_checkpoint)
1387
+
1388
+ if torch_dtype is not None:
1389
+ vae = vae.to(torch_dtype)
1390
+
1391
+ return {"vae": vae}
1392
+
1393
+
1394
+ def create_text_encoders_and_tokenizers_from_ldm(
1395
+ original_config,
1396
+ checkpoint,
1397
+ model_type=None,
1398
+ local_files_only=False,
1399
+ torch_dtype=None,
1400
+ ):
1401
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1402
+
1403
+ if model_type == "FrozenOpenCLIPEmbedder":
1404
+ config_name = "stabilityai/stable-diffusion-2"
1405
+ config_kwargs = {"subfolder": "text_encoder"}
1406
+
1407
+ try:
1408
+ text_encoder = create_text_encoder_from_open_clip_checkpoint(
1409
+ config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype, **config_kwargs
1410
+ )
1411
+ tokenizer = CLIPTokenizer.from_pretrained(
1412
+ config_name, subfolder="tokenizer", local_files_only=local_files_only
1413
+ )
1414
+ except Exception:
1415
+ raise ValueError(
1416
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder in the following path: '{config_name}'."
1417
+ )
1418
+ else:
1419
+ return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1420
+
1421
+ elif model_type == "FrozenCLIPEmbedder":
1422
+ try:
1423
+ config_name = "openai/clip-vit-large-patch14"
1424
+ text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1425
+ config_name,
1426
+ checkpoint,
1427
+ local_files_only=local_files_only,
1428
+ torch_dtype=torch_dtype,
1429
+ )
1430
+ tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1431
+
1432
+ except Exception:
1433
+ raise ValueError(
1434
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: '{config_name}'."
1435
+ )
1436
+ else:
1437
+ return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1438
+
1439
+ elif model_type == "SDXL-Refiner":
1440
+ config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1441
+ config_kwargs = {"projection_dim": 1280}
1442
+ prefix = "conditioner.embedders.0.model."
1443
+
1444
+ try:
1445
+ tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1446
+ text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1447
+ config_name,
1448
+ checkpoint,
1449
+ prefix=prefix,
1450
+ has_projection=True,
1451
+ local_files_only=local_files_only,
1452
+ torch_dtype=torch_dtype,
1453
+ **config_kwargs,
1454
+ )
1455
+ except Exception:
1456
+ raise ValueError(
1457
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1458
+ )
1459
+
1460
+ else:
1461
+ return {
1462
+ "text_encoder": None,
1463
+ "tokenizer": None,
1464
+ "tokenizer_2": tokenizer_2,
1465
+ "text_encoder_2": text_encoder_2,
1466
+ }
1467
+
1468
+ elif model_type in ["SDXL", "Playground"]:
1469
+ try:
1470
+ config_name = "openai/clip-vit-large-patch14"
1471
+ tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1472
+ text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1473
+ config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype
1474
+ )
1475
+
1476
+ except Exception:
1477
+ raise ValueError(
1478
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder and tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1479
+ )
1480
+
1481
+ try:
1482
+ config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1483
+ config_kwargs = {"projection_dim": 1280}
1484
+ prefix = "conditioner.embedders.1.model."
1485
+ tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1486
+ text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1487
+ config_name,
1488
+ checkpoint,
1489
+ prefix=prefix,
1490
+ has_projection=True,
1491
+ local_files_only=local_files_only,
1492
+ torch_dtype=torch_dtype,
1493
+ **config_kwargs,
1494
+ )
1495
+ except Exception:
1496
+ raise ValueError(
1497
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1498
+ )
1499
+
1500
+ return {
1501
+ "tokenizer": tokenizer,
1502
+ "text_encoder": text_encoder,
1503
+ "tokenizer_2": tokenizer_2,
1504
+ "text_encoder_2": text_encoder_2,
1505
+ }
1506
+
1507
+ return
1508
+
1509
+
1510
+ def create_scheduler_from_ldm(
1511
+ pipeline_class_name,
1512
+ original_config,
1513
+ checkpoint,
1514
+ prediction_type=None,
1515
+ scheduler_type="ddim",
1516
+ model_type=None,
1517
+ ):
1518
+ scheduler_config = get_default_scheduler_config()
1519
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1520
+
1521
+ global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
1522
+
1523
+ num_train_timesteps = getattr(original_config["model"]["params"], "timesteps", None) or 1000
1524
+ scheduler_config["num_train_timesteps"] = num_train_timesteps
1525
+
1526
+ if (
1527
+ "parameterization" in original_config["model"]["params"]
1528
+ and original_config["model"]["params"]["parameterization"] == "v"
1529
+ ):
1530
+ if prediction_type is None:
1531
+ # NOTE: For stable diffusion 2 base it is recommended to pass `prediction_type=="epsilon"`
1532
+ # as it relies on a brittle global step parameter here
1533
+ prediction_type = "epsilon" if global_step == 875000 else "v_prediction"
1534
+
1535
+ else:
1536
+ prediction_type = prediction_type or "epsilon"
1537
+
1538
+ scheduler_config["prediction_type"] = prediction_type
1539
+
1540
+ if model_type in ["SDXL", "SDXL-Refiner"]:
1541
+ scheduler_type = "euler"
1542
+ elif model_type == "Playground":
1543
+ scheduler_type = "edm_dpm_solver_multistep"
1544
+ else:
1545
+ beta_start = original_config["model"]["params"].get("linear_start", 0.02)
1546
+ beta_end = original_config["model"]["params"].get("linear_end", 0.085)
1547
+ scheduler_config["beta_start"] = beta_start
1548
+ scheduler_config["beta_end"] = beta_end
1549
+ scheduler_config["beta_schedule"] = "scaled_linear"
1550
+ scheduler_config["clip_sample"] = False
1551
+ scheduler_config["set_alpha_to_one"] = False
1552
+
1553
+ if scheduler_type == "pndm":
1554
+ scheduler_config["skip_prk_steps"] = True
1555
+ scheduler = PNDMScheduler.from_config(scheduler_config)
1556
+
1557
+ elif scheduler_type == "lms":
1558
+ scheduler = LMSDiscreteScheduler.from_config(scheduler_config)
1559
+
1560
+ elif scheduler_type == "heun":
1561
+ scheduler = HeunDiscreteScheduler.from_config(scheduler_config)
1562
+
1563
+ elif scheduler_type == "euler":
1564
+ scheduler = EulerDiscreteScheduler.from_config(scheduler_config)
1565
+
1566
+ elif scheduler_type == "euler-ancestral":
1567
+ scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler_config)
1568
+
1569
+ elif scheduler_type == "dpm":
1570
+ scheduler = DPMSolverMultistepScheduler.from_config(scheduler_config)
1571
+
1572
+ elif scheduler_type == "ddim":
1573
+ scheduler = DDIMScheduler.from_config(scheduler_config)
1574
+
1575
+ elif scheduler_type == "edm_dpm_solver_multistep":
1576
+ scheduler_config = {
1577
+ "algorithm_type": "dpmsolver++",
1578
+ "dynamic_thresholding_ratio": 0.995,
1579
+ "euler_at_final": False,
1580
+ "final_sigmas_type": "zero",
1581
+ "lower_order_final": True,
1582
+ "num_train_timesteps": 1000,
1583
+ "prediction_type": "epsilon",
1584
+ "rho": 7.0,
1585
+ "sample_max_value": 1.0,
1586
+ "sigma_data": 0.5,
1587
+ "sigma_max": 80.0,
1588
+ "sigma_min": 0.002,
1589
+ "solver_order": 2,
1590
+ "solver_type": "midpoint",
1591
+ "thresholding": False,
1592
+ }
1593
+ scheduler = EDMDPMSolverMultistepScheduler(**scheduler_config)
1594
+
1595
+ else:
1596
+ raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")
1597
+
1598
+ if pipeline_class_name == "StableDiffusionUpscalePipeline":
1599
+ scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", subfolder="scheduler")
1600
+ low_res_scheduler = DDPMScheduler.from_pretrained(
1601
+ "stabilityai/stable-diffusion-x4-upscaler", subfolder="low_res_scheduler"
1602
+ )
1603
+
1604
+ return {
1605
+ "scheduler": scheduler,
1606
+ "low_res_scheduler": low_res_scheduler,
1607
+ }
1608
+
1609
+ return {"scheduler": scheduler}
diffusers/loaders/textual_inversion.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Dict, List, Optional, Union
15
+
16
+ import safetensors
17
+ import torch
18
+ from huggingface_hub.utils import validate_hf_hub_args
19
+ from torch import nn
20
+
21
+ from ..models.modeling_utils import load_state_dict
22
+ from ..utils import _get_model_file, is_accelerate_available, is_transformers_available, logging
23
+
24
+
25
+ if is_transformers_available():
26
+ from transformers import PreTrainedModel, PreTrainedTokenizer
27
+
28
+ if is_accelerate_available():
29
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+ TEXT_INVERSION_NAME = "learned_embeds.bin"
34
+ TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
35
+
36
+
37
+ @validate_hf_hub_args
38
+ def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
39
+ cache_dir = kwargs.pop("cache_dir", None)
40
+ force_download = kwargs.pop("force_download", False)
41
+ resume_download = kwargs.pop("resume_download", None)
42
+ proxies = kwargs.pop("proxies", None)
43
+ local_files_only = kwargs.pop("local_files_only", None)
44
+ token = kwargs.pop("token", None)
45
+ revision = kwargs.pop("revision", None)
46
+ subfolder = kwargs.pop("subfolder", None)
47
+ weight_name = kwargs.pop("weight_name", None)
48
+ use_safetensors = kwargs.pop("use_safetensors", None)
49
+
50
+ allow_pickle = False
51
+ if use_safetensors is None:
52
+ use_safetensors = True
53
+ allow_pickle = True
54
+
55
+ user_agent = {
56
+ "file_type": "text_inversion",
57
+ "framework": "pytorch",
58
+ }
59
+ state_dicts = []
60
+ for pretrained_model_name_or_path in pretrained_model_name_or_paths:
61
+ if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
62
+ # 3.1. Load textual inversion file
63
+ model_file = None
64
+
65
+ # Let's first try to load .safetensors weights
66
+ if (use_safetensors and weight_name is None) or (
67
+ weight_name is not None and weight_name.endswith(".safetensors")
68
+ ):
69
+ try:
70
+ model_file = _get_model_file(
71
+ pretrained_model_name_or_path,
72
+ weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
73
+ cache_dir=cache_dir,
74
+ force_download=force_download,
75
+ resume_download=resume_download,
76
+ proxies=proxies,
77
+ local_files_only=local_files_only,
78
+ token=token,
79
+ revision=revision,
80
+ subfolder=subfolder,
81
+ user_agent=user_agent,
82
+ )
83
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
84
+ except Exception as e:
85
+ if not allow_pickle:
86
+ raise e
87
+
88
+ model_file = None
89
+
90
+ if model_file is None:
91
+ model_file = _get_model_file(
92
+ pretrained_model_name_or_path,
93
+ weights_name=weight_name or TEXT_INVERSION_NAME,
94
+ cache_dir=cache_dir,
95
+ force_download=force_download,
96
+ resume_download=resume_download,
97
+ proxies=proxies,
98
+ local_files_only=local_files_only,
99
+ token=token,
100
+ revision=revision,
101
+ subfolder=subfolder,
102
+ user_agent=user_agent,
103
+ )
104
+ state_dict = load_state_dict(model_file)
105
+ else:
106
+ state_dict = pretrained_model_name_or_path
107
+
108
+ state_dicts.append(state_dict)
109
+
110
+ return state_dicts
111
+
112
+
113
+ class TextualInversionLoaderMixin:
114
+ r"""
115
+ Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
116
+ """
117
+
118
+ def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
119
+ r"""
120
+ Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
121
+ be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
122
+ inversion token or if the textual inversion token is a single vector, the input prompt is returned.
123
+
124
+ Parameters:
125
+ prompt (`str` or list of `str`):
126
+ The prompt or prompts to guide the image generation.
127
+ tokenizer (`PreTrainedTokenizer`):
128
+ The tokenizer responsible for encoding the prompt into input tokens.
129
+
130
+ Returns:
131
+ `str` or list of `str`: The converted prompt
132
+ """
133
+ if not isinstance(prompt, List):
134
+ prompts = [prompt]
135
+ else:
136
+ prompts = prompt
137
+
138
+ prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
139
+
140
+ if not isinstance(prompt, List):
141
+ return prompts[0]
142
+
143
+ return prompts
144
+
145
+ def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
146
+ r"""
147
+ Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
148
+ to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
149
+ is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
150
+ inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
151
+
152
+ Parameters:
153
+ prompt (`str`):
154
+ The prompt to guide the image generation.
155
+ tokenizer (`PreTrainedTokenizer`):
156
+ The tokenizer responsible for encoding the prompt into input tokens.
157
+
158
+ Returns:
159
+ `str`: The converted prompt
160
+ """
161
+ tokens = tokenizer.tokenize(prompt)
162
+ unique_tokens = set(tokens)
163
+ for token in unique_tokens:
164
+ if token in tokenizer.added_tokens_encoder:
165
+ replacement = token
166
+ i = 1
167
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
168
+ replacement += f" {token}_{i}"
169
+ i += 1
170
+
171
+ prompt = prompt.replace(token, replacement)
172
+
173
+ return prompt
174
+
175
+ def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
176
+ if tokenizer is None:
177
+ raise ValueError(
178
+ f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
179
+ f" `{self.load_textual_inversion.__name__}`"
180
+ )
181
+
182
+ if text_encoder is None:
183
+ raise ValueError(
184
+ f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
185
+ f" `{self.load_textual_inversion.__name__}`"
186
+ )
187
+
188
+ if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
189
+ raise ValueError(
190
+ f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
191
+ f"Make sure both lists have the same length."
192
+ )
193